Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
try
ng update @angular/core @angular/cli
Then, just to sync material, run:
ng update @angular/material
I was also facing the same problem a few minutes before when I tried to run a flutter project in my C/(.something../.something../.something../.something....)
directory,
So I created a new folder in my E directory and started a new project there and when I run it ..... surprisingly it worked. I don't know why?
This was the message that I got after running in E: directory
Launching lib\main.dart on Lenovo K33a42 in debug mode...
Running Gradle task 'assembleDebug'...
Checking the license for package Android SDK Platform 28 in
C:\Users\Shankar\AppData\Local\Android\sdk\licenses
License for package Android SDK Platform 28 accepted.
Preparing "Install Android SDK Platform 28 (revision: 6)".
"Install Android SDK Platform 28 (revision: 6)" ready.
Installing Android SDK Platform 28 in
C:\Users\Shankar\AppData\Local\Android\sdk\platforms\android-28
"Install Android SDK Platform 28 (revision: 6)" complete.
"Install Android SDK Platform 28 (revision: 6)" finished.
Parameter format not correct -
v Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Debug service listening on ws://127.0.0.1:51105/5xCsT5vV62M=/ws
Syncing files to device Lenovo K33a42...
The meaning of this error is that the number of files monitored by the system has reached the limit!!
Result: The command executed failed! Or throw a warning (such as executing a react-native start VSCode)
Solution:
Modify the number of system monitoring files
Ubuntu
sudo gedit /etc/sysctl.conf
Add a line at the bottom
fs.inotify.max_user_watches=524288
Then save and exit!
sudo sysctl -p
to check it
Then it is solved!
Here's a custom hook that I use which I believe is more intuitive than using usePrevious
.
import { useRef, useEffect } from 'react'
// useTransition :: Array a => (a -> Void, a) -> Void
// |_______| |
// | |
// callback deps
//
// The useTransition hook is similar to the useEffect hook. It requires
// a callback function and an array of dependencies. Unlike the useEffect
// hook, the callback function is only called when the dependencies change.
// Hence, it's not called when the component mounts because there is no change
// in the dependencies. The callback function is supplied the previous array of
// dependencies which it can use to perform transition-based effects.
const useTransition = (callback, deps) => {
const func = useRef(null)
useEffect(() => {
func.current = callback
}, [callback])
const args = useRef(null)
useEffect(() => {
if (args.current !== null) func.current(...args.current)
args.current = deps
}, deps)
}
You'd use useTransition
as follows.
useTransition((prevRate, prevSendAmount, prevReceiveAmount) => {
if (sendAmount !== prevSendAmount || rate !== prevRate && sendAmount > 0) {
const newReceiveAmount = sendAmount * rate
// do something
} else {
const newSendAmount = receiveAmount / rate
// do something
}
}, [rate, sendAmount, receiveAmount])
Hope that helps.
When you use an async function like
async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
}
it returns a promise and useEffect
doesn't expect the callback function to return Promise, rather it expects that nothing is returned or a function is returned.
As a workaround for the warning you can use a self invoking async function.
useEffect(() => {
(async function() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
})();
}, []);
or to make it more cleaner you could define a function and then call it
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
};
fetchData();
}, []);
the second solution will make it easier to read and will help you write code to cancel previous requests if a new one is fired or save the latest request response in state
I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);
I was getting this error because I was importing a reusable component from an npm library and the versions of react-router-dom
did not match.
So make sure you use the same version in both places!
Check the latest edited XML file. It is the main Villian
I had once such error, I then checked the last xml file, ther was a line like android:layout_marginTop="."
I changed it to android:layout_marginTop="16dp"
.
That fixed the bug!
Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:
services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
{
options.YourProperty = yourValue;
})
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
Add this in composer.json
. Then dusk has to be installed explicitly in your project:
"extra": {
"laravel": {
"dont-discover": [
"laravel/dusk"
]
}
},
This did the magic for me. chmod -Rf 0777 storage
Use sudo npm install -g appium
.
We have solved the same error by following the below steps.
linux command for this type of error occurred then, first of all, check your php.ini file
If your php.ini file exists then in configuration file simply uncomment the extension:
;extension=php_pdo_mysql.dll
Else follow below steps
step1:php -v
step2: Install php mysql extension
php 7.0 sudo apt-get install php7.0-mysql
php 7.1 sudo apt-get install php7.1-mysql
php 7.2 sudo apt-get install php7.2-mysql
php 7.3 sudo apt-get install php7.3-mysql
step3: service apache2 restart
step4: php artisan migrate
Delete the table and remove its record from migration table.
After that you just run migration again:
php artisan migrate
If origin
points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example
$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.
Pulling once from the new origin
solves the problem:
$ git stash
$ git pull origin master
$ git stash pop
This one I found simple solutions:
row = myArray.map((cell, i) => {
if (i == myArray.length - 1) {
return <div> Test Data 1</div>;
}
return <div> Test Data 2</div>;
});
Copy .env.example
to .env
:
cp -a .env.example .env
Generate a key:
php artisan key:generate
Only then run:
php artisan serve
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
If you want to know the user version in your code, then you can use using app()
helper function
app()->version();
It is defined in this file ../src/Illuminate/Foundation/Application.php
Hope it will help :)
If this ()Unsupported method: BaseConfig.getApplicationIdSuffix Android Project is old and you have updated Android Studio, what I did was simply CLOSE PROJECT and ran it again. It solved the issue for me. Did not add any dependencies or whatever as described by other answers.
I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.
My problem on the Browser Console:
PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)
In my case my code fix was:
//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ProductosService {
productos:any[] = [];
cargando:boolean = true;
constructor( private http:Http) {
this.cargar_productos();
}
public cargar_productos(){
this.cargando = true;
this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
.subscribe( res => {
console.log(res.json());
this.cargando = false;
this.productos = res.json().productos; // Before this.productos = res.json();
});
}
}
I know this seems to be already answered, but I ran into a specific case, and I feel most answers miss the point.
The overflow:hidden
answers cover 90% of the cases. That's more or less the "sticky nav" scenario.
But the sticky behavior is best used within the height of a container. Think of a newsletter form in the right column of your website that scrolls down with the page. If your sticky element is the only child of the container, the container is the exact same size, and there's no room to scroll.
Your container needs to be the height you expect your element to scroll within. Which in my "right column" scenario is the height of the left column.
The best way to achieve this is to use display:table-cell
on the columns. If you can't, and are stuck with float:right
and such like I was, you'll have to either guess the left column height of compute it with Javascript.
if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:
$auth = new LoginController();
$auth->logout($request);
Complete File:
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
public function handle($request, Closure $next){
$user = Auth::guard()->user();
if( $user->role == 3 ) {
$auth = new LoginController();
$auth->logout($request);
header("Location: https://google.com");
die();
}
return $next($request);
}
}
In general, the error ValueError: Wrong number of items passed 3, placement implies 1
suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation
results['predictedY'] = predictedY
is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.
Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess()
is coming from (I'm guessing, but correct me and revise the question if this is wrong).
Now, you generate predicted values for y here:
predictedY, MSE = gp.predict(testX, eval_MSE = True)
However, as we can see from the documentation for GaussianProcess, predict()
returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets)
which, depending on testX
, could be (1000, 3)
(just to pick numbers). Thus, your predictedY
might have 3 columns.
If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.
You don't need to add --resource flag just type the following and laravel will create the whole desired resources
php artisan make:controller TodoController --model=todo
Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.
For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):
[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'
Simply replace nc -z -v -w1 localhost 443
with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.
For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.
steps to run local docker images in kubernetes
1. eval $(minikube -p minikube docker-env)
2. in the artifact file , under spec section -> containers
add
imagePullPolicy: IfNotPresent
or imagePullPolicy: Never
apiVersion: "v1"
kind: Pod
metadata:
name: web
labels:
name: web
app: demo
spec:
containers:
- name: web
image: web:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5000
name: http
protocol: TCP
3. then run kubectl create -f <filename>
You need to enable these extensions in the php.ini file
Before:
;extension=pdo_mysql
;extension=mysqli
;extension=pdo_sqlite
;extension=sqlite3
After:
extension=pdo_mysql
extension=mysqli
extension=pdo_sqlite
extension=sqlite3
It is advisable that you also activate the fileinfo extension, many packages require this.
The approached that work here was pass a second param with the key name (a short one):
$table->string('my_field_name')->unique(null,'key_name');
in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :
protected function redirectTo()
{
$user=Auth::user();
if($user->account_type == 1){
return '/admin';
}else{
return '/home';
}
}
to get the user information from my db I used "Illuminate\Support\Facades\Auth;".
This solution worked for me:
just add another class into your table element:
w-100 d-block d-md-table
so it would be :
<table class="table table-responsive w-100 d-block d-md-table">
for bootstrap 4 w-100
set the width to 100% d-block
(display: block) and d-md-table
(display: table on min-width: 576px)
In your adapter class make Integer variable as index and assign it to "0" (if you want to select 1st item by default, if not assign "-1").Then on your onBindViewHolder method,
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
holder.texttitle.setText(listTitle.get(position));
holder.itemView.setTag(listTitle.get(position));
holder.texttitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
index = position;
notifyDataSetChanged();
}
});
if (index == position)
holder.texttitle.setTextColor(mContext.getResources().getColor(R.color.selectedColor));
else
holder.texttitle.setTextColor(mContext.getResources().getColor(R.color.unSelectedColor));
}
Thats it and you are good to go.in If condition true section place your selected color or what ever you need, and else section place unselected color or what ever.
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
I got that error because I declared a variable and later wanted to
changed it's value using ngAfterViewInit
export class SomeComponent {
header: string;
}
to fix that I switched from
ngAfterViewInit() {
// change variable value here...
}
to
ngAfterContentInit() {
// change variable value here...
}
Here's Laravel 5.7, Laravel 5.8, Laravel 6.0, Laravel 7.0, and Laravel 8.0 (note a minor bc change in 6.0 to the email verification route).
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');
// Confirm Password (added in v6.2)
Route::get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm');
Route::post('password/confirm', 'Auth\ConfirmPasswordController@confirm');
// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); // v6.x
/* Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); // v5.x */
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
You can verify these routes here:
Just restart the IDE you are using, then it will work.
For example, I will create a table called users
as below and give a column named date
a default value NOW()
create table users_parent (
user_id varchar(50),
full_name varchar(240),
login_id_1 varchar(50),
date timestamp NOT NULL DEFAULT NOW()
);
Thanks
I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.
First, write below code in the component file.
constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
Now in your html image tag, you can write like this.
<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />
You can write as per your requirement instead of item.imageUrl
I got a reference from this site.dynamic urls. Hope this solution will help you :)
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
This works me to Angular 5.2.0
sarasa.Component.ts
import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@Component({
selector: 'app-sarasa',
templateUrl: './sarasa.component.html',
styleUrls: ['./sarasa.component.scss']
})
export class Sarasa implements OnInit {
@Input()
url: string = "https://www.mmlpqtpkasjdashdjahd.com";
urlSafe: SafeResourceUrl;
constructor(public sanitizer: DomSanitizer) { }
ngOnInit() {
this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
}
sarasa.Component.html
<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>
thats all folks!!!
The most elegant way to fix this: use pipe. Here is example (my blog). So you can then simply use url | safe
pipe to bypass the security.
<iframe [src]="url | safe"></iframe>
Refer to the documentation on npm for details: https://www.npmjs.com/package/safe-pipe
If you want to remove the routes cache on your server, remove this file:
bootstrap/cache/routes.php
And if you want to update it just run php artisan route:cache
and upload the bootstrap/cache/routes.php
to your server.
According to Dangerously Set innerHTML,
Improper use of the
innerHTML
can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name
dangerouslySetInnerHTML
is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key
__html
and your sanitized data as the value. Here is an example using the JSX syntax:
function createMarkup() {
return {
__html: 'First · Second' };
};
<div dangerouslySetInnerHTML={createMarkup()} />
Read more about it using below link:
documentation: React DOM Elements - dangerouslySetInnerHTML.
for php7 you can do that:
sudo apt-get install php-gd php-xml php7.0-mbstring
I changed my minSdkVersion to 20 and it worked for me. Check https://developer.android.com/studio/build/multidex#mdex-gradle for more details
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.
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
TL;DR: Check the path to your keystore.jks
file.
In my case, here's what happened:
I moved the project folder of my entire app to another location on my PC. Much later, I wanted to generate a signed apk file. Unknown to me, the default location of the path to my keystore.jks
had been reset to a wrong location and I had clicked okay. Since it could not find a keystore at the path I selected, I got that error.
The solution was to check whether the path to my keystore.jks
file was correct.
PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options
The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values
Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String
Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True
End Sub
Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:
uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)
If you encountered these errors due to opening the android studio with sudo command, then the solution is setting permission for the project folder. Run the command below.
sudo chmod -R 777 your_project_folder
clean and rebuild again your android project.
I could be because you might have not restarted PHP artisan since long
So After making DB changes and config:clear Tinker works fine
But to make browser refect the new DB connection you need to re-run
php artisan serve
One more scenario of this error:
locally
and run the command without npm run
First, it is important to notice this is a "general" terminal error (Even if you write hello bla.js
-or- wowowowow index.js
):
"hello world" example of this error:
-g
) ==> npm install typescript
.
https://docs.npmjs.com/downloading-and-installing-packages-locallytsc
commands available if you run npm run
inside your local project. For example: npm run tsc -v
:-or- install typescript globally (Like other answer mention).
With React-Native 0.56, the above method of changing Text.prototype.render
does not work anymore, so you have to use your own component, which can be done in one line!
MyText.js
export default props => <Text {...props} style={[{fontFamily: 'Helvetica'}, props.style]}>{props.children}</Text>
AnotherComponent.js
import Text from './MyText';
...
<Text>This will show in default font.</Text>
...
It will depend of your php version. Check it running:
php -version
Now, according to your current version, run:
sudo apt-get install php7.2-mysql
Can also occur if 'www-data' user has no access/write permissions on the folder: 'laravel-project-folder'/storage/framework/sessions/
Just Change in build.gradle file
classpath 'com.android.tools.build:gradle:1.3.0'
To
classpath 'com.android.tools.build:gradle:2.0.0'
Now GoTo
-> menu choose File
-> Invalidate Caches/Restart
...
Choose first option: Invalidate and Restart
Android Studio would restart.
After this, it should work normally.
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
This two commands work for me in my project
composer require laravel/ui --dev
Then
php artisan ui:auth
Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots
inside a shiny
app on shinyapps.io.
You can:
This leads to the following upper section inside the app.R
file:
dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')
A full example app can be found here.
I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me,
php artisan config:clear
and restart server
. Works like a charm!
You can generate a key
by the following command:
php artisan key:generate
The key will be written automatically in your .env
file.
APP_KEY=YOUR_GENERATED_KEY
If you want to see your key
after generation use --show
option
php artisan key:generate --show
Note: The .env
is a hidden file in your project folder.
import { readFileSync } from 'fs';
const file = readFileSync('./filename.txt', 'utf-8');
This worked for me.
You may need to wrap the second command in any function or you may need to declare inside a class without keyword const
.
I had a similar issue/error..
fixed it by moving
apply plugin: 'com.google.gms.google-services'
to the end of app level gradle file.
And updated the version of gms:play-services
and gms:play-services auth
As of Dec 2020, I had the same issue when installing python v 3.8.6
via pyenv
. So, I started by:
brew install pyenv
brew install xz
pyenv install 3.8.6
pick the required versionpyenv global 3.8.6
make this version as globalpython -m pip install -U pip
to upgrade pippip install virtualenv
After that, I initialized my new env, installed pandas
via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!
Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.
It seems to me the simplest way to do it with Selenium is to intercept the XHR that sends back the browser fingerprint.
But since this is a Selenium-only problem, its better just to use something else. Selenium is supposed to make things like this easier, not way harder.
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
The same result can be achieved using Lodash.
var result1 = [_x000D_
{id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
{id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
{id:3, name:'Peter', type:'user', username:'pete'},_x000D_
{id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
{id:2, name:'John', email:'[email protected]'},_x000D_
{id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var result3 = _(result1) _x000D_
.differenceBy(result2, 'id', 'name')_x000D_
.map(_.partial(_.pick, _, 'id', 'name'))_x000D_
.value();_x000D_
_x000D_
console.log(result3);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).
Lastly, you have to map the result in order to "omit" the undesired properties of the object.
Hope it helps.
try this out:
font-family: 'SF Pro Text',-apple-system,BlinkMacSystemFont,Roboto,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol';
It worked for me. ;) Do upvote if it works.
JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage
var obj = {"nissan": "sentra", "color": "green"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
var obj = JSON.parse(localStorage.getItem('myStorage'));
Append a semicolon to the following line to fix the issue.
font-family: Arial, Helvetica, sans-serif;
In case of using psr-0 , check the class name does not contain underscore .
The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.
//This did not work for me
Date.from(java.time.ZonedDateTime.now().toInstant());
I have come up with two alternative ways to get the correct Date from a ZonedDateTime.
Say you have this ZonedDateTime for Hawaii
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10
or for UTC as asked originally
Instant zulu = Instant.now(); // GMT, UTC+0
ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));
Alternative 1
We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity
Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());
Alternative 2
We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.
ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now());
long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
Date date2 = new Date(zonedMillis);
Try changing the port number in your project?
Project Properties ? Web ? Servers ? Project Url:
Don't forget to click Create Virtual Directory
, or reply "Yes" to the prompt for creating virtual directory after you change your port number! (Thanks Connor)
Note: I'm a little reluctant to post this as an answer, as I have no idea what the issue is or what caused it, but I had a similar issue, and changing the port number did the trick for me. I'm only posting this per the suggestion in the comments that this worked for someone else as well.
In my case, it seemed like something was conflicting with the specific port number I was using, so I changed to a different one, and my site popped right back up! I'm not sure what that means for the old port number, or if I'll ever be able to use it again. Maybe someone more knowledgeable than myself can chime in on this.
This answer is for react-router-4. You can wrap all the routes in Switch block, which functions just like the switch-case expression, and renders the component with the first matched route. eg)
<Switch>
<Route path="/" component={home}/>
<Route path="/home" component={home}/>
<Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>
When to use exact
Without exact:
<Route path='/home'
component = {Home} />
{/* This will also work for cases like https://<domain>/home/anyvalue. */}
With exact:
<Route exact path='/home'
component = {Home} />
{/*
This will NOT work for cases like https://<domain>/home/anyvalue.
Only for https://<url>/home and https://<domain>/home/
*/}
Now if you are accepting routing parameters, and if it turns out incorrect, you can handle it in the target component itself. eg)
<Route exact path='/user/:email'
render = { (props) => <ProfilePage {...props} user={this.state.user} />} />
Now in ProfilePage.js
if(this.props.match.params.email != desiredValue)
{
<Redirect to="/notFound" component = {GenericNotFound}/>
//Or you can show some other component here itself.
}
For more details you can go through this code:
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
If your data changes a lot, you can use
mAdapter.notifyItemRangeChanged(0, yourData.size());
or some single items in your data set changes, your can use
mAdapter.notifyItemChanged(pos);
For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged()
.
You can call an Artisan command outside the CLI.
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('cache:clear');
// return what you want
});
You can check the official doc here http://laravel.com/docs/5.0/artisan#calling-commands-outside-of-cli
Update
There is no way to delete the view cache. Neither php artisan cache:clear
does that.
If you really want to clear the view cache, I think you have to write your own artisan
command and call it as I said before, or entirely skip the artisan
path and clear the view cache in some class that you call from a controller or a route.
But, my real question is do you really need to clear the view cache? In a project I'm working on now, I have almost 100 cached views and they weight less then 1 Mb, while my vendor
directory is > 40 Mb. I don't think view cache is a real bottleneck in disk usage and never had a real need to clear it.
As for the application cache, it is stored in the storage/framework/cache
directory, but only if you configured the file
driver in config/cache.php
. You can choose many different drivers, such as Redis or Memcached, to improve performances over a file-based cache.
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.
Confirmed that this is related to the Spark build against Hadoop 2.60. Just installed Spark 1.4.0 "Pre built for Hadoop 2.4 and later" (instead of Hadoop 2.6). And the code now works OK.
sc.textFile("s3n://bucketname/Filename")
now raises another error:
java.lang.IllegalArgumentException: AWS Access Key ID and Secret Access Key must be specified as the username or password (respectively) of a s3n URL, or by setting the fs.s3n.awsAccessKeyId or fs.s3n.awsSecretAccessKey properties (respectively).
The code below uses the S3 URL format to show that Spark can read S3 file. Using dev machine (no Hadoop libs).
scala> val lyrics = sc.textFile("s3n://MyAccessKeyID:MySecretKey@zpub01/SafeAndSound_Lyrics.txt")
lyrics: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[3] at textFile at <console>:21
scala> lyrics.count
res1: Long = 9
Even Better: the code above with AWS credentials inline in the S3N URI will break if the AWS Secret Key has a forward "/". Configuring AWS Credentials in SparkContext will fix it. Code works whether the S3 file is public or private.
sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "BLABLA")
sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "....") // can contain "/"
val myRDD = sc.textFile("s3n://myBucket/MyFilePattern")
myRDD.count
Just increasing max_connections
is bad idea. You need to increase shared_buffers
and kernel.shmmax
as well.
Considerations
max_connections
determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.
Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.
Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.
A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.
How to increase max connections
1. Increase max_connection
and shared_buffers
in /var/lib/pgsql/{version_number}/data/postgresql.conf
change
max_connections = 100
shared_buffers = 24MB
to
max_connections = 300
shared_buffers = 80MB
The shared_buffers
configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.
2. Change kernel.shmmax
You would need to increase kernel max segment size to be slightly larger
than the shared_buffers
.
In file /etc/sysctl.conf
set the parameter as shown below. It will take effect when postgresql
reboots (The following line makes the kernel max to 96Mb
)
kernel.shmmax=100663296
References
I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:
enum MyError: ErrorType { case ErrorA, ErrorB }
func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }
do {
try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }
The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:
enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }
we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
in laravel 5 first we need to create migration and then run the migration
Step 1.
php artisan make:migration create_users_table --create=users
Step 2.
php artisan migrate
For me, the mistake was forgetting to put FTP into binary mode before uploading the font files.
Edit
You can test for this by uploading other types of binary data like images. If they also fail to display, then this may be your issue.
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
Migrate tables one by one.
Change the batch number of the migration you want to rollback to the highest.
Run migrate:rollback.
May not be the most comfortable way to deal with larger projects.
In windows OS, you can open command prompt, change directory to your project directory.
Example,
My project directory
E:\xampp\htdocs\my_project
You can type into your Command prompt like this (hit enter each line):
E:
cd xampp\htdocs\my_project
Then you can type,
copy .env.example .env
If you are using Linux, you can type cp, instead of copy
For latest laravel version also check your version because I was also facing this error but after update latest php version, I got rid from this error.
Got it! Log in as root and grant homestead@localhost the rights to everything.
From your terminal:
$ homestead ssh
$ mysql -u root -p
Enter password: secret
mysql> grant all privileges on *.* to 'homestead'@'localhost' identified by 'secret';
Query OK, 0 rows affected (0.00 sec)
exit
Now homesteads regular user has access to all of your tables, and as such, should be able to run things like migrations.
It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.
You can refer to the Registry v2 API to fetch the manifest of image.
GET /v2/<name>/manifests/<reference>
Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.
There is a simple script for handling above cases that will be continuously maintained.
The Interface of Postman is changing acccording to the updates.
So You can get full information about postman can get Here.
Add "barryvdh/laravel-cors": "^0.7.3"
at the end of require
array inside composer.json
Save composer.json and run composer update
You are done !
please try this below command :
sudo php artisan cache:clear
sudo php artisan view:clear
sudo php artisan config:cache
Try to change the rpc_address
to point to the node's IP instead of 0.0.0.0 and specify the IP while connecting to the cqlsh, as if the IP is 10.0.1.34 and the rpc_port
left to the default value 9160 then the following should work:
cqlsh 10.0.1.34 9160
Or:
cqlsh 10.0.1.34
Also make sure that start_rpc is set to true in /etc/cassandra/cassandra.yaml configuration file.
view = MyCustomView(frame: CGRectZero)
In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.
You're already doing it!
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
The getDirty()
method simply compares the current attributes with a copy saved in original
when the model is created. This is done in the syncOriginal()
method:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
If you want to check if the model is dirty just call isDirty()
:
if($product->isDirty()){
// changes have been made
}
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
In Laravel the default environment is always production.
What you need to do is to specify correct hostname in bootstrap/start.php
for your enviroments eg.:
/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/
$env = $app->detectEnvironment(array(
'local' => array('homestead'),
'profile_1' => array('hostname_for_profile_1')
));
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
Smoke testing came from the hardware environment where testing should be done to check whether the development of a new piece of hardware causes no fire and smoke for the first time.
In the software environment, smoke testing is done to verify whether we can consider for further testing the functionality which is newly built.
A subset of regression test cases are executed after receiving a functionality or code with small or minor changes in the functionality or code, to check whether it resolved the issues or software bugs and no other software bug is introduced by the new changes.
Smoke testing is used to test all areas of the application without going into too deep.
A smoke test always use an automated test or a written set of tests. It is always scripted.
Smoke testing is designed to include every part of the application in a not thorough or detailed way.
Smoke testing always ensures whether the most crucial functions of a program are working, but not bothering with finer details.
Sanity testing is a narrow test that focuses on one or a few areas of functionality, but not thoroughly or in-depth.
A sanity test is usually unscripted.
Sanity testing is used to ensure that after a minor change a small part of the application is still working.
Sanity testing is a cursory testing, which is performed to prove that the application is functioning according to the specifications. This level of testing is a subset of regression testing.
Hope these points help you to understand the difference between smoke testing and sanity testing.
Which OS you are using ?
For Windows :
Go to Command Prompt
set path to www/{ur project}
For me : www/laravel5
Then type this command : composer install
It will automatically install all dependency in vendor/
I had the same error in Laravel 5.2, turns out the namespace is incorrect in the model class definition.
I created my model using the command:
php artisan make:model myModel
By default, Laravel 5 creates the model under App
folder, but if you were to move the model to another folder like I did, you must change the the namespace inside the model definition too:
namespace App\ModelFolder;
To include the folder name when creating the model you could use (don't forget to use double back slashes):
php artisan make:model ModelFolder\\myModel
Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.
Remove them all.
The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.
If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.
How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat
Im Maven Project:-
add follwing line in pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${default.javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${default.javax.servlet.jsp.version}</version>
<scope>provided</scope>
</dependency>
It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.
After doing a lot of things, I upgraded pip
, setuptools
and virtualenv
.
python -m pip install -U pip
pip install -U setuptools
pip install -U virtualenv
I did steps 1, 2 in my virtual environment as well as globally.
Next, I installed the package through pip
and it worked.
I have a file called NewsArticle.txt on my Desktop.
In Spark, I typed:
val textFile= sc.textFile(“file:///C:/Users/582767/Desktop/NewsArticle.txt”)
I needed to change all the \ to / character for the filepath.
To test if it worked, I typed:
textFile.foreach(println)
I'm running Windows 7 and I don't have Hadoop installed.
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*
Or you can simply required the package using composer...
composer require doctrine/dbal
Source: https://laravel.com/docs/5.0/schema#renaming-columns
Note: Use make:migration and not migrate:make for Laravel 5.x
In my case, I named a column name type
and tried to set its value as UNPREPARED
. And I got an error message like this:
Caused by: api_1 | NameError: uninitialized constant UNPREPARED
In rails, column type
is reserved:
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information
I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.
In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "customerEntityManager",
transactionManagerRef = "customerTransactionManager",
basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {
The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:
em.setPackagesToScan("com.mm.boot.multidb.model.customer");
Also the injection of proper EntityManagerFactory did not work. It should be:
@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
}
The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.
The last thing I have done was to disable to automatic configuration of JpaRepositories:
@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)
And with all fixes the application starts as you probably expect!
My Database table has mismatch column name with the Java Object (@Entity) which leads to throw the above exception.
By updating the table with appropriate column name resolves this issue.
This error happens because you didn't install composer on your project.
run composer install
command in your project path.
I'm running the very latest Laravel 5 dev release, and if you've changed the namespace you'll need to call your seed class like this:
$this->call('\todoparrot\TodolistTableSeeder');
Obviously you'll need to replace todoparrot
with your designated namespace. Otherwise I receive the same error indicated in the original question.
First check the migrations table in your DB and sure that your migration files in database folder in your project is equal to this table data. Sometimes if you create migration files by manual appear this error when run migrate command in composer.
I'm sure there are other ways to accomplish this, but one solution would be to use join
through the Query Builder.
If you have tables set up something like this:
users
id
...
friends
id
user_id
friend_id
...
votes, comments and status_updates (3 tables)
id
user_id
....
In your User model:
class User extends Eloquent {
public function friends()
{
return $this->hasMany('Friend');
}
}
In your Friend model:
class Friend extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:
$user = User::find(1);
$friends_votes = $user->friends()
->with('user') // bring along details of the friend
->join('votes', 'votes.user_id', '=', 'friends.friend_id')
->get(['votes.*']); // exclude extra details from friends table
Run the same join
for the comments
and status_updates
tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.
Edit
To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany
relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where
instead:
$friends_votes =
DB::table('friends')->where('friends.user_id','1')
->join('votes', 'votes.user_id', '=', 'friends.friend_id');
$friends_comments =
DB::table('friends')->where('friends.user_id','1')
->join('comments', 'comments.user_id', '=', 'friends.friend_id');
$friends_status_updates =
DB::table('status_updates')->where('status_updates.user_id','1')
->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');
$friends_events =
$friends_votes
->union($friends_comments)
->union($friends_status_updates)
->get();
At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.
x = [10000.21, 22000.32, 10120.54]
Perhaps make a list (comprehension) for the labels, and then apply them "manually".
xlables = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:
"Cannot install at this time".
Finally Zillan's link helped me to get apple documentation. So, check:
ax.init.itunes.apple.com
is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load). As soon as I changed the proxy it installed completely. Hope it will help someone.
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.
From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.
I had no problems with this until recently.
Now I had to move the suite's xml test file into the root of the project I was testing.
It may be that there is a setting to point at the classes I am testing, but I have not found it.
Why relying on objc runtime? I don't get the point. By using something like the following you will achieve almost the identical behaviour of a stored property, by using only a pure Swift approach:
extension UIViewController {
private static var _myComputedProperty = [String:Bool]()
var myComputedProperty:Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIViewController._myComputedProperty[tmpAddress] ?? false
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIViewController._myComputedProperty[tmpAddress] = newValue
}
}
}
For those wanting to use Postgresql on OpenSuse (and co), try the following:
zypper --no-refresh in php5-pgsql
Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:
[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0
The code above will display € 62.123 as "€ 62 K".
In Laravel 6 there is a channel called 'stderr'. See config/logging.php
:
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
In your controller:
use Illuminate\Support\Facades\Log;
Log::channel('stderr')->info('Something happened!');
Assuming timestamp is the index of the data frame, you can just do the following:
hours = sales.index.hour
If you want to add that to your sales data frame, just do:
import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)
Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:
hours = sales['date'].hour
Edit2:
If you want to adjust a column in your data frame you have to include dt
:
sales['datehour'] = sales['date'].dt.hour
November 2020 :
As I experienced , these meta tags are required and effect on what you see on shared link in Whatsapp and WhatsApp-thumbnail
:
<head>
<meta content='myTitle' property='og:title'/>
<meta content="myDescription" property="og:Description"/>
<meta property="og:type" content= "website" />
<meta property="og:image" itemprop="image primaryImageOfPage" content="https://i.ibb.co/1GRpwND/600px-Approve-icon-svg.png" />
</head>
and inside <body>
:
<a href="https://wa.me/?text=https://myaddress.blogspot.com/2020/11/try-16.html" target="_blank" rel="nofollow">Hello whatsApp</a>
More explanation :
1- Suppose you have <meta content='example.com/page1' property='og:url'/>
and inside body you refer to <a href="https://wa.me/?text=example.com/page2" >Hello whatsApp</a>
, the og:image
and og:description
of page example.com/page2
wil be rendered on whatsApp as you referred on your link in body (maybe obvious).
2-When you add/change
any open graph tags such as og:description
, and again you click your <a></a>
tag on your page/body, what you see on WhatsApp doesn't change unless you change the href="I am a new URL"
of your <a></a>
tag or clear cache of WhatsApp !!
3-I tried Png/jpg
images, all less than 300 kb in size and all bigger than 300*300 in pixels, and image content was a https
or a http
url, the above code supports both of them ( No need to og:image:secure_url
).
4-Each time you add/change og
contents, to have a thumbnail on WhatsApp, the changes doesn't affect on first try !! and successful on second try. Very strange !
In brief sense:
Partition Key is nothing but identification for a row, that identification most of the times is the single column (called Primary Key) sometimes a combination of multiple columns (called Composite Partition Key).
Cluster key is nothing but Indexing & Sorting. Cluster keys depend on few things:
What columns you use in where clause except primary key columns.
If you have very large records then on what concern I can divide the date for easy management. Example, I have data of 1million a county population records. So for easy management, I cluster data based on state and after pincode and so on.
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 proposal without ugly "foreach" control structures is
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$allFiles = array_filter(iterator_to_array($iterator), function($file) {
return $file->isFile();
});
You may only want to extract the filepath, which you can do so by:
array_keys($allFiles);
Still 4 lines of code, but more straight forward than using a loop or something.
Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.
As a different approach to the other answer, instead of indicating the user upon image creation on the Dockerfile, you can do so via command-line on a particular container as a per-command basis.
With docker exec
, use --user
to specify which user account the interactive terminal will use (the container should be running and the user has to exist in the containerized system):
docker exec -it --user [username] [container] bash
See https://docs.docker.com/engine/reference/commandline/exec/
Assuming you are simply trying to get a sklearn.preprocessing.LabelEncoder()
object that can be used to represent your columns, all you have to do is:
le.fit(df.columns)
In the above code you will have a unique number corresponding to each column.
More precisely, you will have a 1:1 mapping of df.columns
to le.transform(df.columns.get_values())
. To get a column's encoding, simply pass it to le.transform(...)
. As an example, the following will get the encoding for each column:
le.transform(df.columns.get_values())
Assuming you want to create a sklearn.preprocessing.LabelEncoder()
object for all of your row labels you can do the following:
le.fit([y for x in df.get_values() for y in x])
In this case, you most likely have non-unique row labels (as shown in your question). To see what classes the encoder created you can do le.classes_
. You'll note that this should have the same elements as in set(y for x in df.get_values() for y in x)
. Once again to convert a row label to an encoded label use le.transform(...)
. As an example, if you want to retrieve the label for the first column in the df.columns
array and the first row, you could do this:
le.transform([df.get_value(0, df.columns[0])])
The question you had in your comment is a bit more complicated, but can still be accomplished:
le.fit([str(z) for z in set((x[0], y) for x in df.iteritems() for y in x[1])])
The above code does the following:
LabelEncoder
class not supporting tuples as a class name.LabelEncoder
.Now to use this new model it's a bit more complicated. Assuming we want to extract the representation for the same item we looked up in the previous example (the first column in df.columns and the first row), we can do this:
le.transform([str((df.columns[0], df.get_value(0, df.columns[0])))])
Remember that each lookup is now a string representation of a tuple that contains the (column, row).
If you renamed the folder containing your Homestead project, you'll get this error. Visit your Homestead.yaml
file and update any references to point to the renamed folder, then do vagrant up
(etc.) again
Right-Click on your project -> Properties -> Deployment Assembly.
On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.
'Project and External Dependencies' will have all the spring related jars deployed along with your application
Unable to process Jar entry [module-info.class] from Jar [jar:file:/xxxxxxxx/lombok-1.18.4.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
1.update and append below argument in <root or instance tomcat folder>/conf/catalina.properties
org.apache.catalina.startup.ContextConfig.jarsToSkip=...,lombok-1.18.4.jar
2.clean and deploy the to-be-pulish project.
@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.
We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.
CriteriaQuery
instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.EntityManager
to create a Query
instance for those (which effectively triggers query syntax validation).Metamodel
for meta-data about the domain types handled to prepare is-new checks etc.All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).
If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:
This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext
usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager
or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.
Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager
injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager
-> CriteriaBuilder
, CriteriaQuery
etc.) so that you end up with mocks returning mocks and so on.
This is what I achieved, but had to set width, and it cannot be percentual.
.trunc{_x000D_
width:250px; _x000D_
white-space: nowrap; _x000D_
overflow: hidden; _x000D_
text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
_x000D_
<tr>_x000D_
<td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
<td>_x000D_
<div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/
use Illuminate\Database\Eloquent\Builder;
$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
$query = $query->where('orders.customer_id', 'NULL')
});
$query = $query->get();
So simple !!!
if your first create 'priorities'
migration file, Laravel first run 'priorities'
while 'users'
table does not exist.
how it can add relation to a table that does not exist!.
Solution: pull out foreign key codes from 'priorities'
table. your migration file should be like this:
and add to a new migration file, here its name is create_prioritiesForeignKey_table
and add these codes:
public function up()
{
Schema::table('priorities', function (Blueprint $table) {
$table->foreign('user_id')
->references('id')
->on('users');
});
}
Capitalization matters as well! Inside my directive, I tried specifying:
templateUrl: 'Views/mytemplate'
and got the "more than once" warning. The warning disappeared when I changed it to:
templateUrl: 'views/mytemplate'
Correct me, but I think this happened because page that I placed the directive on was under "views" and not "Views" in the route config function.
I was also getting the same error --> "[PDOException]
could not find driver "
After that I used many commands but not didn't get any help
Finally I used the following command, which solved my problem.
sudo apt-get install php5-sqlite
simply
the error means that your models has changes and is not in Sync with DB ,so
go to package manager console ,
add-migration foo2
this will give a hint of what is causing the issue ,
may be you removed something or in my case I remove a data annotation .
from there you can get the change and hopefully reverse it in your model.
after that delete foo2 .
To make all fields fillable, just declare on your class:
protected $guarded = array();
This will enable you to call fill method without declare each field.
Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
You need to print the result of the getText()
. You're currently printing the object TxtBoxContent
.
getText()
will only get the inner text of an element. To get the value, you need to use getAttribute()
.
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
you can use instead of click :
$('#whatever').on('touchstart click', function(){ /* do something... */ });
This solution is for windows:
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
I have the same problem while integrating the Facebook SDK for login.
I'm suggesting below approach for development mode > you can test all things if you are login with same account, which is used for 'developers.facebook.com' and if you want to use another accounts then you need to add Roles for that particular app, for that you can add developer or testers by using fid or facebook username.
Eg: - Select the particular app > Roles and then add developer or testers.
You'll get this error as well if you are verifying that an extension method of an interface is called.
For example if you are mocking:
var mockValidator = new Mock<IValidator<Foo>>();
mockValidator
.Verify(validator => validator.ValidateAndThrow(foo, null));
You will get the same exception because .ValidateAndThrow()
is an extension on the IValidator<T>
interface.
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet = null)...
Download it from here and extract LatoOFL.rar
then go to TTF and open this font-face-generator click at Choose File
choose font which you want to use and click at generate then download it and then go html
file open it and you see the code like this
@font-face {
font-family: "Lato Black";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body{
font-family: "Lato Black";
direction: ltr;
}
change the src code and give the url where your this font directory placed, now you can use it at your website...
If you don't want to download it use this
<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />
you could also solved it by adding lazy=false into into your *.hbm.xml file or you can init your object in Hibernate.init(Object) when you get object from db
It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).
To create HTML in email template that is emailer/newsletter, padding/margin is not supporting on email clients. You can take 1x1 size of blank gif image and use it.
<tr>
<td align="left" valign="top" style="background-color:#7d9aaa;">
<table width="640" cellspacing="0" cellpadding="0" border="0">
<tr>
<td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10" alt="" /></td>
</tr>
<tr>
<td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1" alt="" /></td>
<td align="right" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;"><a href="#" style="color:#ffffff; text-decoration:none; cursor:pointer;" target="_blank">Order Confirmation</a></font></td>
<td align="left" valign="top" width="200"><img style="display:block;" src="images/spacer.gif" width="200" height="1" alt="" /></td>
<td align="left" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;">Your Confirmation Number is 260556</font></td>
<td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1" alt="" /></td>
</tr>
<tr>
<td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10" alt="" /></td>
</tr>
</table>
</td>
</tr>
It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.
There are windows installers for MySQLdb avaialable for both 32 and 64 bit, supporting Python from 2.6 to 3.4. Check here.
We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed
, Memory usage
, Syntax
and Features
.
My intent is to cover each one of these as clearly as possible from data.table perspective.
Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.
The data.table syntax is consistent in its form - DT[i, j, by]
. To keep i
, j
and by
together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.
Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas
. See also updated benchmarks, which include Spark
and pydatatable
as well.
On benchmarks, it would be great to cover these remaining aspects as well:
Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z]
type operations.
Benchmark other operations such as update and joins.
Also benchmark memory footprint for each operation in addition to runtime.
Operations involving filter()
or slice()
in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.
Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.
data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).
# sub-assign by reference, updates 'y' in-place
DT[x >= 1L, y := NA]
But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):
# copies the entire 'y' column
ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.
Therefore we are working towards exporting shallow()
function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:
foo <- function(DT) {
DT = shallow(DT) ## shallow copy DT
DT[, newcol := 1L] ## does not affect the original DT
DT[x > 2L, newcol := 2L] ## no need to copy (internally), as this column exists only in shallow copied DT
DT[x > 2L, x := 3L] ## have to copy (like base R / dplyr does always); otherwise original DT will
## also get modified.
}
By not using shallow()
, the old functionality is retained:
bar <- function(DT) {
DT[, newcol := 1L] ## old behaviour, original DT gets updated by reference
DT[x > 2L, x := 3L] ## old behaviour, update column x in original DT.
}
By creating a shallow copy using shallow()
, we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.
Also, once
shallow()
is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.But it will still lack many features that data.table provides, including (sub)-assignment by reference.
Aggregate while joining:
Suppose you have two data.tables as follows:
DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
# x y z
# 1: 1 a 1
# 2: 1 a 2
# 3: 1 b 3
# 4: 1 b 4
# 5: 2 a 5
# 6: 2 a 6
# 7: 2 b 7
# 8: 2 b 8
DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
# x y mul
# 1: 1 a 4
# 2: 2 b 3
And you would like to get sum(z) * mul
for each row in DT2
while joining by columns x,y
. We can either:
1) aggregate DT1
to get sum(z)
, 2) perform a join and 3) multiply (or)
# data.table way
DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
# dplyr equivalent
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
right_join(DF2) %>% mutate(z = z * mul)
2) do it all in one go (using by = .EACHI
feature):
DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
What is the advantage?
We don't have to allocate memory for the intermediate result.
We don't have to group/hash twice (one for aggregation and other for joining).
And more importantly, the operation what we wanted to perform is clear by looking at j
in (2).
Check this post for a detailed explanation of by = .EACHI
. No intermediate results are materialised, and the join+aggregate is performed all in one go.
Have a look at this, this and this posts for real usage scenarios.
In dplyr
you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).
Update and joins:
Consider the data.table code shown below:
DT1[DT2, col := i.mul]
adds/updates DT1
's column col
with mul
from DT2
on those rows where DT2
's key column matches DT1
. I don't think there is an exact equivalent of this operation in dplyr
, i.e., without avoiding a *_join
operation, which would have to copy the entire DT1
just to add a new column to it, which is unnecessary.
Check this post for a real usage scenario.
To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!
Let's now look at syntax. Hadley commented here:
Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...
I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.
We will work with the dummy data shown below:
DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
Basic aggregation/update operations.
# case (a)
DT[, sum(y), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
DT[, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
# case (b)
DT[x > 2, sum(y), by = z]
DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
DT[x > 2, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
# case (c)
DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).
In case (b), we had to use filter()
in dplyr while summarising. But while updating, we had to move the logic inside mutate()
. In data.table however, we express both operations with the same logic - operate on rows where x > 2
, but in first case, get sum(y)
, whereas in the second case update those rows for y
with its cumulative sum.
This is what we mean when we say the DT[i, j, by]
form is consistent.
Similarly in case (c), when we have if-else
condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if
condition satisfies and skip otherwise, we cannot use summarise()
directly (AFAICT). We have to filter()
first and then summarise because summarise()
always expects a single value.
While it returns the same result, using filter()
here makes the actual operation less obvious.
It might very well be possible to use filter()
in the first case as well (does not seem obvious to me), but my point is that we should not have to.
Aggregation / update on multiple columns
# case (a)
DT[, lapply(.SD, sum), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
DT[, (cols) := lapply(.SD, sum), by = z]
ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
# case (b)
DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
# case (c)
DT[, c(.N, lapply(.SD, sum)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply()
, whereas dplyr
introduces *_each()
along with a bunch of functions to funs()
.
data.table's :=
requires column names to be provided, whereas dplyr generates it automatically.
In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.
In case (c) though, dplyr would return n()
as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j
. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c()
to concatenate .N
to a list
which returns a list
.
Note: Once again, in data.table, all we need to do is return a list in
j
. Each element of the list will become a column in result. You can usec()
,as.list()
,lapply()
,list()
etc... base functions to accomplish this, without having to learn any new functions.You will need to learn just the special variables -
.N
and.SD
at least. The equivalent in dplyr aren()
and.
Joins
dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by]
(and with reason). It also provides an equivalent merge.data.table()
function as an alternative.
setkey(DT1, x, y)
# 1. normal join
DT1[DT2] ## data.table syntax
left_join(DT2, DT1) ## dplyr syntax
# 2. select columns while join
DT1[DT2, .(z, i.mul)]
left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
# 3. aggregate while join
DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
# 4. update while join
DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
??
# 5. rolling join
DT1[DT2, roll = -Inf]
??
# 6. other arguments to control output
DT1[DT2, mult = "first"]
??
Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by]
, or merge()
which is similar to base R.
However dplyr joins do just that. Nothing more. Nothing less.
data.tables can select columns while joining (2), and in dplyr you will need to select()
first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.
data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI
feature. Why materialse the entire join result to add/update just a few columns?
data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.
data.table also has mult =
argument which selects first, last or all matches (6).
data.table has allow.cartesian = TRUE
argument to protect from accidental invalid joins.
Once again, the syntax is consistent with
DT[i, j, by]
with additional arguments allowing for controlling the output further.
do()
...
dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do()
. You have to know beforehand about all your functions return value.
DT[, list(x[1], y[1]), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
DT[, list(x[1:2], y[1]), by = z]
DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
DT[, quantile(x, 0.25), by = z]
DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
DT[, quantile(x, c(0.25, 0.75)), by = z]
DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
DT[, as.list(summary(x)), by = z]
DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
.SD
's equivalent is .
In data.table, you can throw pretty much anything in j
- the only thing to remember is for it to return a list so that each element of the list gets converted to a column.
In dplyr, cannot do that. Have to resort to do()
depending on how sure you are as to whether your function would always return a single value. And it is quite slow.
Once again, data.table's syntax is consistent with
DT[i, j, by]
. We can just keep throwing expressions inj
without having to worry about these things.
Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...
To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.
data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.
But one should also consider the number of features that dplyr lacks in comparison to data.table.
I have pointed out most of the features here and also in this post. In addition:
fread - fast file reader has been available for a long time now.
fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.
Automatic indexing - another handy feature to optimise base R syntax as is, internally.
Ad-hoc grouping: dplyr
automatically sorts the results by grouping variables during summarise()
, which may not be always desirable.
Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.
Non-equi joins: Allows joins using other operators <=, <, >, >=
along with all other advantages of data.table joins.
Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.
setorder()
function in data.table that allows really fast reordering of data.tables by reference.
dplyr provides interface to databases using the same syntax, which data.table does not at the moment.
data.table
provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff
, fintersect
, funion
and fsetequal
with additional all
argument (as in SQL).
data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame
compatibility when passed to any R package. dplyr changes base functions filter
, lag
and [
which can cause problems; e.g. here and here.
Finally:
On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.
On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).
OpenMP
.A feature rich Angular grid is this one:
Some of its features:
Enjoy. Yes, I'm the author. I got fed up with all the Angular grids out there.
${PODS_ROOT}/Manifest.lock
with:
${SRCROOT}/Podfile.lock" "${SRCROOT}/Pods/Manifest.lock
Check in image :
You need to use quote marks.
font-family: "Comic Sans MS", cursive, sans-serif;
Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
You should apply the following styles:
#button:active {
vertical-align: top;
padding: 8px 13px 6px;
}
This will give you the necessary effect, demo here.
If anybody is looking for a TypeScript solution:
.ts file (change variables where applicable):
module App.Filters {
export class trustedResource {
static $inject:string[] = ['$sce'];
static filter($sce:ng.ISCEService) {
return (value) => {
return $sce.trustAsResourceUrl(value)
};
}
}
}
filters.filter('trustedResource', App.Filters.trusted.filter);
Html:
<video controls ng-if="HeaderVideoUrl != null">
<source ng-src="{{HeaderVideoUrl | trustedResource}}" type="video/mp4"/>
</video>
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
You just have to read the laravel installation page:
composer global require "laravel/installer"
Inside your htdocs or www directory, use either:
laravel new appName
(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:
composer create-project --prefer-dist laravel/laravel appName
(this works also on windows) to create a project called "appName".
To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)
1-First of all, import you'r crt file into {JAVA_HOME}/jre/security/cacerts, if you still faced with this exception, change you'r jdk version. For example from jdk1.8.0_17
to jdk1.8.0_231
After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.
Long story short, the creator of YAML are saying .yaml
, but personally I keep doing .yml
. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml
everywhere. I've been writing docker-compose.yml
files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml
...
So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...
My problem was that I had @WebServlet("/route")
and the same servlet declared in web.xml
The -i
flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/
).
So in your first command, you are actually asking scp
to upload the .pem file itself using your default ssh key. I don't think that is what you want.
Try instead with:
scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads
Hibernate 4.3 is the first version to implement the JPA 2.1 spec (part of Java EE 7). And it's thus expecting the JPA 2.1 library in the classpath, not the JPA 2.0 library. That's why you get this exception: Table.indexes() is a new attribute of Table, introduced in JPA 2.1
In my case, I was running php artisan migrate on my mac terminal, when I needed to ssh into vagrant and run it from there. Hope that helps someone the headache.
This is because the inline style display:block
is overwriting your CSS. You'll need to either remove this inline style or use:
#tfl {
display: none !important;
}
This overrides inline styles. Note that using !important
is generally not recommended unless it's a last resort.
The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).
If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.
From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
Try to use https://www.pagedjs.org/. It polyfills page counter, header-/footer-functionality for all major browsers.
@page {
@bottom-left {
content: counter(page) ' of ' counter(pages);
}
}
It's so much more comfortable compared to alternatives like PrinceXML, Antennahouse, WeasyPrince, PDFReactor, etc ...
And it is totally free! No pricing or whatever. It really saved my life!
You can use display:inline-block
instead of float
and vertical-align:middle
with this CSS:
.col-lg-4, .col-lg-8 {
float:none;
display:inline-block;
vertical-align:middle;
margin-right:-4px;
}
The demo http://bootply.com/94402
Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier
date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")
This was you can always keep a check of when it was run
Try this:
CSS:
.hidden{display:none;}
HTML:
<table id="table" class="hidden">
<tr>
<th>City</th>
<th>Status</th>
</tr>
</table>
JS:
$('#search').click(function() {
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].city && data[i].cStatus){
txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.
So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!
Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:
You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW())
.
You do INSERT INTO table (dateCreated) VALUES (?)
, and specify the current time from your application code.
CASE #1
MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.
So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.
CASE #2
It depends on what type of value you pass as ?
. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
Swift:-
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Love Nature", size: 40)!]
Not sure what you have tried so far, but its pretty simple. Just do this: http://plnkr.co/edit/kmEWh7?p=preview
html, body {
height: 100%;
}
footer {
position: absolute;
bottom: 0;
}
As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.
ie:
public class Museo500TextView extends TextView {
public Museo500TextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
}
}
and
<my.package.views.Museo900TextView
android:id="@+id/dialog_error_text_header"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="12sp" />
After years I have discovered one, if not the, answer to the Microsoft bug of the 'User-defined type not defined' error in Excel. I'm running Excel 2010 for Windows.
If you have a UDF named for example 'xyz()
', then if you invoke a non-existent entity beginning with that name followed by a period followed by other chars -- e.g., if you try to invoke non-existent range name 'xyz.abc
', the stupid app throws that wrong msg., after which it returns you to your sheet.
In my case it was especially unnerving, because I have UDFs named with just one letter, e.g. x()
, y()
, etc., and I also have range names that include periods--'x.a
', 'c.d
', etc. Every time I, say, misspelled a range name--for example, 'x.h', the 'User-defined …' error was thrown simply because a UDF named 'x()
' existed somewhere in my project.
It took several hrs. to diagnose. Suggestions above to incrementally remove code from your project, or conversely strip all code and incrementally add it back in, were on the right track but they didn't follow thru. It has nothing to do with code per se; it has only to do with the name of the first line of code in each proc, namely the Sub MyProc
or Function MyProc
line naming the proc. It was when I commented out one of my 1-letter-named UDFs in a completely unrelated part of the project that the bugged error msg. went away, and from there, after another hr. or so, I was able to generalize the rule as stated.
Perhaps the bug also occurs with punctuation characters other than period ('.
') But there aren't very many non-alpha chars permitted in a range name; underline ('_
') is allowed, but using it in the manner described doesn't seem to throw the bug.
Jim Luedke
That is R's way of printing a zero length vector (an integer one), so you could test for a
being of length 0:
R> length(a)
[1] 0
It might be worth rethinking the strategy you are using to identify which elements you want, but without further specific details it is difficult to suggest an alternative strategy.
Try in cmd
taskkill /im iisexpress.exe /f
taskkill /im dotnet.exe /f
and press f5. I do not change ports, delete files or reboot VS.
I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:
echo @start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login > %systemroot%\sh.bat
Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
<? php
//1 Day = 24*60*60 = 86400
echo date("d-m-Y", time()+86400);
?>
In SQL, a comparison between a null
value and any other value (including another null
) using a comparison operator (eg =
, !=
, <
, etc) will result in a null
, which is considered as false
for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).
The reasoning is that a null
means "unknown", so the result of any comparison to a null
is also "unknown". So you'll get no hit on rows by coding where my_column = null
.
SQL provides the special syntax for testing if a column is null
, via is null
and is not null
, which is a special condition to test for a null
(or not a null
).
Here's some SQL showing a variety of conditions and and their effect as per above.
create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);
select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);
returns only 1 row (as expected):
TEST X Y
x = y 1 1
See this running on SQLFiddle
Quick, interactive way to see column names
If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.
import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description
Outputs something like this:
(('Date', None, None, None, None, None, None),
('Object-Name', None, None, None, None, None, None),
('Object-Count', None, None, None, None, None, None))
Or, quick way to access and print them out.
colnames = cursor.description
for row in colnames:
print row[0]
Outputs something like this:
Date
Object-Name
Object-Count
Absolute positioning is based on co-ordiantes of the display:
position:absolute;
top:0px;
left:0px;
^ places the element top left of the window.
Relative position is relative to where the element is placed:
position:relative;
top:1px;
left:1px;
^ places the element 1px down and 1px from the left of where it originally sat :)
You have two options:
Either use:
sb.setLength(0); // It will just discard the previous data, which will be garbage collected later.
Or use:
sb.delete(0, sb.length()); // A bit slower as it is used to delete sub sequence.
Avoid declaring StringBuffer
or StringBuilder
objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.
My suggestion:
using System.Linq;
string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());
reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c
Kos's answer is almost right, but can have damaging side effects. This is more correct:
#myTable tr td:nth-child(1), #myTable th:nth-child(1) {
display: none;
}
CSS (Cascading Style Sheets) will cascade attributes to all of its children. This means that *:nth-child(1)
will hide the first td
of each tr
AND hide the first element of all td
children. If any of your td
have things like buttons, icons, inputs, or selects, the first one will be hidden (woops!).
Even if you don't currently have things that will be hidden, image your frustration down the road if you need to add one. Don't punish your future self like that, that's going to be a pain to debug!
My answer will only hide the first td
and th
on all tr
in #myTable
keeping your other elements safe.
That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting
line, therefore the error reporting settings aren't changed yet.
You cannot change error reporting settings (or really, do anything) in a file with syntax errors.
Here is a new way to work with SQL views in EF Core: Query Types.
What I did with spring-data-jpa-1.3 was adding a version to xsd and lowered it to 1.2. Then the error message disappears. Like this
<beans
xmlns="http://www.springframework.org/schema/beans"
...
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
...
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
Seems like it was fixed for for 1.2 but then appears again in 1.3.
Use sqlcmd instead of osql if it's a 2005 database
Let me draw the scenario.
From: -303 To 183, what is the percentage change?
-303, -100% 0 183, 60.396% 303, 100%
|_________________ ||||||||||||||||||||||||________|
(183 - -303) / |-303| * 100 = 160.396%
Total Percent Change is approximately 160%
Note: No matter how negative the value is, it is treated as -100%.
The only way to achieve what you want is opening several instances of SSMS by right clicking on shortcut and using the 'Run-as' feature.
For this particular relationship, you could use np.sign
:
>>> df["C"] = np.sign(df.A - df.B)
>>> df
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Thank you to all that have responded! I've tried all of the solutions presented here and I've done more searching on the internet for other possible solutions, and I think I've found one that's promising:
tr.top td {_x000D_
border-top: thin solid black;_x000D_
}_x000D_
_x000D_
tr.bottom td {_x000D_
border-bottom: thin solid black;_x000D_
}_x000D_
_x000D_
tr.row td:first-child {_x000D_
border-left: thin solid black;_x000D_
}_x000D_
_x000D_
tr.row td:last-child {_x000D_
border-right: thin solid black;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<table cellspacing="0">_x000D_
<tr>_x000D_
<td>no border</td>_x000D_
<td>no border here either</td>_x000D_
</tr>_x000D_
<tr class="top row">_x000D_
<td>one</td>_x000D_
<td>two</td>_x000D_
</tr>_x000D_
<tr class="bottom row">_x000D_
<td>three</td>_x000D_
<td>four</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">once again no borders</td>_x000D_
</tr>_x000D_
<tr class="top bottom row">_x000D_
<td colspan="2">hello</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">world</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Output:
Instead of having to add the top
, bottom
, left
, and right
classes to every <td>
, all I have to do is add top row
to the top <tr>
, bottom row
to the bottom <tr>
, and row
to every <tr>
in between. Is there anything wrong with this solution? Are there any cross-platform issues I should be aware of?
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore)
The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler
The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events
I wrote this looking with reflector at the ErrorHandler inside elmah.mvc
public class ElmahMVCErrorFilter : IExceptionFilter
{
private static ErrorFilterConfiguration _config;
public void OnException(ExceptionContext context)
{
if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
{
var e = context.Exception;
var context2 = context.HttpContext.ApplicationInstance.Context;
//TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
{
_LogException(e, context2);
}
}
}
private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
{
if (_config == null)
{
_config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
}
var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
return _config.Assertion.Test(context2);
}
private static void _LogException(System.Exception e, System.Web.HttpContext context)
{
ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
}
private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
{
var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
if (signal == null)
{
return false;
}
signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
return true;
}
}
Now, in your filter config you want to do something like this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//These filters should go at the end of the pipeline, add all error handlers before
filters.Add(new ElmahMVCErrorFilter());
}
Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.
Now, make sure the appsettings for elmah in your webconfig look something like this:
<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->
The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings
This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.
Download it from here and extract LatoOFL.rar
then go to TTF and open this font-face-generator click at Choose File
choose font which you want to use and click at generate then download it and then go html
file open it and you see the code like this
@font-face {
font-family: "Lato Black";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body{
font-family: "Lato Black";
direction: ltr;
}
change the src code and give the url where your this font directory placed, now you can use it at your website...
If you don't want to download it use this
<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />
Regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. Hence you can see that regular grammar is a subset of context-free grammar.
So for a palindrome for instance, is of the form,
S->ABA
A->something
B->something
You can clearly see that palindromes cannot be expressed in regular grammar since it needs to be either right or left linear and as such cannot have a non-terminal on both side.
Since regular grammars are non-ambiguous, there is only one production rule for a given non-terminal, whereas there can be more than one in the case of a context-free grammar.
You could definitely use the attributes to return all attributes but you could add an instance method to Post, call it "to_hash" and have it return the data you would like in a hash. Something like
def to_hash
{ name: self.name, active: true }
end
This line solved my same problem in postgresql:
SELECT DATE_PART('year', column_name::date) from tableName;
If you want month, then simply replacing year
with month
solves that as well and likewise.
I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.
Here's a simple example.
HTML:
?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????
Basic CSS:
?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?
jQuery:
$("#testText").hover(
function(e){
$("#tooltip").show();
},
function(e){
$("#tooltip").hide();
});??????????
If you call a new window UI statement in an existing thread, it throws an error. Instead of that create a new thread inside the main thread and write the window UI statement in the new child thread.
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array
To access the attributes of an object is pretty easy:
alert(data.second);
But, if this does not completely answer your question, please clarify it and post back.
Thanks !
I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:
<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>
Angular Translate provides the $translate
service which you can use in your Controllers.
An example usage of the $translate
service can be:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$translate('PAGE.TITLE')
.then(function (translatedValue) {
$scope.pageTitle = translatedValue;
});
});
The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant()
:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
The downside with using $translate.instant()
could be that the language file isn't loaded yet if you are loading it async.
This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.
.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
var $translate = $filter('translate');
$scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:
http://www.youtube.com/watch?v=y1c7WFMMkZ4
When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.
What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.
Depending what you really mean, I propose the following solutions:
You mean a list of space separated sub-strings and want to know what is the sub-string position number among all sub-strings:
s = 'sub1 sub2 sub3'
s.split().index('sub2')
>>> 1
You mean the char-position of the sub-string in the string:
s.find('sub2')
>>> 5
You mean the (non-overlapping) counts of appearance of a su-bstring:
s.count('sub2')
>>> 1
s.count('sub')
>>> 3
1.- Export signed packages:
Use the Extract a Signed Android Application Package Wizard (On the main menu, choose Build | Generate Signed APK
). The package will be signed during extraction.
OR
Configure the .apk file as an artifact by creating an artifact definition of the type Android application with the Release signed package mode.
2.- Export unsigned packages: this can only be done through artifact definitions with the Debug or Release unsigned package mode specified.
You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.
Other options include:
Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.
Starting from ASP.NET Core 3.0, it is much simpler to access the environment variable from both ConfigureServices
and Configure
.
Simply inject IWebHostEnvironment
into the Startup constructor itself. Like so...
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
private readonly IWebHostEnvironment _env;
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
//development
}
}
public void Configure(IApplicationBuilder app)
{
if (_env.IsDevelopment())
{
//development
}
}
}
A simple two lines of code works for me.
dataGridView.DataSource = dataTable;
dataGridView.AutoResizeColumns();
it is working in my google chrome browser version 11.0.696.60
I created a simple page with no other items just basic tags and no separate CSS file and got an image
this is what i setup:
<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>
I put an id just in case there was a hidden id tag and it works
I have IE 7.0, Firefox 3.0 and Chrome 1.0
The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.
Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.
This does NOT work when the table-layout CSS property is set to fixed.
Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic. Hope this helps.
This worked for me. A combination of some of the answers here. And I included the code showing a model only once. And the model goes away when clicked anywhere else.
<script>
var leave = 0
//show modal when mouse off of page
$("html").mouseleave(function() {
//check for first time
if (leave < 1) {
modal.style.display = "block";
leave = leave + 1;
}
});
// Get the modal with id="id01"
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
I was trying a hello world program, and this line:
#include <stdio.h>
was underlined green. I tried:
fixed the error warning. i don't know if it fixed the actual problem. But then i'm compiling via a linux VM on Windows 10
select convert_tz(now(),@@session.time_zone,'+05:30')
replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994
to format into desired time format, eg:
select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p')
you will get similar to this -> Dec 17 2014 10:39:56 AM
DateTime.Now will not work, use DateTime.Today instead.
This is the easiest method i have found using prototype:
Main.html:
<html>
<head>
<script src="prototype.js"></script>
<script>
function init() {
var iframe = $(document.getElementById("iframe"));
var iframe_content = $(iframe.contentWindow.document.getElementById("iframe_content"));
var cy = iframe_content.getDimensions().height;
iframe.style.height = cy + "px";
}
</script>
</head>
<body onload="init()">
<iframe src="./content.html" id="iframe" frameBorder="0" scroll="no"></iframe>
<br>
this is the next line
</body>
</html>
content.html:
<html>
<head>
<script src="prototype.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="iframe_content" style="max-height:200px;">
Sub content<br>
Sub content<br>
...
...
...
</div>
</body>
</html>
This seems to work (so far) in all the major browsers.
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
I'll use find
command
find / -maxdepth 2 -iname 'tmp' -type d
as non superuser for the demo. It should complain 'Permission denied' when acessing /
dir.
#!/bin/bash
echo "terminal:"
{ err="$(find / -maxdepth 2 -iname 'tmp' -type d 2>&1 1>&3 3>&- | tee /dev/stderr)"; } 3>&1 | tee /dev/fd/4 2>&1; out=$(cat /dev/fd/4)
echo "stdout:" && echo "$out"
echo "stderr:" && echo "$err"
that gives output:
terminal:
find: ‘/root’: Permission denied
/tmp
/var/tmp
find: ‘/lost+found’: Permission denied
stdout:
/tmp
/var/tmp
stderr:
find: ‘/root’: Permission denied
find: ‘/lost+found’: Permission denied
The terminal
output has also /dev/stderr
content the same way as if you were running that find command without any script. $out
has /dev/stdout
and $err
has /dev/stderr
content.
use:
#!/bin/bash
echo "terminal:"
{ err="$(find / -maxdepth 2 -iname 'tmp' -type d 2>&1 1>&3 3>&-)"; } 3>&1 | tee /dev/fd/4; out=$(cat /dev/fd/4)
echo "stdout:" && echo "$out"
echo "stderr:" && echo "$err"
if you don't want to see /dev/stderr
in the terminal output.
terminal:
/tmp
/var/tmp
stdout:
/tmp
/var/tmp
stderr:
find: ‘/root’: Permission denied
find: ‘/lost+found’: Permission denied
In case it helps anyone setBackgroundImage
didn't work for me, but setImage
did
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.
But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private List<Node<T>> children = new ArrayList<Node<T>>();
private Node<T> parent = null;
private T data = null;
public Node(T data) {
this.data = data;
}
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setParent(Node<T> parent) {
parent.addChild(this);
this.parent = parent;
}
public void addChild(T data) {
Node<T> child = new Node<T>(data);
child.setParent(this);
this.children.add(child);
}
public void addChild(Node<T> child) {
child.setParent(this);
this.children.add(child);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRoot() {
return (this.parent == null);
}
public boolean isLeaf() {
return this.children.size == 0;
}
public void removeParent() {
this.parent = null;
}
}
Example:
import java.util.List;
Node<String> parentNode = new Node<String>("Parent");
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");
childNode2.setParent(parentNode);
Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1);
List<Node<String>> childrenNodes = parentNode.getChildren();
This is easily caused when you add git based subprojects. Xcode isn't smart enough to ignore the .git subfolder even though you can't see it from finder, so it will get very confused that there are multiple files named "master" or "exclude", (standard git repo files). With Xcode4, go to the project (root of the left tree) then click your app target and expand "Copy Bundle Resources", then remove all the references to .git, you shouldn't need them baked into your app anyway.
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
(?!
is useful in practice.
Although strictly speaking, looking ahead is not regular expression as defined mathematically.
You can write an invert regular expression manually.
Here is a program to calculate the result automatically. Its result is machine generated, which is usually much more complex than hand writing one. But the result works.
EDIT: I was wrong, and you should see Marks answer above.
I cannot speak from experience with SQL Server, but for most databases the answer would be no. The only potential benefit that you get, performance wise, from using a view is that it could potentially create some access paths based on the query. But the main reason to use a view is to simplify a query or to standardize a way of accessing some data in a table. Generally speaking, you won't get a performance benefit. I may be wrong, though.
I would come up with a moderately more complicated example and time it yourself to see.
Let's not use NOW()
as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.
In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.
Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW()
function as it kills your caching.
SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);
You can use BETWEEN
if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.
For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:
import logging
logging.basicConfig(level = logging.INFO)
Then to display anything at or above that level:
logging.info("Hi you just set your fleeb to level plumbus")
It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken")
.
The levels, in increasing order of severity, are DEBUG
, INFO
, WARNING
, ERROR
, and CRITICAL
. The default setting is WARNING
.
This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3
Check this,
char s='A';
int i = (s<='9')?(s-'0'):(s<='F')?((s-'A')+10):((s-'a')+10);
for only 0,1,2,....,E,F.
I had a project that I also needed an exact replica of a DataTable in Excel format. Using ClosedXML, the following code did exactly that for me.
using ClosedXML.Excel;
private void DumpDataTableToExcel(DataTable dt, string SavePathAndFilename)
{
try
{
using (XLWorkbook excelWorkbook = new XLWorkbook())
{
excelWorkbook.AddWorksheet(dt);
excelWorkbook.SaveAs(SavePathAndFilename);
}
}
catch
{
//Insert error handling here...
}
}
This method will use your DataTable's column names as the column names in Excel and the DataTable name itself will be the sheet name. Hard to accomplish all of this with fewer lines of code.
Adding ClosedXML to your project is equally simple. There are instructions in the link above as well as directly on nuget.org.
I am using Idea based Android Studio (some people are talking about eclipse one here)
When I launch the app in the emulator (using the Run App button of Android Studio) AVD shows up but the app does not launch or run.
However when I connect my mobile and launch the app on my mobile the App works (this itself took some time, enabling developer options on mobile and doing the right configuration)
1 - I installed the app manually by dragging the APK file on AVD. (APK file is app\build\outputs\apk\debug folder)
2 - Then my AVD was not showing the installed APP list. 3 - I searched my APP using Google bar on AVD and dragged the APP icon on the home screen of AVD.
4 - I can now launch the APP using my APP icon on the home screen of AVD.
That's how I am working around my problem. I will try to debug more on why it does not get installed and launched directly.
I have verified that Run App Icon does install the Application. Installation, not launching, appears to be the problem for me.
You can use:
SELECT IDENT_CURRENT('tablename')
to access the latest identity for a perticular table.
e.g. Considering following code:
INSERT INTO dbo.MyTable(columns....) VALUES(..........)
INSERT INTO dbo.YourTable(columns....) VALUES(..........)
SELECT IDENT_CURRENT('MyTable')
SELECT IDENT_CURRENT('YourTable')
This would yield to correct value for corresponding tables.
It returns the last IDENTITY
value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT
is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT
returns the identity value generated for a specific table in any session and any scope.
Writing the properties file with multiple comments is not supported. Why ?
PropertyFile.java
public class PropertyFile extends Task {
/* ========================================================================
*
* Instance variables.
*/
// Use this to prepend a message to the properties file
private String comment;
private Properties properties;
The ant property file task is backed by a java.util.Properties
class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties
class to save into the file.
The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties
. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment>
elements.
You can simply do:
Serial.println(n);
which will convert n
to an ASCII string automatically. See the documentation for Serial.println()
.
change
<input type="submit" value="Submit" />
to
<input type="submit" value="Submit" name='submit'/>
change
<form method="post" action="<?php echo $PHP_SELF;?>">
to
<form method="post" action="">
if
only when it is submitted.I had the same problem as yours. I found that when i use the BoundField
tag in GridView to show my data. The row.Cells[1].Text
is working in:
GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";
But when i use TemplateField
tag to show data like this:
<asp:TemplateField HeaderText="??">
<ItemTemplate>
<asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="bhead" />
<ItemStyle CssClass="bbody" />
</asp:TemplateField>
The row.Cells[1].Text
just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.
My Solution:
Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;
I use Controls
attribute to find the Label
control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:
string showText = lbCod.Text;
Reference: reference
If your properties file path and your java class path are same then you should this.
For example:
src/myPackage/MyClass.java
src/myPackage/MyFile.properties
Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);
I don't think you can!
/home/export/user1 $ sqlplus /
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql
script2.sql has to be in /home/export/user1
.
You either use the full path, or exit the script and start sqlplus
again from the right directory.
#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql
(something like that - doing this from memory!)
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
No. Its not possible to add link through css. But you can use jquery
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});
Here the demo: http://jsfiddle.net/r5uWX/1/
Here is another approach...
When I've got to the same problem, I didn't like the suggested solutions here. So, I've come up with another way: I've inserted a TextView in the XML file between the two fields I wanted to separate with two important fields:
height is set to whatever I needed the separation to be.
XML:
...//some view up here
<TextView
android:id="@+id/dialogSeparator"
android:layout_width="match_parent"
android:layout_height="30dp"
android:visibility="gone"/>
...//some view down here
Now, I the code, all I needed to do it simple change the visibility to invisible (i.e. it's there, and taking the needed space, but it's unseen)
JAVA:
TextView tvSeparator = (TextView)activity.findViewById(R.id.dialogSeparator);
tvSeparator.setVisibility(View.INVISIBLE);
//Inside an activity extended class I can use 'this' instead of 'activity'.
Viola...I got the needed margin. BTW, This solution is for LinearLayout with vertical orientation, but you can do it with different layouts.
Hope this helps.
As per MSDN
Create MD5:
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
I'm using FontAwesome Pro, and the solution for me was to embed all.min.css
instead of fontawesome.min.css
.
Here's a pure javascript solution,
<iframe
width="100%"
height="443"
class="yvideo"
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0"
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>
<script>
document.getElementById("myStopClickButton").addEventListener("click", function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}
});
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
If you're running Windows then make use of this:
g++ -o program program.cpp
g++
is the name of the compiler and -o
is the option needed for creating a .o file. Program (without .cpp suffix) is the exe
file and program.cpp
is your source file that you want to compile.
g++ -o program program.cpp&program.exe
Use this shortcut to run the .exe
file of the program. This may run in Ubuntu but you may have to use .out
suffix instead of .exe
. Use this handy batch script I made to execute your programs on Windows:
@echo off&&cls
set /p pathName=Enter The Path where the file is located:%=%
cd %pathName%
REM set /p exec=Enter The Name of the executable you want to make:%=%
set /p file=Enter The Name of the file you want to compile:%=%
g++ -o %file% %file%.cpp
%file%.exe
save it as cppExecutor.bat
Also you could use the following commands on Unix (Linux and Mac) OS:
CC program.cc
If you want to use gcc
:
gcc -o program program.cpp
With the shortcut:
gcc -o program program.cpp&program.exe
Nice clean solution:
<?php
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="example.csv"');
header("Content-Length: " . filesize("example.csv"));
$fp = fopen("example.csv", "r");
fpassthru($fp);
fclose($fp);
?>
I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code
Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
AllowOverride AuthConfig
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
with this
Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
AllowOverride AuthConfig
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
Don't Forget to Restart your Xampp.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
You could use HorizontalContentAlignment="Stretch"
as follows:
<ListBox HorizontalContentAlignment="Stretch"/>
In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
I got the same error. I uninstalled the app on my virtual device and rerun the command: 'react-native run-android'.
iframe
s are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.
Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended.
Nowadays there's a simpler way to achieve this if you are using a DialogFragment
(not a Fragment
):
val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
activity.supportFragmentManager,
"YOUR_TAG_FRAGMENT"
)
Under the hood, the show()
method does create a FragmentTransaction
and adds the tag by using the add()
method. But it's much more convenient to use the show()
method in my opinion.
You could shorten it for Fragment
too, by using a Kotlin Extension :)
Maybe the span element is hidden. If that's the case then use the innerHtml property:
By.css:
String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
.getAttribute("innerHTML");
By.xpath:
String kk = wd.findElement(By.xpath(
"//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
.getAttribute("innerHTML");
"/.//" means "look under the selected element".
Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)
^
[A-Z] // Start with an uppercase Letter
( // A Group of:
[a-z] // mandatory lowercase letter
[A-Z]? // an optional Uppercase Letter at the end
// or in between lowercase letters
)+ // This group at least one time
$
Just a bit more compact and easier to read I think...
Initialize the MailMessage
with sender and reciever's email addresses. It should be something like
string from = "[email protected]"; //Senders email
string to = "[email protected]"; //Receiver's email
MailMessage msg = new MailMessage(from, to);
Read the full code snippet of how to send emails in c#
Let me explain to you by an example:
if you have Python list
>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]
and you want to remove duplicates from it.
>>> uniqueList = []
>>> for letter in randomList:
if letter not in uniqueList:
uniqueList.append(letter)
>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']
This is how you can remove duplicates from the list.
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
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.
Why not use drop_duplicates
from pandas:
>>> timeit pd.DataFrame(image.reshape(-1,3)).drop_duplicates().values
1 loops, best of 3: 3.08 s per loop
>>> timeit np.vstack({tuple(r) for r in image.reshape(-1,3)})
1 loops, best of 3: 51 s per loop
You can add a NuGet package CefSharp.WinForms to your application and then add a ChromiumWebBroweser control to your form. In the code you can write:
chromiumWebBrowser1.Load(filePath);
This is the easiest solution I have found, it is completely free and independent of the user's computer settings like it would be when using default WebBrowser control.
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
For example:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:
Reuses cells while scrolling up/down : this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Decouples list from its container : so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.
October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -
(first, install pre-requisites using sudo apt-get install build-essential curl file git)
finally create a ~/.zprofile
with the following contents:
emulate sh -c '. ~/.profile'
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
We can simply use Collections.max()
and Collections.min()
method.
public class MaxList {
public static void main(String[] args) {
List l = new ArrayList();
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
System.out.println(Collections.max(l)); // 5
System.out.println(Collections.min(l)); // 1
}
}
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
Without any JS library or jQuery. To open a nice popup window if possible. Fails safely to normal link open.
<a href="https://acme.com/" onclick="onclick="openNewWindow(event, this.href);">...</a>
And the helper function:
function openNewWindow(event, location) {
if (event.preventDefault && event.stopImmediatePropagation) {
event.preventDefault();
event.stopImmediatePropagation();
} else {
event.returnValue = false;
}
window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}
**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
sessions = get_abstracts['sessions']
abs = {}
for a in get_abstracts['abstracts']:
a_session_id = a['session_id']
abs.setdefault(a_session_id,[]).append(a)
authors = {}
# print('authors')
# print(get_abstracts['authors'])
for au in get_abstracts['authors']:
# print(au)
au_abs_id = au['abs_id']
authors.setdefault(au_abs_id,[]).append(au)
**In jinja template**
{% for s in sessions %}
<h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4>
{% for a in abs[s.session_id] %}
<hr>
<p><b>Chief Author :</b> Dr. {{ a.full_name }}</p>
{% for au in authors[a.abs_id] %}
<p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
http://snipplr.com/view/51108/nested-array-search-by-value-or-key/
<?php
//PHP 5.3
function searchNestedArray(array $array, $search, $mode = 'value') {
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
if ($search === ${${"mode"}})
return true;
}
return false;
}
$data = array(
array('abc', 'ddd'),
'ccc',
'bbb',
array('aaa', array('yyy', 'mp' => 555))
);
var_dump(searchNestedArray($data, 555));
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
it should works at least in pyspark 2.4
tdata = tdata.withColumn("Age", when((tdata.Age == "") & (tdata.Survived == "0") , "NewValue").otherwise(tdata.Age))
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
I generally like the shorthand version:
if (!!wlocation) { window.location = wlocation; }
First thing Correctly specify all settings in the .ENV file for Mail.
I LOST 6 HOURS FOR THIS
Example
MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
For IE there is fireEvent() method. Don't know if that works for other browsers.
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
Java 8+ has computeIfAbsent
examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);
No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.
Check this link: https://developers.google.com/gsuite/products for updates.
However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi
If you use Drupal AND the module called "WYSIWYG" with the CKEditor library, then the following workaround could be a solution. For me it works like a charm. I use CKEditor 4.4.5 and WYSIWYG 2.2 in Drupal 7.33. I found this workaround here: https://www.drupal.org/node/1956778.
Here it is: I create a custom module and put the following code in the ".module" file:
<?php
/**
* Implements hook_wysiwyg_editor_settings_alter().
*/
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
if ($context['profile']->editor == 'ckeditor') {
$settings['allowedContent'] = TRUE;
}
}
?>
I hope this help other Drupal users.
I had a similar issue with 50,000 rdf/xml files in 5,000 directories (the Project Gutenberg catalog file). I solved it with riot (in the jena distribution)
the directory is cache/epub/NN/nn.rdf (where NN is a number)
in the directory above the directory where all the files are, i.e. in cache
riot epub/*/*.rdf --output=turtle > allTurtle.ttl
This produces possibly many warnings but the result is in a format which can be loaded into jena (using the fuseki web interface).
surprisingly simple (at least in this case).
Just tried on my machine compiling this :
int a = ...;
int b = a * 10;
When disassembling it produces output :
MOV EAX,DWORD PTR SS:[ESP+1C] ; Move a into EAX
LEA EAX,DWORD PTR DS:[EAX+EAX*4] ; Multiply by 5 without shift !
SHL EAX, 1 ; Multiply by 2 using shift
This version is faster than your hand-optimized code with pure shifting and addition.
You really never know what the compiler is going to come up with, so it's better to simply write a normal multiplication and let him optimize the way he wants to, except in very precise cases where you know the compiler cannot optimize.
I have been looking for the solution for quite a bit. And finally I have the answer. If your virtual host is not working on your Windows 10, or 7 etc, it's because of this new https hype, where all the sites are routed to https.
XAMPP follows the same trend, so fixing virtual hosts, hosts file etc is not enough, due to strict https redirection. Here is the full solution.
My desired site is located at D:\xampp\htdocs\ikeen.
1) Add this to your httpd-vhosts.conf:
<VirtualHost *:80>
ServerName localhost
DocumentRoot "D:\xampp\htdocs"
<Directory "D:\xampp\htdocs">
DirectoryIndex index.php
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName ikeen.localhost
DocumentRoot "D:\xampp\htdocs\ikeen"
SetEnv APPLICATION_ENV "development"
<Directory "D:\xampp\htdocs\ikeen">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
2) Add this to the end of httpd.conf:
<Directory />
AllowOverride none
Require all granted
</Directory>
3) Add this line to your hosts file in Windows directory
127.0.0.1 ikeen.localhost
4) The final step is to change the VirtualHost section of your httpd-ssl.conf file to the following
<VirtualHost _default_:443>
# General setup for the virtual host
DocumentRoot "D:/xampp/htdocs"
#ServerName www.example.com:443
ServerName localhost
ServerAdmin [email protected]
ErrorLog "D:/xampp/apache/logs/error.log"
TransferLog "D:/xampp/apache/logs/access.log"
# General setup for the ikeen host
DocumentRoot "D:/xampp/htdocs/ikeen"
#ServerName www.example.com:443
ServerName ikeen.localhost
ServerAdmin [email protected]
ErrorLog "D:/xampp/apache/logs/error.log"
TransferLog "D:/xampp/apache/logs/access.log"
Restart and be happy:)
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
function getMetaContentByName(name,content){
var content = (content==null)?'content':content;
return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}
Used in this way:
getMetaContentByName("video");
The example on this page:
getMetaContentByName("twitter:domain");
After Pressing Control+Shift+P as suggested by @Edwin:
I just wanted to add to this question. I had Git setup to use PLink and Pageant for authentication and I was also getting the error FATAL ERROR: Disconnected: No supported authentication methods available (server sent: publickey)
. I had Pageant opened but the error was still showing up. The problem? I didn't have the private key loaded in Pageant (to add a key, follow these instructions). It was that simple.
Install Fake Sendmail (download sendmail.zip). Then configure C:\wamp\sendmail\sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password
The above will work against a Gmail account. And then configure php.ini:
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
Now, restart Apache, and that is basically all you need to do.
When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.
u can use this :
@Override
public void afterTextChanged(Editable s) {
super.afterTextChanged(s);
if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
Bank bank = BankUtil.findByPan(s.toString());
if (null != bank && mNewPanEntered && !mNameDefined) {
mNewPanEntered = false;
suggestCardName(bank);
}
private void suggestCardName(Bank bank) {
mLastSuggestTime = System.currentTimeMillis();
if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
inputCardNumber.setError(R.string.balance_not_enmb, true);
}
}
something like this:
f = open('data.txt', 'r')
for line in f:
line = line.split(';')
product = Product()
product.name = line[2] + '(' + line[1] + ')'
product.description = line[4]
product.price = '' #data is missing from file
product.save()
f.close()
Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.
$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts
Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.
#!/bin/bash
#Jason Xiong: Dec 2013
# The ip or ipalias stored in known_hosts file is hashed and
# is not human readable.This script check if the supplied ip
# or ipalias exists in ~/.ssh/known_hosts file
if [[ $# != 2 ]]; then
echo "Usage: ./search_known_hosts -i ip_or_ipalias"
exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;
cat $known_host_file | while read -r line;do
if [[ -z "$line" ]]; then
continue;
fi
hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}');
key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}');
hex_key=$(echo $key | base64 -d | xxd -p);
if [[ $hash_type = 1 ]]; then
gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
-macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);
if [[ $gen_value = $stored_value ]]; then
echo $gen_value;
echo "Found match in known_hosts file : entry#"$entry" !!!!"
fi
else
echo "unknown hash_type"
fi
entry=$((entry + 1));
done
With regard to Tomcat, a lot depends on the particular version. There was a bug fix https://bz.apache.org/bugzilla/show_bug.cgi?id=50026 which means the servlet-mapping (other than for '/') for the default servlet behaves differently in Tomcat 6.0.29 (and earlier) compared with later versions.
The problem in my case was that I was running the command inside a python virtual environment and it didn't had the path to /usr/local/mysql/bin though I have put it in the .bash_profile file. Just exporting the path in the virtual env worked for me.
For your info sql_config resides inside bin directory.
You can also pipe commands inside Docker container, bash -c "<command1> | <command2>"
for example:
docker run img /bin/bash -c "ls -1 | wc -l"
But, without invoking the shell in the remote the output will be redirected to the local terminal.
The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.
var firstSelect = document.getElementById('first select elements id'),
secondSelect = document.getElementById('second select elements id'),
optionsHTML = [],
i = 12;
for (; i < 100; i += 1) {
optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}
firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');
Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.
To prevent having further issues with SSL you should add all those to Path :
SETX PATH "%PATH%;C:\<path>\Anaconda3;C:\<path>\Anaconda3\Scripts;C:\<path>\Anaconda3\Library\bin"
From here
Thus, only alphanumerics, the special characters
$-_.+!*'(),
and reserved characters used for their reserved purposes may be used unencoded within a URL.
May I humbly suggest the Rabin-Karp algorithm if the big
list is really big. The link even contains almost-usable code in almost-Python.
The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.
Manifest-Version: 1.0
All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers
Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions
Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:
Main-Class: classname
The value classname is to be replaced with the application's entry point.
Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:
Class-Path: servlet.jar infobus.jar acme/beans.jar
With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.
Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:
Name: myCompany/myPackage/
Sealed: true
The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.
Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:
Name: java/util/
Specification-Title: "Java Utility Classes"
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util"
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
std::chrono::milliseconds
to integer (uint64_t
to avoid overflow)#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
std::cout << timeSinceEpochMillisec() << std::endl;
return 0;
}
I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.
If you are trying to load the image at your form_load, it's a better idea to use the code
pictureBox1.LoadAsync(@"http://google.com/test.png");
not only loading from web but also no lag in your form loading.
select the image in chrome, right click on it, click on Copy image address
, paste it into a str
variable (my_url
) to read the image:
import shutil
import requests
my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
shutil.copyfileobj(response.raw, file)
del response
open it;
from PIL import Image
img = Image.open('my_image.png')
img.show()
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Necromancing.
Also, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:
// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages
// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages
// https://en.wikipedia.org/wiki/Chinese_character_encoding
System.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;
encRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding
encRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)
encRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R
encRemoveAllBut = System.Text.Encoding.GetEncoding("ISO-8859-5"); // used by less than 0.1% of websites
encRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada
encRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1
encRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified
encRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional
encRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question
// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c
string inputString = "Räksmör??????, ???gås";
string asAscii = encRemoveAllBut.GetString(
System.Text.Encoding.Convert(
System.Text.Encoding.UTF8,
System.Text.Encoding.GetEncoding(
encRemoveAllBut.CodePage,
new System.Text.EncoderReplacementFallback(string.Empty),
new System.Text.DecoderExceptionFallback()
),
System.Text.Encoding.UTF8.GetBytes(inputString)
)
);
System.Console.WriteLine(asAscii);
AND for those that just want to remote the accents:
(caution, because Normalize != Latinize != Romanize)
// string str = Latinize("(æøå âôû?aè");
public static string Latinize(string stIn)
{
// Special treatment for German Umlauts
stIn = stIn.Replace("ä", "ae");
stIn = stIn.Replace("ö", "oe");
stIn = stIn.Replace("ü", "ue");
stIn = stIn.Replace("Ä", "Ae");
stIn = stIn.Replace("Ö", "Oe");
stIn = stIn.Replace("Ü", "Ue");
// End special treatment for German Umlauts
string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int ich = 0; ich < stFormD.Length; ich++)
{
System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
{
sb.Append(stFormD[ich]);
} // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
} // Next ich
//return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));
return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));
} // End Function Latinize
Alternatively, if you have control of the css, you could get clever with url parameters and css.
Markdown:
![A cute kitten](http://placekitten.com/200/300?style=centerme)
And CSS:
img[src$="centerme"] {
display:block;
margin: 0 auto;
}
You could create a variety of styling options this way and still keep the markdown clean of extra code. Of course you have no control over what happens if someone else uses the markdown somewhere else but thats a general styling issue with all markdown documents one shares.
One more reason for this error (assuming that gradle properly setup) is incompatibility between andorid.gradle tools and gradle itself - check out this answer for the complete compatibility table.
In my case the error was the same as in the question and the stacktrace as following:
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at com.android.build.gradle.BasePlugin.lambda$configureProject$1(BasePlugin.java:436)
at sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
...
I've fixed that by upgrading com.android.tools.build:gradle
to the current latest 3.1.4
buildscript {
repositories {
...
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
}
}
Gradle version is 4.6
When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.
let a = [];
a[1] = 'foo';
console.log(!!a[0]) // false
console.log(!!a[1]) // true
One consideration is that FTP can use non-standard ports, which can make getting though firewalls difficult (especially if you're using SSL). HTTP is typically on a known port, so this is rarely a problem.
If you do decide to use FTP, make sure you read about Active and Passive FTP.
In terms of performance, at the end of the day they're both spewing files directly down TCP connections so should be about the same.
It has to do with the new Play Store update.
Go to:
settings/apps/all/Google Play Store
Select Google Play Store
and select uninstall updates - that should solve your issue. Open up play store and purchase your app or game select bill to Verizon or whatever phone provider you use then accept. Log in to your Google account and you're done. When you close out the play store it will update again to the latest version and will allow you to bill to account.
Depending on what you want to do you could do this:
template<typename Base, typename T>
inline bool instanceof(const T*) {
return std::is_base_of<Base, T>::value;
}
Use:
if (instanceof<BaseClass>(ptr)) { ... }
However, this purely operates on the types as known by the compiler.
Edit:
This code should work for polymorphic pointers:
template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
Example: http://cpp.sh/6qir
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
I've created a simple Dictionary
initializer that replaces NSDictionary(contentsOfFile: path)
. Just remove the NS
.
extension Dictionary where Key == String, Value == Any {
public init?(contentsOfFile path: String) {
let url = URL(fileURLWithPath: path)
self.init(contentsOfURL: url)
}
public init?(contentsOfURL url: URL) {
guard let data = try? Data(contentsOf: url),
let dictionary = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any]) ?? nil
else { return nil }
self = dictionary
}
}
You can use it like so:
let filePath = Bundle.main.path(forResource: "Preferences", ofType: "plist")!
let preferences = Dictionary(contentsOfFile: filePath)!
UserDefaults.standard.register(defaults: preferences)
You need to delete your old db folder and recreate new one. It will resolve your issue.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
You can't do pointer arithmetic on void *
types, for exactly this reason!
The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.
The basic process is:
The table should, of course, be nice HTML. Something like this...
<table>
<thead>
<tr><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Sioned</td><td>62</td></tr>
<tr><td>Dylan</td><td>37</td></tr>
...etc...
</tbody>
</table>
So, first adding the click handlers...
const table = document.querySelector('table'); //get the table to be sorted
table.querySelectorAll('th') // get all the table header elements
.forEach((element, columnNo)=>{ // add a click handler for each
element.addEventListener('click', event => {
sortTable(table, columnNo); //call a function which sorts the table by a given column number
})
})
This won't work right now because the sortTable
function which is called in the event handler doesn't exist.
Lets write it...
function sortTable(table, sortColumn){
// get the data from the table cells
const tableBody = table.querySelector('tbody')
const tableData = table2data(tableBody);
// sort the extracted data
tableData.sort((a, b)=>{
if(a[sortColumn] > b[sortColumn]){
return 1;
}
return -1;
})
// put the sorted data back into the table
data2table(tableBody, tableData);
}
So now we get to the meat of the problem, we need to make the functions table2data
to get data out of the table, and data2table
to put it back in once sorted.
Here they are ...
// this function gets data from the rows and cells
// within an html tbody element
function table2data(tableBody){
const tableData = []; // create the array that'll hold the data rows
tableBody.querySelectorAll('tr')
.forEach(row=>{ // for each table row...
const rowData = []; // make an array for that row
row.querySelectorAll('td') // for each cell in that row
.forEach(cell=>{
rowData.push(cell.innerText); // add it to the row data
})
tableData.push(rowData); // add the full row to the table data
});
return tableData;
}
// this function puts data into an html tbody element
function data2table(tableBody, tableData){
tableBody.querySelectorAll('tr') // for each table row...
.forEach((row, i)=>{
const rowData = tableData[i]; // get the array for the row data
row.querySelectorAll('td') // for each table cell ...
.forEach((cell, j)=>{
cell.innerText = rowData[j]; // put the appropriate array element into the cell
})
tableData.push(rowData);
});
}
And that should do it.
A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2"
is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
I use Eclipse for cross compiling and I have to add the explicit directories for some of the standard C++ libraries. Right click your project and select Properties. You'll get the dialog shown in the image. Follow the image and use the + icon to explicitly add the paths to your C++ libraries.
I don't know about past versions of UITableView
protocols, but as of iOS 9, func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
is part of the UITableViewDataSource
protocol.
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section name"
}
}
You don't need to declare the delegate
to fill your table with data.
Add the column and update all rows in the DataTable
, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
Try this. For example:
You should use UINavigationController
as the initial view controller. Then, you can set any view controller as root from the storyboard.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController = storyboard.instantiateInitialViewController() as UINavigationController
let rootViewController = storyboard.instantiateViewControllerWithIdentifier("VC") as UIViewController
navigationController.viewControllers = [rootViewController]
self.window?.rootViewController = navigationController
return true
}
Just use the following sql, you are done:
SELECT replace(CustomerName,' ', '') FROM Customers;
you can test this sample over here: W3School
git stash
git checkout master
cd .git/ && find . -type f -empty -delete
git branch your-branch-name -D
git checkout -b your-branch-name
git stash pop
resolve my problem
Had this error when I had deleted a table from the database. Solved it by right clicking on EDMX diagram, going to Properties, selecting the table from the list in the Properties window, and deleting it (using delete key) from the diagram.
Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.
OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.buffer(Okio.sink(os)));
json.beginObject();
json.name("id").value(getId());
json.name("scores");
json.beginArray();
for (Double score : getScores()) {
json.value(score);
}
json.endArray();
json.endObject();
If you want the string in hand:
Buffer b = new Buffer(); // okio.Buffer
JsonWriter writer = new JsonWriter(b);
//...
String jsonString = b.readUtf8();
Why don't u use:
<script>
$('input').keyup(function(){
if(($('#eng').val().length > 0) && ($('#spa').val().length > 0))
$("#submit").prop('disabled', false);
else
$("#submit").prop('disabled', true);
});
</script>
Then delete the onkeyup function on the input.
For me, it only worked when I added the following line of code
$('#target').val($('#target').find("option:first").val());
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
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.
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
This can also be done as follows for a list of dataframes df_list
:
df = df_list[0]
for df_ in df_list[1:]:
df = df.merge(df_, on='join_col_name')
or if the dataframes are in a generator object (e.g. to reduce memory consumption):
df = next(df_list)
for df_ in df_list:
df = df.merge(df_, on='join_col_name')
Considering Rails 3:
html_safe
actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.
h
can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe
declaration, pretty unusual.
Prepending your expression with raw
is actually equivalent to calling to_s
chained with html_safe
on it, but is declared on a helper, just like h
, so it can only be used on controllers and views.
"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffer
s (the class that does the html_safe
magic) work.
Checkout this thread, it has some useful information about exiting and tracebacks.
If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
For formatting the price in another currency than the current one:
Mage::app()->getLocale()->currency('EUR')->toCurrency($price);
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my very similar problem. I know some of the other solutions look shorter but they seem to use SUBSTRING_INDEX() way more than necessary. Here I try to just use LOCATE() just once per delimiter.
-- *****************************************************************************
-- test_PVreplace
DROP FUNCTION IF EXISTS test_PVreplace;
delimiter //
CREATE FUNCTION test_PVreplace (
str TEXT, -- String to do search'n'replace on
pv TEXT -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
)
RETURNS TEXT
-- Replace specific tags with specific values.
sproc:BEGIN
DECLARE idx INT;
DECLARE idx0 INT DEFAULT 1; -- 1-origined, not 0-origined
DECLARE len INT;
DECLARE sPV TEXT;
DECLARE iPV INT;
DECLARE sP TEXT;
DECLARE sV TEXT;
-- P/V string *must* end with a delimiter.
IF (RIGHT (pv, 1) <> '|') THEN
SET pv = CONCAT (pv, '|');
END IF;
-- Find all the P/V pairs.
SELECT LOCATE ('|', pv, idx0) INTO idx;
WHILE (idx > 0) DO
SET len = idx - idx0;
SELECT SUBSTRING(pv, idx0, len) INTO sPV;
-- Found a P/V pair. Break it up.
SELECT LOCATE ('=', sPV) INTO iPV;
IF (iPV = 0) THEN
SET sP = sPV;
SET sV = '';
ELSE
SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
SELECT SUBSTRING(sPV, iPV+1) INTO sV;
END IF;
-- Do the substitution(s).
SELECT REPLACE (str, sP, sV) INTO str;
-- Do next P/V pair.
SET idx0 = idx + 1;
SELECT LOCATE ('|', pv, idx0) INTO idx;
END WHILE;
RETURN (str);
END//
delimiter ;
SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');
I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.
Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).
First here is the Java objects.
public class A implements Serializable{
protected int id;
// put some others fields if needed ...
private Set<AC> ac = new HashSet<AC>();
public A(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<AC> getAC() {
return ac;
}
public void setAC(Set<AC> ac) {
this.ac = ac;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 97;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof A))
return false;
final A other = (A) obj;
if (id != other.getId())
return false;
return true;
}
}
public class C implements Serializable{
protected int id;
// put some others fields if needed ...
public C(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 98;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof C))
return false;
final C other = (C) obj;
if (id != other.getId())
return false;
return true;
}
}
Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).
public class ACId implements Serializable{
private A a;
private C c;
public ACId() {
super();
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result
+ ((c == null) ? 0 : c.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ACId other = (ACId) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (c == null) {
if (other.c != null)
return false;
} else if (!c.equals(other.c))
return false;
return true;
}
}
Now let's create the association object itself.
public class AC implements java.io.Serializable{
private ACId id = new ACId();
private String extra;
public AC(){
}
public ACId getId() {
return id;
}
public void setId(ACId id) {
this.id = id;
}
public A getA(){
return getId().getA();
}
public C getC(){
return getId().getC();
}
public void setC(C C){
getId().setC(C);
}
public void setA(A A){
getId().setA(A);
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AC that = (AC) o;
if (getId() != null ? !getId().equals(that.getId())
: that.getId() != null)
return false;
return true;
}
public int hashCode() {
return (getId() != null ? getId().hashCode() : 0);
}
}
At this point, it's time to map all our classes with hibernate xml configuration.
A.hbm.xml and C.hxml.xml (quiete the same).
<class name="A" table="a">
<id name="id" column="id_a" unsaved-value="0">
<generator class="identity">
<param name="sequence">a_id_seq</param>
</generator>
</id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
<set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
<key>
<column name="id_a" not-null="true" />
</key>
<one-to-many class="AC" />
</set>
</class>
<class name="C" table="c">
<id name="id" column="id_c" unsaved-value="0">
<generator class="identity">
<param name="sequence">c_id_seq</param>
</generator>
</id>
</class>
And then association mapping file, a_c.hbm.xml.
<class name="AC" table="a_c">
<composite-id name="id" class="ACId">
<key-many-to-one name="a" class="A" column="id_a" />
<key-many-to-one name="c" class="C" column="id_c" />
</composite-id>
<property name="extra" type="string" column="extra" />
</class>
Here is the code sample to test.
A = ADao.get(1);
C = CDao.get(1);
if(A != null && C != null){
boolean exists = false;
// just check if it's updated or not
for(AC a : a.getAC()){
if(a.getC().equals(c)){
// update field
a.setExtra("extra updated");
exists = true;
break;
}
}
// add
if(!exists){
ACId idAC = new ACId();
idAC.setA(a);
idAC.setC(c);
AC AC = new AC();
AC.setId(idAC);
AC.setExtra("extra added");
a.getAC().add(AC);
}
ADao.save(A);
}
You better install Ruby 2.2.5 for compatibility. The Ruby version in your local machine is different from the one declared in Gemfile.
If you're using rvm:
rvm install 2.2.5
rvm use 2.2.5
else if you're using rbenv:
rbenv install 2.2.5
rbenv local 2.2.5
else if you can not change ruby version by rbenv, read here
If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.
If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.
In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.
Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!
You just need to set :
/usr/bin/php path_to_your_php_file
in your crontab.
This line:
private dynamic defaultReminder =
reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder
will be initialized before defaultReminder
, so the above line might throw a NullReferenceException
.
Instead, just use:
private dynamic defaultReminder = TimeSpan.FromMinutes(15);
Alternatively, set up the value in the constructor:
private dynamic defaultReminder;
public Reminders()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
There are more details about this compiler error on MSDN - Compiler Error CS0236.
If you read all answer above and it still does not work...
Make sure that your PHP PDO connection string is fine. Not like mine:
$dbh = new PDO('"mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS)
There is no information in error message what driver was not found.
After reinstalling all possible PDO and MySQL libraries I found out that there was " at start of my connection string.
May I present my recursive Python solution to this problem?
def choose_iter(elements, length):
for i in xrange(len(elements)):
if length == 1:
yield (elements[i],)
else:
for next in choose_iter(elements[i+1:len(elements)], length-1):
yield (elements[i],) + next
def choose(l, k):
return list(choose_iter(l, k))
Example usage:
>>> len(list(choose_iter("abcdefgh",3)))
56
I like it for its simplicity.
Very simple code with Bootstrap and JQuery without any additionnal javascript code :
HTML :
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<form class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<label class="dropdown-item"><input type="checkbox" name="" value="one">First checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="two">Second checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="three">Third checkbox</label>
</form>
</div>
CSS :
.dropdown-menu label {
display: block;
}
double a = 1.000001;
double b = 0.000001;
System.out.println( a.compareTo(b) );
Returns:
-1 : 'a' is numerically less than 'b'.
0 : 'a' is equal to 'b'.
1 : 'a' is greater than 'b'.
Background You never ... really ... need to know the user's password. You just want to verify an incoming user knows the password for an account.
Hash It: Store user passwords hashed (one-way encryption) via a strong hash function. A search for "c# encrypt passwords" gives a load of examples.
See the online SHA1 hash creator for an idea of what a hash function produces (But don't use SHA1 as a hash function, use something stronger such as SHA256).
Now, a hashed passwords means that you (and database thieves) shouldn't be able to reverse that hash back into the original password.
How to use it: But, you say, how do I use this mashed up password stored in the database?
When the user logs in, they'll hand you the username and the password (in its original text) You just use the same hash code to hash that typed-in password to get the stored version.
So, compare the two hashed passwords (database hash for username and the typed-in & hashed password). You can tell if "what they typed in" matched "what the original user entered for their password" by comparing their hashes.
Extra credit:
Question: If I had your database, then couldn't I just take a cracker like John the Ripper and start making hashes until I find matches to your stored, hashed passwords? (since users pick short, dictionary words anyway ... it should be easy)
Answer: Yes ... yes they can.
So, you should 'salt' your passwords. See the Wikipedia article on salt
See "How to hash data with salt" C# example (archived)
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
Something like this should work, calling the ArrayList constructor that takes a Collection:
List theList = new ArrayList(coll);
If you're on macOS and installed postgres via homebrew, try restarting it with
brew services restart postgresql
If you're on Ubuntu, you can restart it with either one of these commands
sudo service postgresql restart
sudo /etc/init.d/postgresql restart
Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.
Make sure that you don't have the "me" in brackets.
Also if you can post the full code for the userform it would help massively.
If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.
For example, if you have a class called MyCustomObject
, that has a property called LongPropertyName
, you can use a custom resolver like this…
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MyCustomObject))
{
if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "Short";
}
}
return property;
}
}
Then call for serialization and supply the resolver:
var result = JsonConvert.SerializeObject(myCustomObjectInstance,
new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });
And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}
More info on custom resolvers here
I looked thru the answers above, I recommend pejman's Dec 29 '16 at 13:31 suggestion but he/she has not left a full answer. Here it is, I will put this as --> (you need a service and a listener $watch on one of the scopes from controllers for changes in the service area)
var app =
angular.module('myApp', ['ngRoute', 'ngSanitize']);
app.service('bridgeService', function () {
var msg = "";
return msg;
});
app.controller('CTRL_1'
, function ($scope, $http, bridgeService)
{
$http.get(_restApi, config)
.success(
function (serverdata, status, config) {
$scope.scope1Box = bridgeService.msg = serverdata;
});
});
app.controller('CTRL_2'
, function ($scope, $http, bridgeService)
{
$scope.$watch( function () {
return (bridgeService.msg);
}, function (newVal, oldVal) {
$scope.scope2Box = newVal;
}, true
);
});
As of latest Chrome/FF and on IE11 there's no need for -ms/-moz/-webkit prefix. Here's a shorter code (based on previous answers):
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
/* The animation part: */
animation-name: spin;
animation-duration: 4000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
Live Demo: http://jsfiddle.net/9Ryvs/3057/
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
The "int" instruction causes an interrupt.
Simple Answer: An interrupt, put simply, is an event that interrupts the CPU, and tells it to run a specific task.
Detailed Answer:
The CPU has a table of Interrupt Service Routines (or ISRs) stored in memory. In Real (16-bit) Mode, this is stored as the IVT, or Interrupt Vector Table. The IVT is typically located at 0x0000:0x0000
(physical address 0x00000
), and it is a series of segment-offset addresses that point to the ISRs. The OS may replace the pre-existing IVT entries with its own ISRs.
(Note: The IVT's size is fixed at 1024 (0x400) bytes.)
In Protected (32-bit) Mode, the CPU uses an IDT. The IDT is a variable-length structure that consists of descriptors (otherwise known as gates), which tell the CPU about the interrupt handlers. The structure of these descriptors is much more complex than the IVT's simple segment-offset entries; here it is:
bytes 0, 1: Lower 16 bits of the ISR's address.
bytes 2, 3: A code segment selector (in the GDT/LDT)
byte 4: Zero.
byte 5: A type field consisting of several bitfields.
bit 0: P (Present): 0 for unused interrupts, 1 for used interrupts.*
bits 1, 2: DPL (Descriptor Privilege Level): The privilege level the descriptor (bytes 2, 3) must have.
bit 3: S (Storage Segment): Is 0 for interrupt and trap gates. Otherwise, is one.
bits 4, 5, 6, 7: GateType:
0101: 32 bit task gate
0110: 16-bit interrupt gate
0111: 16-bit trap gate
1110: 32-bit interrupt gate
1111: 32-bit trap gate
*The IDT may be of variable size, but it must be sequential, i.e. if you declare your IDT to be from 0x00 to 0x50, you must have every interrupt from 0x00 to 0x50. The OS does not necessarily use all of them, so the Present bit allows the CPU to properly handle interrupts the OS does not intend to handle.
When an interrupt occurs (either by an external trigger (e.g. a hardware device) in an IRQ, or by the int
instruction from a program), the CPU pushes EFLAGS, then CS, and then EIP. (These are automatically restored by iret
, the interrupt return instruction.) The OS usually stores more information about the state of the machine, handles the interrupt, restores the machine state, and continues on.
In many *NIX OSes (including Linux), system calls are interrupt based. The program puts the arguments to the system call in the registers (EAX, EBX, ECX, EDX, etc..), and calls interrupt 0x80. The kernel has already set the IDT to contain an interrupt handler on 0x80, which is called when it receives interrupt 0x80. The kernel then reads the arguments and invokes a kernel function accordingly. It may store a return in EAX/EBX. System calls have largely been replaced by the sysenter
and sysexit
(or syscall
and sysret
on AMD) instructions, which allow for faster entry into ring 0.
This interrupt could have a different meaning in a different OS. Be sure to check its documentation.
Use following code
function trancateTitle (title) {
var length = 10;
if (title.length > length) {
title = title.substring(0, length)+'...';
}
return title;
}
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
I have found a solution. This worked for me:
import numpy as np
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
I had similar problems because of .gitignore for the /storage
folder on first machine, then cloned repository on second machine and laravel was revision to write down sessions cache
So, manually creating folder /storage/sessions
might be an solution..
$eval
and $parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.
Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.