I downgrade the support
previously it was
implementation 'com.android.support:appcompat-v7:27.0.2'
Use it
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
Its Working Happy Codng
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
This error can also occur when you load all google play services apis when you only using afew.
As stated by google:"In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.
From version 6.5, you can instead selectively compile Google Play service APIs into your app."
For example when your app needs play-services-maps ,play-services-location .You need to add only the two apis in your build.gradle file at app level as show below:
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
Instead of:
compile 'com.google.android.gms:play-services:10.2.1'
For full documentation and list of google play services apis click here
I changed the target=android-26
to target=android-23
project.properties
this works great for me.
On Linux or Ubuntu you need to use the complete path.
For example
/home/ubuntu/.android/keystorname.keystore
In my case I was using ~
instead of /home/user/
. Using shorthands like the below does not work
~/.android/keystorname.keystore
./keystorename.keystore
For me, dataBinding { enabled true } was enabled in gradle, removing this helped me
I meet the problem when using Firebase, i think different package cause the problem.
I solved by adding packeage of new app within Firebase Console, and download google-services.json again.
In my case the problem was because of capital letters in some packages.
Important note: You should only apply plugin at bottom of build.gradle (App level)
apply plugin: 'com.google.gms.google-services'
I mistakenly apply this plugin at top of the build.gradle. So I get error.
One more tips : You no need to remove even you use the 3.1.0 or above. Because google not officially announced
classpath 'com.google.gms:google-services:3.1.0'
For me the issue was caused by com.google.android.exoplayer
conflicting with com.facebook.android:audience-network-sdk
.
I fixed the problem by excluding the exoplayer
library from the audience-network-sdk
:
compile ('com.facebook.android:audience-network-sdk:4.24.0') {
exclude group: 'com.google.android.exoplayer'
}
The best answer is already given in the gradle output:
* Try:
Run with --stacktrace option to get the stack trace.
Open the Terminal in Android Studio and run gradlew :app:mergeDebugResources --stacktrace
.
(In my case it was the Windows 240 char limit), but it should give you the root cause for any other issue just as well.
You can set timeouts on the underlying HTTP client. If you don't specify a client, Retrofit will create one with default connect and read timeouts. To set your own timeouts, you need to configure your own client and supply it to the RestAdapter.Builder
.
An option is to use the OkHttp client, also from Square.
1. Add the library dependency
In the build.gradle, include this line:
compile 'com.squareup.okhttp:okhttp:x.x.x'
Where x.x.x
is the desired library version.
2. Set the client
For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 (FOR THE NEWER VERSIONS, SEE THE EDITS):
public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
EDIT 1
For okhttp versions since 3.x.x
, you have to set the dependency this way:
compile 'com.squareup.okhttp3:okhttp:x.x.x'
And set the client using the builder pattern:
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
More info in Timeouts
EDIT 2
Retrofit versions since 2.x.x
also uses the builder pattern, so change the return block above to this:
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
If using a code like my providesRestAdapter
method, then change the method return type to Retrofit.
More info in Retrofit 2 — Upgrade Guide from 1.9
ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES
:
okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
For more details about the units, see TimeUnit.
Maybe you can change your buildToolsVersion num.
this is my problem:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\ProgramTools\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1
my build.gradle:
android {
compileSdkVersion 23
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.pioneers.recyclerviewitemanimation"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
I just change buildToolsVersion to buildToolsVersion "23.0.2" and the problem was solved.
I noticed this commit comment in AOSP, the solution will be to exclude some files using DSL. Probably when 0.7.1 is released.
commit e7669b24c1f23ba457fdee614ef7161b33feee69
Author: Xavier Ducrohet <--->
Date: Thu Dec 19 10:21:04 2013 -0800
Add DSL to exclude some files from packaging.
This only applies to files coming from jar dependencies.
The DSL is:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
When Gradle builds your project, it puts all APKs in build/apk directory. You could also just do a simple recursive find command for *.apk in the top level directory of your project.
Here is a better description...
View full image at http://i.stack.imgur.com/XwjEZ.png
EDITED: This guy really brought it home and has a good little tutorial http://instantiatorgratification.blogspot.com/2013/05/google-play-services-with-android-studio.html
one side note: I had played around so much that I needed to do a gradlew clean
to get it to run succesfully
If you have imported your project or are working from the Sample Maps application located in \extras\google\google_play_services\samples\maps check out this tutorial.
https://stackoverflow.com/a/16598478/2414698
If you are creating a new project from scratch then note Xav's comments on that same post. He describes that Android Studio uses a different compiler and that you have to modify the build.gradle file manually. I did this with success. I copied
into my lib directory and added the following to my build.gradle file
dependencies {
compile files('libs/android-support-v4.jar')
compile files('libs/google-play-services.jar')
}
Also, if this is a new project check out this post, too.
Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.
The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:
/p:VisualStudioVersion=12.0
12.0
is for VS2013, replace with the version you use. Once I added this parameter, it just worked.
The complete command line looks like this:
MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0
I've found it here:
http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment
They state:
If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config
is not a valid variable name. $.FullName
should be $_.FullName
$
should be $_.Name
You could use robocopy:
robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E
I found a list of Java class file versions on the Wikipedia page that describes the class file format:
http://en.wikipedia.org/wiki/Java_class_file#General_layout
Under byte offset 6 & 7, the versions are listed with which Java VM they correspond to.
select t1.* from
(select * from TABLE Where CCC='D' AND DDD='X') as t1,
(select * from TABLE Where CCC<>'D' AND DDD='X') as t2
Another way to do this!
echo $var
output highly depends on the value of IFS
variable. By default it contains space, tab, and newline characters:
[ks@localhost ~]$ echo -n "$IFS" | cat -vte
^I$
This means that when shell is doing field splitting (or word splitting) it uses all these characters as word separators. This is what happens when referencing a variable without double quotes to echo it ($var
) and thus expected output is altered.
One way to prevent word splitting (besides using double quotes) is to set IFS
to null. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05 :
If the value of IFS is null, no field splitting shall be performed.
Setting to null means setting to empty value:
IFS=
Test:
[ks@localhost ~]$ echo -n "$IFS" | cat -vte
^I$
[ks@localhost ~]$ var=$'key\nvalue'
[ks@localhost ~]$ echo $var
key value
[ks@localhost ~]$ IFS=
[ks@localhost ~]$ echo $var
key
value
[ks@localhost ~]$
my solution to the problem:
in footer add <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
First you need to add all untracked files. Use this command line:
git add *
Then commit using this command line :
git commit -a
Wikipedia ought to have a good answer, here's my thoughts:
If you want multiple lines consider this:
<textarea rows="2"></textarea>
Specify rows as needed.
Starting another dispatch before your reducer is finished is an anti-pattern, because the state you received at the beginning of your reducer will not be the current application state anymore when your reducer finishes. But scheduling another dispatch from within a reducer is NOT an anti-pattern. In fact, that is what the Elm language does, and as you know Redux is an attempt to bring the Elm architecture to JavaScript.
Here is a middleware that will add the property asyncDispatch
to all of your actions. When your reducer has finished and returned the new application state, asyncDispatch
will trigger store.dispatch
with whatever action you give to it.
// This middleware will just add the property "async dispatch" to all actions
const asyncDispatchMiddleware = store => next => action => {
let syncActivityFinished = false;
let actionQueue = [];
function flushQueue() {
actionQueue.forEach(a => store.dispatch(a)); // flush queue
actionQueue = [];
}
function asyncDispatch(asyncAction) {
actionQueue = actionQueue.concat([asyncAction]);
if (syncActivityFinished) {
flushQueue();
}
}
const actionWithAsyncDispatch =
Object.assign({}, action, { asyncDispatch });
const res = next(actionWithAsyncDispatch);
syncActivityFinished = true;
flushQueue();
return res;
};
Now your reducer can do this:
function reducer(state, action) {
switch (action.type) {
case "fetch-start":
fetch('wwww.example.com')
.then(r => r.json())
.then(r => action.asyncDispatch({ type: "fetch-response", value: r }))
return state;
case "fetch-response":
return Object.assign({}, state, { whatever: action.value });;
}
}
We can get a list of files inside a folder on the file system using various golang standard library functions.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
var (
root string
files []string
err error
)
root := "/home/manigandan/golang/samples"
// filepath.Walk
files, err = FilePathWalkDir(root)
if err != nil {
panic(err)
}
// ioutil.ReadDir
files, err = IOReadDir(root)
if err != nil {
panic(err)
}
//os.File.Readdir
files, err = OSReadDir(root)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
The
path/filepath
package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files, err
}
ioutil.ReadDir
reads the directory named by dirname and returns a list of directory entries sorted by filename.
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.
func OSReadDir(root string) ([]string, error) {
var files []string
f, err := os.Open(root)
if err != nil {
return files, err
}
fileInfo, err := f.Readdir(-1)
f.Close()
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Benchmark results.
Get more details on this Blog Post
Also wanted to add this (Python 3.7)
import json
with open("dict_to_json_textfile.txt", 'w') as fout:
json_dumps_str = json.dumps(a_dictionary, indent=4)
print(json_dumps_str, file=fout)
const
in C++ does not mean that a value is a constant.
const
in C++ implies that the client of a contract undertakes not to alter its value.
Whether the value of a const
expression changes becomes more evident if you are in an environment which supports thread based concurrency.
As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final
has.
eg:
#include <iostream>
int main ()
{
volatile const int x = 42;
std::cout << x << std::endl;
*const_cast<int*>(&x) = 7;
std::cout << x << std::endl;
return 0;
}
outputs 42 then 7.
Although x
marked as const
, as a non-const alias is created, x
is not a constant. Not every compiler requires volatile
for this behaviour (though every compiler is permitted to inline the constant)
With more complicated systems you get const/non-const aliases without use of const_cast
, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const
merely means that your code can't change it without a cast, not that the value is constant.
While it is possible to combine the results, I would advise against doing so.
You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.
You need to define a class for the bullets you want to hide. For examples
.no-bullets {
list-style-type: none;
}
Then apply it to the list you want hidden bullets:
<ul class="no-bullets">
All other lists (without a specific class) will show the bulltets as usual.
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e
or E
character (where the exponent is the number after the e
or E
):
A floating-point number consists of the following parts, in exactly the following order:
- Optionally, the first character may be a "
-
" character.- One or more characters in the range "
0—9
".- Optionally, the following parts, in exactly the following order:
- a "
.
" character- one or more characters in the range "
0—9
"- Optionally, the following parts, in exactly the following order:
- a "
e
" character or "E
" character- optionally, a "
-
" character or "+
" character- One or more characters in the range "
0—9
".
You can more simply run one of the following commands:
Latest version:
nvm install node --reinstall-packages-from=node
Stable (LTS) version:
nvm install lts/* --reinstall-packages-from=node
This will install the appropriate version and reinstall all packages from the currently used node version. This saves you from manually handling the specific versions.
Edit - added command for installing LTS version according to @m4js7er comment.
Based on Martin Atkins' solution, here is a complete, concise pure-Angular solution:
(function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
angular.module('config', []).constant('CONFIG', response.data);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
);
})();
This solution uses a self-executing anonymous function to get the $http service, request the config, and inject it into a constant called CONFIG when it becomes available.
Once completely, we wait until the document is ready and then bootstrap the Angular app.
This is a slight enhancement over Martin's solution, which deferred fetching the config until after the document is ready. As far as I know, there is no reason to delay the $http call for that.
Unit Testing
Note: I have discovered this solution does not work well when unit-testing when the code is included in your app.js
file. The reason for this is that the above code runs immediately when the JS file is loaded. This means the test framework (Jasmine in my case) doesn't have a chance to provide a mock implementation of $http
.
My solution, which I'm not completely satisfied with, was to move this code to our index.html
file, so the Grunt/Karma/Jasmine unit test infrastructure does not see it.
From Go 1.10 there is a strings.Builder
type, please take a look at this answer for more detail.
The benchmark code of @cd1 and other answers are wrong. b.N
is not supposed to be set in benchmark function. It's set by the go test tool dynamically to determine if the execution time of the test is stable.
A benchmark function should run the same test b.N
times and the test inside the loop should be the same for each iteration. So I fix it by adding an inner loop. I also add benchmarks for some other solutions:
package main
import (
"bytes"
"strings"
"testing"
)
const (
sss = "xfoasneobfasieongasbg"
cnt = 10000
)
var (
bbb = []byte(sss)
expected = strings.Repeat(sss, cnt)
)
func BenchmarkCopyPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
bs := make([]byte, cnt*len(sss))
bl := 0
for i := 0; i < cnt; i++ {
bl += copy(bs[bl:], sss)
}
result = string(bs)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkAppendPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, cnt*len(sss))
for i := 0; i < cnt; i++ {
data = append(data, sss...)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
buf := bytes.NewBuffer(make([]byte, 0, cnt*len(sss)))
for i := 0; i < cnt; i++ {
buf.WriteString(sss)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkCopy(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, 64) // same size as bootstrap array of bytes.Buffer
for i := 0; i < cnt; i++ {
off := len(data)
if off+len(sss) > cap(data) {
temp := make([]byte, 2*cap(data)+len(sss))
copy(temp, data)
data = temp
}
data = data[0 : off+len(sss)]
copy(data[off:], sss)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkAppend(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, 64)
for i := 0; i < cnt; i++ {
data = append(data, sss...)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferWrite(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var buf bytes.Buffer
for i := 0; i < cnt; i++ {
buf.Write(bbb)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferWriteString(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var buf bytes.Buffer
for i := 0; i < cnt; i++ {
buf.WriteString(sss)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkConcat(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var str string
for i := 0; i < cnt; i++ {
str += sss
}
result = str
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
Environment is OS X 10.11.6, 2.2 GHz Intel Core i7
Test results:
BenchmarkCopyPreAllocate-8 20000 84208 ns/op 425984 B/op 2 allocs/op
BenchmarkAppendPreAllocate-8 10000 102859 ns/op 425984 B/op 2 allocs/op
BenchmarkBufferPreAllocate-8 10000 166407 ns/op 426096 B/op 3 allocs/op
BenchmarkCopy-8 10000 160923 ns/op 933152 B/op 13 allocs/op
BenchmarkAppend-8 10000 175508 ns/op 1332096 B/op 24 allocs/op
BenchmarkBufferWrite-8 10000 239886 ns/op 933266 B/op 14 allocs/op
BenchmarkBufferWriteString-8 10000 236432 ns/op 933266 B/op 14 allocs/op
BenchmarkConcat-8 10 105603419 ns/op 1086685168 B/op 10000 allocs/op
Conclusion:
CopyPreAllocate
is the fastest way; AppendPreAllocate
is pretty close to No.1, but it's easier to write the code.Concat
has really bad performance both for speed and memory usage. Don't use it.Buffer#Write
and Buffer#WriteString
are basically the same in speed, contrary to what @Dani-Br said in the comment. Considering string
is indeed []byte
in Go, it makes sense.Copy
with extra book keeping and other stuff.Copy
and Append
use a bootstrap size of 64, the same as bytes.BufferAppend
use more memory and allocs, I think it's related to the grow algorithm it use. It's not growing memory as fast as bytes.BufferSuggestion:
Append
or AppendPreAllocate
. It's fast enough and easy to use.bytes.Buffer
of course. That's what it's designed for."Book Author Title".parameterize('_').to_sym
=> :book_author_title
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
parameterize is a rails method, and it lets you choose what you want the separator to be. It is a dash "-" by default.
New method in Django 3
you can use Field.choices Enumeration Types new update in django3 like this :
from django.db import models
class Status(models.TextChoices):
UNPUBLISHED = 'UN', 'Unpublished'
PUBLISHED = 'PB', 'Published'
class Book(models.Model):
status = models.CharField(
max_length=2,
choices=Status.choices,
default=Status.UNPUBLISHED,
)
View -> debug console (Ctrl+Shift+Y) next to debug console is terminal
You can use the numeric_limits<data_type>::min()
and numeric_limits<data_type>::max()
functions present in limits
header file and find the limits of each data type.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
cout<<"Limits of Data types:\n";
cout<<"char\t\t\t: "<<static_cast<int>(numeric_limits<char>::min())<<" to "<<static_cast<int>(numeric_limits<char>::max())<<endl;
cout<<"unsigned char\t\t: "<<static_cast<int>(numeric_limits<unsigned char>::min())<<" to "<<static_cast<int>(numeric_limits<unsigned char>::max())<<endl;
cout<<"short\t\t\t: "<<numeric_limits<short>::min()<<" to "<<numeric_limits<short>::max()<<endl;
cout<<"unsigned short\t\t: "<<numeric_limits<unsigned short>::min()<<" to "<<numeric_limits<unsigned short>::max()<<endl;
cout<<"int\t\t\t: "<<numeric_limits<int>::min()<<" to "<<numeric_limits<int>::max()<<endl;
cout<<"unsigned int\t\t: "<<numeric_limits<unsigned int>::min()<<" to "<<numeric_limits<unsigned int>::max()<<endl;
cout<<"long\t\t\t: "<<numeric_limits<long>::min()<<" to "<<numeric_limits<long>::max()<<endl;
cout<<"unsigned long\t\t: "<<numeric_limits<unsigned long>::min()<<" to "<<numeric_limits<unsigned long>::max()<<endl;
cout<<"long long\t\t: "<<numeric_limits<long long>::min()<<" to "<<numeric_limits<long long>::max()<<endl;
cout<<"unsiged long long\t: "<<numeric_limits<unsigned long long>::min()<<" to "<<numeric_limits<unsigned long long>::max()<<endl;
cout<<"float\t\t\t: "<<numeric_limits<float>::min()<<" to "<<numeric_limits<float>::max()<<endl;
cout<<"double\t\t\t: "<<numeric_limits<double>::min()<<" to "<<numeric_limits<double>::max()<<endl;
cout<<"long double\t\t: "<<numeric_limits<long double>::min()<<" to "<<numeric_limits<long double>::max()<<endl;
}
The output will be: Limits of Data types:
Use this -
create table dummy_table_name as select * from source_table_name;
This will create the new table with existing data available on source_table_name
.
As here str(u'\u2013')
is causing error so use isinstance(foo,basestring)
to check for unicode/string, if not of type base string convert it into Unicode and then apply encode
if isinstance(foo,basestring):
foo.encode('utf8')
else:
unicode(foo).encode('utf8')
Try using an empty collapse argument within the paste function:
paste(sdata, collapse = '')
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
A late but useful answer, PHP has a function specifically for this purpose.
$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end
new[] { "item" }.ToList();
It's shorter than
new List<string> { "item" };
and you don't have to specify the type.
jQuery('.validatedForm').validate({
rules : {
password : {
minlength : 5
},
password_confirm : {
minlength : 5,
equalTo : '[name="password"]'
}
}
In general, you will not use id="password"
like this.
So, you can use [name="password"]
instead of "#password"
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
You just need to set background and give previous.xml file in background of button in your layout file.
<Button
android:id="@+id/button1"
android:background="@drawable/previous"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
and done.Edit Following is previous.xml file in drawable directory
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>
If you want to obtain it from query instead of psql, you can query the catalog schema. Here's a complex query that does that:
SELECT
f.attnum AS number,
f.attname AS name,
f.attnum,
f.attnotnull AS notnull,
pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,
CASE
WHEN p.contype = 'p' THEN 't'
ELSE 'f'
END AS primarykey,
CASE
WHEN p.contype = 'u' THEN 't'
ELSE 'f'
END AS uniquekey,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.confkey
END AS foreignkey_fieldnum,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.conkey
END AS foreignkey_connnum,
CASE
WHEN f.atthasdef = 't' THEN d.adsrc
END AS default
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
JOIN pg_type t ON t.oid = f.atttypid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
WHERE c.relkind = 'r'::char
AND n.nspname = '%s' -- Replace with Schema name
AND c.relname = '%s' -- Replace with table name
AND f.attnum > 0 ORDER BY number
;
It's pretty complex but it does show you the power and flexibility of the PostgreSQL system catalog and should get you on your way to pg_catalog mastery ;-). Be sure to change out the %s's in the query. The first is Schema and the second is the table name.
EMAILCC=" -c [email protected],[email protected]"
TURNO_EMAIL="[email protected]"
mailx $EMAILCC -s "$(echo "Status: Control Aplicactivo \nContent-Type: text/html")" $TURNO_EMAIL < tmp.tmp
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
According to the Javadocs:
The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
A StackTraceElement
has getClassName()
, getFileName()
, getLineNumber()
and getMethodName()
.
You will have to experiment to determine which index you want
(probably stackTraceElements[1]
or [2]
).
Storing files in your database will lead to a huge database size. You may not like that, for development, testing, backups, etc.
Instead, you'd use FileStream (SQL-Server) or BFILE (Oracle).
There is no default-implementation of BFILE/FileStream in Postgres, but you can add it: https://github.com/darold/external_file
And further information (in french) can be obtained here:
http://blog.dalibo.com/2015/01/26/Extension_BFILE_pour_PostgreSQL.html
To answer the acual question:
Apart from bytea
, for really large files, you can use LOBS:
// http://stackoverflow.com/questions/14509747/inserting-large-object-into-postgresql-returns-53200-out-of-memory-error
// https://github.com/npgsql/Npgsql/wiki/User-Manual
public int InsertLargeObject()
{
int noid;
byte[] BinaryData = new byte[123];
// Npgsql.NpgsqlCommand cmd ;
// long lng = cmd.LastInsertedOID;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
using (Npgsql.NpgsqlTransaction transaction = connection.BeginTransaction())
{
try
{
NpgsqlTypes.LargeObjectManager manager = new NpgsqlTypes.LargeObjectManager(connection);
noid = manager.Create(NpgsqlTypes.LargeObjectManager.READWRITE);
NpgsqlTypes.LargeObject lo = manager.Open(noid, NpgsqlTypes.LargeObjectManager.READWRITE);
// lo.Write(BinaryData);
int i = 0;
do
{
int length = 1000;
if (i + length > BinaryData.Length)
length = BinaryData.Length - i;
byte[] chunk = new byte[length];
System.Array.Copy(BinaryData, i, chunk, 0, length);
lo.Write(chunk, 0, length);
i += length;
} while (i < BinaryData.Length);
lo.Close();
transaction.Commit();
} // End Try
catch
{
transaction.Rollback();
throw;
} // End Catch
return noid;
} // End Using transaction
} // End using connection
} // End Function InsertLargeObject
public System.Drawing.Image GetLargeDrawing(int idOfOID)
{
System.Drawing.Image img;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
lock (connection)
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
NpgsqlTypes.LargeObject lo = lbm.Open(takeOID(idOfOID), NpgsqlTypes.LargeObjectManager.READWRITE); //take picture oid from metod takeOID
byte[] buffer = new byte[32768];
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int read;
while ((read = lo.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
} // Whend
img = System.Drawing.Image.FromStream(ms);
} // End Using ms
lo.Close();
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End lock connection
} // End Using connection
return img;
} // End Function GetLargeDrawing
public void DeleteLargeObject(int noid)
{
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
lbm.Delete(noid);
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End Using connection
} // End Sub DeleteLargeObject
There is an option in WinSCP that does exactly what you are looking for:
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
String[][] shades = new String[intSize][intSize];
// print array in rectangular form
for (int r=0; r<shades.length; r++) {
for (int c=0; c<shades[r].length; c++) {
shades[r][c]="hello";//your value
}
}
Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:
total = 0;
for i = 1:numel(A)
total = total+A(i);
end
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
grep -a will force grep to search and output from a file that grep thinks is binary. grep -a re test.log
This is more of a suggestion on how NOT to do it. I've just had a bad time finding a bug in a rather big Perl application. Most of the modules had its own configuration files. To read the configuration files as-a-whole, I found this single line of Perl somewhere on the Internet:
# Bad! Don't do that!
my $content = do{local(@ARGV,$/)=$filename;<>};
It reassigns the line separator as explained before. But it also reassigns the STDIN.
This had at least one side effect that cost me hours to find: It does not close the implicit file handle properly (since it does not call close
at all).
For example, doing that:
use strict;
use warnings;
my $filename = 'some-file.txt';
my $content = do{local(@ARGV,$/)=$filename;<>};
my $content2 = do{local(@ARGV,$/)=$filename;<>};
my $content3 = do{local(@ARGV,$/)=$filename;<>};
print "After reading a file 3 times redirecting to STDIN: $.\n";
open (FILE, "<", $filename) or die $!;
print "After opening a file using dedicated file handle: $.\n";
while (<FILE>) {
print "read line: $.\n";
}
print "before close: $.\n";
close FILE;
print "after close: $.\n";
results in:
After reading a file 3 times redirecting to STDIN: 3
After opening a file using dedicated file handle: 3
read line: 1
read line: 2
(...)
read line: 46
before close: 46
after close: 0
The strange thing is, that the line counter $.
is increased for every file by one. It's not reset, and it does not contain the number of lines. And it is not reset to zero when opening another file until at least one line is read. In my case, I was doing something like this:
while($. < $skipLines) {<FILE>};
Because of this problem, the condition was false because the line counter was not reset properly. I don't know if this is a bug or simply wrong code... Also calling close;
oder close STDIN;
does not help.
I replaced this unreadable code by using open, string concatenation and close. However, the solution posted by Brad Gilbert also works since it uses an explicit file handle instead.
The three lines at the beginning can be replaced by:
my $content = do{local $/; open(my $f1, '<', $filename) or die $!; my $tmp1 = <$f1>; close $f1 or die $!; $tmp1};
my $content2 = do{local $/; open(my $f2, '<', $filename) or die $!; my $tmp2 = <$f2>; close $f2 or die $!; $tmp2};
my $content3 = do{local $/; open(my $f3, '<', $filename) or die $!; my $tmp3 = <$f3>; close $f3 or die $!; $tmp3};
which properly closes the file handle.
the problem might be that networkservice has no read rights
salution:
rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply
This <?>
is a beast. It often leads to confusion and errors, because, when you see it first, then you start believing, <?>
is a wildcard for any java type. Which is .. not true. <?>
is the unknown type, a slight and nasty difference.
It's not a problem when you use it with Class
. Both lines work and compile:
Class anyType = String.class;
Class <?> theUnknownType = String.class;
But - if we start using it with collections, then we see strange compiletime errors:
List<?> list = new ArrayList<Object>(); // ArrayList<?> is not allowed
list.add("a String"); // doesn't compile ...
Our List<?>
is not a collection, that is suitable for just any type of object. It can only store one type: the mystic "unkown type". Which is not a real type, for sure.
Starting in Python 2.6 there is a operator.methodcaller function.
So you can get something more elegant (and fast):
from operator import methodcaller
map(methodcaller('method_name'), list_of_objects)
The problem is related to Sam´s response:
"have encountered the same problem you have. I found that it may have some relationship with the way you terminate your run result. When you run your code, whether it has a printout, the debugger will call the console which print a "Press any key to continue...". If you terminate the console by pressing key, it's ok; if you do it by click the close button, the problem comes as you described. When you terminate it in the latter way, you have to wait several minutes before you can rebuild your code."
Avoid kill processes, and we have two choices, wait until the process release the .EXE file or this problem will be solved faster restarting the IDE.
Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg'
in your constructor. It will work definitely.
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
Or you can:
hadoop fs -rm -r PATH
Hint: if you enter:
hadoop fs -rmr PATH
you would mostly get:Please use 'rm -r' instead.
I ran into this same issue recently, posted the my solution also here: Preventing element from displaying on top of footer when using position:fixed
You can achieve a solution leveraging the position
property of the element with jQuery, switching between the default value (static
for divs
), fixed
and absolute
.
You will also need a container element for your fixed element. Finally, in order to prevent the fixed element to go over the footer, this container element can't be the parent of the footer.
The javascript part involves calculating the distance in pixels between your fixed element and the top of the document, and comparing it with the current vertical position of the scrollbar relatively to the window object (i.e. the number of pixels above that are hidden from the visible area of the page) every time the user scrolls the page. When, on scrolling down, the fixed element is about to disappear above, we change its position to fixed and stick on top of the page.
This causes the fixed element to go over the footer when we scroll to the bottom, especially if the browser window is small. Therefore, we will calculate the distance in pixels of the footer from the top of the document and compare it with the height of the fixed element plus the vertical position of the scrollbar: when the fixed element is about to go over the footer, we will change its position to absolute and stick at the bottom, just over the footer.
Here's a generic example.
The HTML structure:
<div id="content">
<div id="leftcolumn">
<div class="fixed-element">
This is fixed
</div>
</div>
<div id="rightcolumn">Main content here</div>
<div id="footer"> The footer </div>
</div>
The CSS:
#leftcolumn {
position: relative;
}
.fixed-element {
width: 180px;
}
.fixed-element.fixed {
position: fixed;
top: 20px;
}
.fixed-element.bottom {
position: absolute;
bottom: 356px; /* Height of the footer element, plus some extra pixels if needed */
}
The JS:
// Position of fixed element from top of the document
var fixedElementOffset = $('.fixed-element').offset().top;
// Position of footer element from top of the document.
// You can add extra distance from the bottom if needed,
// must match with the bottom property in CSS
var footerOffset = $('#footer').offset().top - 36;
var fixedElementHeight = $('.fixed-element').height();
// Check every time the user scrolls
$(window).scroll(function (event) {
// Y position of the vertical scrollbar
var y = $(this).scrollTop();
if ( y >= fixedElementOffset && ( y + fixedElementHeight ) < footerOffset ) {
$('.fixed-element').addClass('fixed');
$('.fixed-element').removeClass('bottom');
}
else if ( y >= fixedElementOffset && ( y + fixedElementHeight ) >= footerOffset ) {
$('.fixed-element').removeClass('fixed');
$('.fixed-element').addClass('bottom');
}
else {
$('.fixed-element').removeClass('fixed bottom');
}
});
There is another way to do this.
From iTerm2 2.9.20140923 you can use Dynamic Profiles as stated in the documentation page:
Dynamic Profiles is a feature that allows you to store your profiles in a file outside the usual macOS preferences database. Profiles may be changed at runtime by editing one or more plist files (formatted as JSON, XML, or in binary). Changes are picked up immediately.
So it is possible to create a file like this one:
{
"Profiles": [{
"Name": "MYSERVER1",
"Guid": "MYSERVER1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "M",
"Tags": [
"LOCAL", "THATCOMPANY", "WORK", "NOCLOUD"
],
"Badge Text": "SRV1",
},
{
"Name": "MYOCEANSERVER1",
"Guid": "MYOCEANSERVER1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "O",
"Tags": [
"THATCOMPANY", "WORK", "DIGITALOCEAN"
],
"Badge Text": "PPOCEAN1",
},
{
"Name": "PI1",
"Guid": "PI1",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "1",
"Tags": [
"LOCAL", "PERSONAL", "RASPBERRY", "SMALL"
],
"Badge Text": "LocalServer",
},
{
"Name": "VUZERO",
"Guid": "VUZERO",
"Custom Command": "Yes",
"Command": "ssh [email protected]",
"Shortcut": "0",
"Tags": [
"LOCAL", "PERSONAL", "SMALL"
],
"Badge Text": "TeleVision",
}
]
}
in the folder ~/Library/Application\ Support/iTerm2/DynamicProfiles/
and share it across different machines.
This enables you to retain some visual differences among iterm2 installations such as font type or dimension, while synchronising remote hosts, shortcuts, commands, and even a small badge to quickly identify a session
Since version 2.10, one can use Scala's string interpolation feature:
implicit class RegexOps(sc: StringContext) {
def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}
scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true
Even better one can bind regular expression groups:
scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123
scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25
It is also possible to set more detailed binding mechanisms:
scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler
scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20
scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive
scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10
An impressive example on what's possible with Dynamic
is shown in the blog post Introduction to Type Dynamic:
object T {
class RegexpExtractor(params: List[String]) {
def unapplySeq(str: String) =
params.headOption flatMap (_.r unapplySeq str)
}
class StartsWithExtractor(params: List[String]) {
def unapply(str: String) =
params.headOption filter (str startsWith _) map (_ => str)
}
class MapExtractor(keys: List[String]) {
def unapplySeq[T](map: Map[String, T]) =
Some(keys.map(map get _))
}
import scala.language.dynamics
class ExtractorParams(params: List[String]) extends Dynamic {
val Map = new MapExtractor(params)
val StartsWith = new StartsWithExtractor(params)
val Regexp = new RegexpExtractor(params)
def selectDynamic(name: String) =
new ExtractorParams(params :+ name)
}
object p extends ExtractorParams(Nil)
Map("firstName" -> "John", "lastName" -> "Doe") match {
case p.firstName.lastName.Map(
Some(p.Jo.StartsWith(fn)),
Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
println(s"Match! $fn ...$lastChar")
case _ => println("nope")
}
}
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
You can fix the errors by validating your input, which is something you should do regardless of course.
The following typechecks correctly, via type guarding validations
const DNATranscriber = {
G: 'C',
C: 'G',
T: 'A',
A: 'U'
};
export default class Transcriptor {
toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.
In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function
, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.
const DNATranscriber = {
G = 'C',
C = 'G',
T = 'A',
A = 'U'
};
export default function toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
Update:
Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures.
const DNATranscriber = {
G = 'C',
C = 'G',
T = 'A',
A = 'U'
} as const;
type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];
export default function toRna(dna: string): RNACodon[] {
const codons = [...dna];
validateSequence(codons);
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function validateSequence(values: string[]): asserts values is DNACodon[] {
if (!values.every(isValidCodon)) {
throw Error('invalid sequence');
}
}
function isValidCodon(value: string): value is DNACodon {
return value in DNATranscriber;
}
You can read more about assertion signatures in the TypeScript 3.7 release notes.
Use this code:
<?php
$var = "This is Ashok's Pen.";
mysql_real_escape_string($var);
?>
This will solve your problem, because the database can't detect the special characters of a string.
What do you think about this approach?
<body class="thatClass anotherClass"> </body>
var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );
Split your date into year, month, and day components then use Date:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Date will take care of fixing the year.
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
To use Toolbar as an Action Bar, first disable the decor-provided Action Bar.
The easiest way is to have your theme extend from
Theme.AppCompat.NoActionBar
(or its light variant).
Second, create a Toolbar instance, usually via your layout XML:
<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:minHeight=”?attr/actionBarSize”
android:background=”?attr/colorPrimary” />
Then in your Activity or Fragment, set the Toolbar to act as your Action Bar:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blah);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
}
This code worked for me.
You can union the queries as long as the columns match.
SELECT name,
games,
goals
FROM tblMadrid
WHERE id = 1
UNION ALL
SELECT name,
games,
goals
FROM tblBarcelona
WHERE id = 2
The easiest way to quickly view large varchar/text column:
declare @t varchar(max)
select @t = long_column from table
print @t
Android Studio --> Preferences --> Editors --> Auto Import
I tested and used this command in kafka confluent V4.0.0
and apache kafka V 1.0.0 and 1.0.1
/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config retention.ms=55000
test
is the topic name.
I think it works well in other versions too
In my case it was libjpeg
. All I had to do was run brew reinstall libjpeg
and everything just worked!
I think you are trying to check whether the array is empty or not.You can do like this :
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
Reference isEmpty()
You can use the jquery-backstretch image which allows for animated slideshows as your background-images!
https://github.com/jquery-backstretch/jquery-backstretch Scroll down to setup and all of the documentation is there.
GetUserId()
is an extension method on IIdentity
and it is in Microsoft.AspNet.Identity.IdentityExtensions
. Make sure you have added the namespace with using Microsoft.AspNet.Identity;
.
for_example, you have anyFile.php, and there is written $any_variable='hi Frank';
to change that variable to hi Jack
, use like the following code:
<?php
$content = file_get_contents('anyFile.php');
$new_content = preg_replace('/\$any_variable=\"(.*?)\";/', '$any_variable="hi Jack";', $content);
file_put_contents('anyFile.php', $new_content);
?>
first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab)
if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation
if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns
Of all the gems I tried, show_data
gem worked the best for me, I now use it extensively to log params hash in Rails pretty much all the time
Here is example given which so how to use open
and "python close
from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()
It's necessary to how many times you opened file have to close that times.
You can simply use the border class from bootstrap:
<div class="row border border-dark">
...
</div>
For more details visit the following link: Borders
port 443 is not open, just allow custom tcp port 443 if on AWS else open the port 443 for the outbound connections ...
You need to use framelayout. And the better way to do this is to make the view invisible when thay are not require. Also you need to set the position for each and every view,So that they will move according to there corresponding position
While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.
Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter
@ECHO OFF
REM testing at cmd : sc query "MSSQLSERVER" | findstr RUNNING
REM "MSSQLSERVER" is the name of Service for sample
sc query "MSSQLSERVER" %1 | findstr RUNNING
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo Oh noooo.. trouble mas bro
goto end
:started
echo "SQL Server (MSSQLSERVER)" is started
goto end
:stopped
echo "SQL Server (MSSQLSERVER)" is stopped
echo Starting service
net start "MSSQLSERVER"
goto end
:erro
echo Error please check your command.. mas bro
goto end
:end
You can handle the attribute onClick for both i.e. 'ok' & 'cancel' condition like ternary operator
Scenario: Here is the scenario that I wants to show confirm box which will ask for 'ok' or 'cancel' while performing a delete action. In that I want if user click on 'ok' then the form action will redirect to page location and on cancel page will not respond.
Adding further explanation i'm having one button with type="submit" which is originally use default form action of form tag. and I want above scenario on delete button with same input type.
So below code is working properly for me
onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;"
Full code
<input type="submit" name="action" id="Delete" value="Delete" onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;">
And by the way I'm implementing this code as inline in html element using PHP. so that's why I used 'echo $_SERVER['PHP_SELF']'.
I hope it will work for you also. Thank You
Thanks for all your answers.
Free currencyconverterapi:
A sample conversion URL is: http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y
For posterity here they are along with other possible answers:
Discontinued as of 2017-11-06 with message
It has come to our attention that this service is being used in violation of the Yahoo Terms of Service. As such, the service is being discontinued. For all future markets and equities data research, please refer to finance.yahoo.com.
Request: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X
This CSV was being used by a jQuery plugin called Curry. Curry has since (2017-08-29) moved to use fixer.io instead due to stability issues.
Might be useful if you need more than just a CSV.
Here is the YQL query builder, where you can test a query and copy the url: (NO LONGER AVAILABLE)
Free for personal use (1000 hits per month)
Changing "base" (from "USD") is not allowed in Free account
Requires registration.
Request: http://openexchangerates.org/latest.json
Response:
<!-- language: lang-js -->
{
"disclaimer": "This data is collected from various providers ...",
"license": "all code open-source under GPL v3 ...",
"timestamp": 1323115901,
"base": "USD",
"rates": {
"AED": 3.66999725,
"ALL": 102.09382091,
"ANG": 1.78992886,
// 115 more currency rates here ...
}
}
Free Plan for 250 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
Documentation: currencylayer.com/documentation
JSON Response:
<!-- language: lang-js -->
{
[...]
"timestamp": 1436284516,
"source": "USD",
"quotes": {
"USDAUD": 1.345352401,
"USDCAD": 1.27373397,
"USDCHF": 0.947845302,
"USDEUR": 0.91313905,
"USDGBP": 0.647603397,
// 168 world currencies
}
}
Free Plan (1000 hits per month)
Changing 'Base' (From 'USD') is not allowed in free account
Requires registration
Data updated every 60 sec.
179 currencies worldwide including currencies, metals, and cryptocurrencies
Support (Even on the free plan) Shell,Node.js, Java, Python, PHP, Ruby, JS, C#, C, Go, Swift.
Documentation: https://currencyfreaks.com/documentation.html
Endpoint:
$ curl 'https://api.currencyfreaks.com/latest?apikey=YOUR_APIKEY'
JSON Response:
{
"date": "2020-10-08 12:29:00+00",
"base": "USD",
"rates": {
"FJD": "2.139",
"MXN": "21.36942",
"STD": "21031.906016",
"LVL": "0.656261",
"SCR": "18.106031",
"CDF": "1962.53482",
"BBD": "2.0",
"GTQ": "7.783265",
"CLP": "793.0",
"HNL": "24.625383",
"UGX": "3704.50271",
"ZAR": "16.577611",
"TND": "2.762",
"CUC": "1.000396",
"BSD": "1.0",
"SLL": "9809.999914",
"SDG": 55.325,
"IQD": "1194.293591",
.
.
.
[179 currencies]
}
}
Free Plan for 1,000 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
This API endpoint is deprecated and will stop working on June 1st, 2018. For more information please visit: https://github.com/fixerAPI/fixer#readme)
Docs:
http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev
Request: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
XML Response:
<!-- language: lang-xml -->
<Cube>
<Cube time="2015-07-07">
<Cube currency="USD" rate="1.0931"/>
<Cube currency="JPY" rate="133.88"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.100"/>
</Cube>
According to the website:
Exchange rates API is a free service for current and historical foreign exchange rates published by the European Central BankThis service is compatible with fixer.io and is really easy to use: no API key needed. For example (this uses CURL, but you can use your favourite requesting tool):
> curl https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD
{"base":"GBP","rates":{"USD":1.264494191},"date":"2019-05-29"}
Free Plan for 1250 monthly hits
150 Crypto and physical currencies - live updates
Base currency is set as USD on free account
Requires registration.
Documentation: currencyapi.net/documentation
JSON Response:
{
"valid": true,
"updated": 1567957373,
"base": "USD",
"rates": {
"AED": 3.673042,
"AFN": 77.529504,
"ALL": 109.410403,
// 165 currencies + some cryptos
}
}
Website: https://labstack.com/currency
Documentation: https://labstack.com/docs/api/currency/convert
Pricing: https://labstack.com/pricing
Request: https://currency.labstack.com/api/v1/convert/1/USD/INR
Response:
```js
{
"time": "2019-10-09T21:15:00Z",
"amount": 71.1488
}
```
1: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
In my case, similar to Basim, there was a NuGet package that was telling the compiler we needed C# 6, which we didn't.
We had to remove the NuGet package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
which then removed:
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform"
version="1.0.0" targetFramework="net452" />
from the
packages.config file<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
In the system.codedom
node, you can see why it was bringing in roslyn: compilerOptions="/langversion:6
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
Just searched for the docs, and found this:
Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
Posting a note here for users looking into this into the future. Google's libphonenumber
is what you most likely would want to use. There is wrappers for PHP, node.js, Java, etc. to use the data which Google has been collecting and reduces the requirements for maintaining large arrays of regex patterns to apply.
Could do it with :contains()
selector as well:
$('#toptitle:contains("Profil")').text("New word");
example: http://jsfiddle.net/niklasvh/xPRzr/
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
Apparently, adding:
td {
display: block; /* or inline-block */
}
solves the problem as well.
Another possible solution is to set table-layout: fixed;
for the table, and also set it's width
. For example: http://jsfiddle.net/fd3Zx/5/
jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex'),"
54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67
jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex')," | python -c "print raw_input().decode('hex'),"
The quick brown fox jumps over the lazy dog
it could be done with Python3 as well, but differently, and I'm a lazy dog.
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
cat ip_addresses | sort | uniq -c | sort -nr | awk '{print $2 " " $1}'
this command would give you desired output
Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where let
might mean a value, or a variable that can be assigned, but not changed, which in turn lets the compiler catch more programming errors and optimize code better.
JavaScript has had var
from the beginning, so they just needed another keyword, and just borrowed from dozens of other languages that use let
already as a traditional keyword as close to var
as possible, although in JavaScript let
creates block scope local variable instead.
here is an example i did on change i get children of the first select in second select
jQuery(document).ready(function($) {
$('.your_select').change(function() {
$.ajaxSetup({
headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
});
$.ajax({
type:'POST',
url: 'Link',
data:{
'id': $(this).val()
},
success:function(r){
$.each(r, function(res) {
console.log(r[res].Nom);
$('.select_to_populate').append($("<option />").val(r[res].id).text(r[res].Nom));
});
},error:function(r) {
alert('Error');
}
});
});
});enter code here
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
I had the same errors with CMake. In my case, I have used the wrong Visual Studio version in the initial CMake dialog where we have to select the Visual Studio compiler.
Then I changed it to "Visual Studio 11 2012" and things worked. (I have Visual Studio Ultimate 2012 version on my PC). In general, try to input an older version of Visual Studio version in the initial CMake configuration dialog.
I known this isn't markdown, but <p align="center">
worked for me, so if anyone figures out the markdown syntax instead I'll be happy to use that. Until then I'll use the HTML tag.
Use this:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
Since XML is a text format and images are usually not (except some ancient and archaic formats) there is no really sensible way to do it. Looking at things like ODT or OOXML also shows you that they don't embed images directly into XML.
What you can do, however, is convert it to Base64 or similar and embed it into the XML.
XML's whitespace handling may further complicate things in such cases, though.
Try:
SELECT into #T1 execute ('execute ' + @SQLString )
And this smells real bad like an sql injection vulnerability.
correction (per @CarpeDiem's comment):
INSERT into #T1 execute ('execute ' + @SQLString )
also, omit the 'execute'
if the sql string is something other than a procedure
I've got the error in my windows 10 so I set permission as the following and it works.
In details, remove other users/groups until it has only 'SYSTEM' and 'Administrators'. Then add your windows login into it with Read permission only.
Note the id_rsa
file is under the c:\users\<username>
folder.
You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
You can check if now is before or after today's 8am:
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False
The key lies in when you create the project in eclipse.
First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.
In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. Then you can push to github.
N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.
I'd start by the distinction that exists in Scala between def, val and var.
def - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.
val - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.
var - defines a mutable variable, initially set to the evaluated right side content.
Example, def
scala> def something = 2 + 3 * 4
something: Int
scala> something // now it's evaluated, lazily upon usage
res30: Int = 14
Example, val
scala> val somethingelse = 2 + 3 * 5 // it's evaluated, eagerly upon definition
somethingelse: Int = 17
Example, var
scala> var aVariable = 2 * 3
aVariable: Int = 6
scala> aVariable = 5
aVariable: Int = 5
According to above, labels from def and val cannot be reassigned, and in case of any attempt an error like the below one will be raised:
scala> something = 5 * 6
<console>:8: error: value something_= is not a member of object $iw
something = 5 * 6
^
When the class is defined like:
scala> class Person(val name: String, var age: Int)
defined class Person
and then instantiated with:
scala> def personA = new Person("Tim", 25)
personA: Person
an immutable label is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:
scala> personA.age = 44
personA.age: Int = 25
as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:
scala> var personB = new Person("Matt", 36)
personB: Person = Person@59cd11fe
scala> personB.age = 44
personB.age: Int = 44 // value re-assigned, as expected
as clear, from the mutable variable reference (i.e. 'personB') it is possible to modify the class mutable field 'age'.
I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.
Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.
PRINT 'It''s me, Arul.';
we are going to look on some other alternate ways of escaping the single quotes.
1.UNICODE Characters
39 is the UNICODE character of Single Quote. So we can use it like below.
PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';
2.QUOTED_IDENTIFIER
Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.
SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;
CONCLUSION
The above mentioned methods are applicable to both AZURE and On Premises .
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.
Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011
. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.
When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY
, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.
Whether that is the problem or not, you should always specify the date model:
UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');
Since you aren't specifying a time component - all Oracle DATE
columns include a time, even if it's midnight - you could also use a date literal:
UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';
You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.
you need to add the javascript language file,after the moment library, example:
<script type="text/javascript" src="js/moment/moment.js"></script>
<script type="text/javascript" src="js/moment/es.js"></script>
now you can set a language.
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({locale:'es'});
});
</script>
Here are all language: https://github.com/moment/moment
Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.
That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:
COUNT
, MIN
, MAX
, or TOP
.This article describes additional benefits and limitations of indexed views:
You Can…
- The view definition can reference one or more tables in the same database.
- Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
- You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.
You Can’t…
- The view definition can’t reference other views, or tables in other databases.
- It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
- You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
- You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.
As stated on Installing MySQL-python on mac :
pip uninstall MySQL-python
brew install mysql
pip install MySQL-python
Then test it :
python -c "import MySQLdb"
I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution
cell.cellView.addSubview(graph)
graph.tag = 10
now, in code block where you want to remove it (in your case gestureRecognizerFunction)
if let removable = cell.cellView.viewWithTag(10){
removable.removeFromSuperview()
}
to embed it again
cell.cellView.addSubview(graph)
graph.tag = 10
The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use
# dig
To get a TXT record of a specific host use
# dig example.com txt
# dig host.example.com txt
To query a specific name server just add @nameserver.tld
# dig host.example.com txt @a.iana-servers.net
The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.
I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch
This is the NPM known Issue for windows that NPM is pretty much unusable under Windows. This is of course related to the path size limitations.
https://github.com/npm/npm/issues/5641
My main concern here is that there are no mention of these issues when installing node or npm via the website. Not being able to install prime packages makes npm fundamentally unusable for windows.
HTML:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">
JavaScript:
function fun(obj) {
var uid= $(obj).attr('data-uid');
var name= $(obj).attr('data-name');
var value= $(obj).attr('data-value');
}
but I'm using jQuery.
Return a new array of given shape and type, filled with zeros.
or
Return a new array of given shape and type, filled with ones.
or
Return a new array of given shape and type, without initializing entries.
However, the mentality in which we construct an array by appending elements to a list is not much used in numpy, because it's less efficient (numpy datatypes are much closer to the underlying C arrays). Instead, you should preallocate the array to the size that you need it to be, and then fill in the rows. You can use numpy.append
if you must, though.
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
I came here from google so it might be relevant to others:
for yarn
you could use:
yarn --cwd /path/to/your/app run start
I used the implementation Nathan Leigh referenced and Kayvan N's and user2582318's suggested regex to remove all chars except digits to create the following version:
fun EditText.addCurrencyFormatter() {
// Reference: https://stackoverflow.com/questions/5107901/better-way-to-format-currency-input-edittext/29993290#29993290
this.addTextChangedListener(object: TextWatcher {
private var current = ""
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s.toString() != current) {
[email protected](this)
// strip off the currency symbol
// Reference for this replace regex: https://stackoverflow.com/questions/5107901/better-way-to-format-currency-input-edittext/28005836#28005836
val cleanString = s.toString().replace("\\D".toRegex(), "")
val parsed = if (cleanString.isBlank()) 0.0 else cleanString.toDouble()
// format the double into a currency format
val formated = NumberFormat.getCurrencyInstance()
.format(parsed / 100)
current = formated
[email protected](formated)
[email protected](formated.length)
[email protected](this)
}
}
})
}
This is an extension function in Kotlin which adds the TextWatcher to the TextChangedListener of the EditText.
In order to use it, just:
yourEditText = (EditText) findViewById(R.id.edit_text_your_id);
yourEditText.addCurrencyFormatter()
I hope it helps.
It turns out that lstlisting
is able to format code nicely, but requires a lot of tweaking.
Wikibooks has a good example for the parameters you can tweak.
As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE
which "shows the CREATE TABLE
statement that creates a given table, or the CREATE VIEW
statement that creates a given view."
Usage:
SHOW CREATE TABLE myTable;
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
As of ASP.NET Identity 3.0.0, This has been refactored into
//returns the userid claim value if present, otherwise returns null
User.GetUserId();
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).
I've spent a lot of time trying solutions from here and none of them helped me. After a few hours, I belive this will allow u to center vert any child element in BS3.
CSS
.vertical-center {
display: flex;
flex-direction: column;
justify-content: center;
}
HTML
<div class="col-md-6 vertical-center">
<div class="container">
<div class="row">
</div>
</div>
</div>
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Just use:
sed 's.\\./.g'
There's no reason to use /
as the separator in sed
. But if you really wanted to:
sed 's/\\/\//g'
I was given access to a database, but not the table where my query was being stored in.
Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.
I found that it can also search a database for a string.
It will search each table and give you how many times it found the string per table!
Serializable
Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable.
Parcelable
Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities.
SSLSHopper has some pretty thorough articles about moving between different servers.
http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html
Just pick the relevant link at bottom of this page.
Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.
You can still install and use Query Analyzer from previous SQL Server versions.
The Following code helps to search for a file in directory and open its location
import java.io.*;
import java.util.*;
import java.awt.Desktop;
public class Filesearch2 {
public static void main(String[] args)throws IOException {
Filesearch2 fs = new Filesearch2();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
fs.findFile(name,new File(directory));
}
public void findFile(String name,File file1)throws IOException
{
File[] list = file1.listFiles();
if(list!=null)
{
for(File file2 : list)
{
if (file2.isDirectory())
{
findFile(name,file2);
}
else if (name.equalsIgnoreCase(file2.getName()))
{
System.out.println("Found");
System.out.println("File found at : "+file2.getParentFile());
System.out.println("Path diectory: "+file2.getAbsolutePath());
String p1 = ""+file2.getParentFile();
File f2 = new File(p1);
Desktop.getDesktop().open(f2);
}
}
}
}
}
You can't, but if you want, you can do some trick. :)
public struct Orientation
{
...
public static Orientation None = -1;
public static Orientation North = 0;
public static Orientation East = 1;
public static Orientation South = 2;
public static Orientation West = 3;
}
usage of this struct as simple enum.
where you can create p.a == Orientation.East (or any value that you want) by default
to use the trick itself, you need to convert from int by code.
there the implementation:
#region ConvertingToEnum
private int val;
static Dictionary<int, string> dict = null;
public Orientation(int val)
{
this.val = val;
}
public static implicit operator Orientation(int value)
{
return new Orientation(value - 1);
}
public static bool operator ==(Orientation a, Orientation b)
{
return a.val == b.val;
}
public static bool operator !=(Orientation a, Orientation b)
{
return a.val != b.val;
}
public override string ToString()
{
if (dict == null)
InitializeDict();
if (dict.ContainsKey(val))
return dict[val];
return val.ToString();
}
private void InitializeDict()
{
dict = new Dictionary<int, string>();
foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
{
dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
}
}
#endregion
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.
you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name
import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')
sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
site-packages
directory where pip is installing your packages.psycopg2
directory).pip install YOUR-PACKAGE
Is there really a difference between:
class User implements IUser
and
class UserImpl implements User
if all we're talking about is naming conventions?
Personally I prefer NOT preceding the interface with I
as I want to be coding to the interface and I consider that to be more important in terms of the naming convention. If you call the interface IUser
then every consumer of that class needs to know its an IUser
. If you call the class UserImpl
then only the class and your DI container know about the Impl
part and the consumers just know they're working with a User
.
Then again, the times I've been forced to use Impl
because a better name doesn't present itself have been few and far between because the implementation gets named according to the implementation because that's where it's important, e.g.
class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
I realize that this is an old question, but one scenario where RabbitMQ might be a better choice is when dealing with data redaction.
With RabbitMQ, by default once the message has been consumed, it's deleted. With Kafka, by default, messages are kept for a week. It's common to set this to a much longer time, or even to never delete them.
While both products can be configured to retain (or not retain) messages, if CCPA or GDPR compliance is a concern, I'd go with RabbitMQ.
You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.
CREATE VIEW MyView
AS
WITH MyVars (SomeVar, Var2)
AS (
SELECT
'something' AS 'SomeVar',
123 AS 'Var2'
)
SELECT *
FROM MyTable
WHERE x = (SELECT SomeVar FROM MyVars)
You can also try this:
import * as drawGauge from '../../../../js/d3gauge.js';
and just new drawGauge(this.opt);
in your ts-code. This solution works in project with angular-cli embedded into laravel on which I currently working on. In my case I try to import poliglot
library (btw: very good for translations) from node_modules:
import * as Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js';
...
export class Lang
{
constructor() {
this.polyglot = new Polyglot({ locale: 'en' });
...
}
...
}
This solution is good because i don't need to COPY any files from node_modules
:) .
You can also look on this LIST of ways how to include libs in angular.
PySimpleGUI wraps tkinter and works on Python 3 and 2.7. It also runs on Qt, WxPython and in a web browser, using the same source code for all platforms.
You can make custom GUIs that utilize all of the same widgets that you find in tkinter (sliders, checkboxes, radio buttons, ...). The code tends to be very compact and readable.
#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
import PySimpleGUI as sg
else:
import PySimpleGUI27 as sg
layout = [[ sg.Text('My Window') ],
[ sg.Button('OK')]]
window = sg.Window('My window').Layout(layout)
button, value = window.Read()
As explained in the PySimpleGUI Documentation, to build the .EXE file you run:
pyinstaller -wF MyGUIProgram.py
I wonder whether the below method is what you want.
You can use defaultdict
.
>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
Here is an example of custom combobox in android:
package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
public class ComboBox extends LinearLayout {
private AutoCompleteTextView _text;
private ImageButton _button;
public ComboBox(Context context) {
super(context);
this.createChildControls(context);
}
public ComboBox(Context context, AttributeSet attrs) {
super(context, attrs);
this.createChildControls(context);
}
private void createChildControls(Context context) {
this.setOrientation(HORIZONTAL);
this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
_text = new AutoCompleteTextView(context);
_text.setSingleLine();
_text.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_NORMAL
| InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
| InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
| InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
_text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1));
_button = new ImageButton(context);
_button.setImageResource(android.R.drawable.arrow_down_float);
_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_text.showDropDown();
}
});
this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
/**
* Sets the source for DDLB suggestions.
* Cursor MUST be managed by supplier!!
* @param source Source of suggestions.
* @param column Which column from source to show.
*/
public void setSuggestionSource(Cursor source, String column) {
String[] from = new String[] { column };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
android.R.layout.simple_dropdown_item_1line, source, from, to);
// this is to ensure that when suggestion is selected
// it provides the value to the textbox
cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
_text.setAdapter(cursorAdapter);
}
/**
* Gets the text in the combo box.
*
* @return Text.
*/
public String getText() {
return _text.getText().toString();
}
/**
* Sets the text in combo box.
*/
public void setText(String text) {
_text.setText(text);
}
}
Hope it helps!!
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
Read This: 1.2 Date
and Time Datatype
best data type to store date and time is:
TEXT
best format is: yyyy-MM-dd HH:mm:ss
Then read this page; this is best explain about date and time in SQLite
.
I hope this help you
For Sql Server 2017 and later you can use the new STRING_AGG
function
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.
SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv FROM Person.Person;
Here is the result set.
John,N/A,Mike,Peter,N/A,N/A,Alice,Bob
Perhaps a more common use case is to group together and then aggregate, just like you would with SUM
, COUNT
or AVG
.
SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
Here is an example of the wget script in action:
wget -q -O /dev/null "http://example.com/cronjob.php" > /dev/null 2>&1
Using -O
parameter like the above means that the output of the web request will be sent to STDOUT
(standard output).
And the >/dev/null 2>&1
will instruct standard output to be redirected to a black hole. So no message from the executing program is returned to the screen.
Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.
So you could something like this git cherry-pick --strategy=recursive -X theirs commit
or git cherry-pick --strategy=recursive -X ours commit
Yes, you can solve it using the ElementName=Something
as suggested by Juve.
BUT!
If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!
I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.
<UserControl x:Class="MyNiceControl"
x:Name="TheSameName">
the content ...
</UserControl>
<UserControl x:Class="AnotherUserControl">
<ListView x:Name="TheSameName">
<ListView.ItemTemplate>
<DataTemplate>
<MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'}, function(response) {
console.log(response);
});//
I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.
So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.
The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:
<script>
{
localStorage.setItem("redirect", "/ansible/");
location.href = "/";
}
</script>
Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):
import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";
class App extends Component {
render() {
const redirect = localStorage.getItem("redirect");
if(redirect) {
localStorage.removeItem("redirect");
}
return (
<Router>
{redirect ?<Redirect to={redirect}/> : ""}
<div className="App">
...
<Link to="/">
<li>Home</li>
</Link>
<Link to="/dev">
<li>Development</li>
</Link>
<Link to="/wood">
<li>Wood Working</li>
</Link>
...
<Route
path="/"
exact
render={(props) => (
<Home {...props} />
)}
/>
<Route
path="/dev"
render={(props) => (
<Code {...props} />
)}
/>
<Route
path="/wood"
render={(props) => (
<Wood {...props} />
)}
/>
<Route
path="/ansible/"
exact
render={(props) => (
<Ansible {...props} checked={this.state.checked} />
)}
/>
...
</Router>
);
}
}
export default App;
Actual usage: chizl.com
You can use JsonResponse with values. Simple example:
from django.http import JsonResponse
def some_view(request):
data = list(SomeModel.objects.values()) # wrap in list(), because QuerySet is not JSON serializable
return JsonResponse(data, safe=False) # or JsonResponse({'data': data})
Or another approach with Django's built-in serializers:
from django.core import serializers
from django.http import HttpResponse
def some_view(request):
qs = SomeModel.objects.all()
qs_json = serializers.serialize('json', qs)
return HttpResponse(qs_json, content_type='application/json')
In this case result is slightly different (without indent by default):
[
{
"model": "some_app.some_model",
"pk": 1,
"fields": {
"name": "Elon",
"age": 48,
...
}
},
...
]
I have to say, it is good practice to use something like marshmallow to serialize queryset.
...and a few notes for better performance:
objects.values()
to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields
to serializers.serialize
);You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.
border-style: solid; border-width:thin; border-color: #FFFFFF;
unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.
I was having this issue and found that within ~/.ssh/config
I had a line that read:
UserKnownHostsFile=/home/.ssh-agent/known_hosts
I just modified this line to read:
UserKnownHostsFile=~/.ssh/known_hosts
That fixed the problem for me.
ORA-01775: looping chain of synonyms I faced the above error while I was trying to compile a Package which was using an object for which synonym was created however underlying object was not available.
There's a nice example of try-else
in PEP 380. Basically, it comes down to doing different exception handling in different parts of the algorithm.
It's something like this:
try:
do_init_stuff()
except:
handle_init_suff_execption()
else:
try:
do_middle_stuff()
except:
handle_middle_stuff_exception()
This allows you to write the exception handling code nearer to where the exception occurs.
Based on inspiration from answer. I defined a function as below. Looks like its working fine. Please let me know if you find any issue
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
You can also check for first DecorView's child bottom padding. It will be set to non-zero value when keyboard is shown.
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
View view = getRootView();
if (view != null && (view = ((ViewGroup) view).getChildAt(0)) != null) {
setKeyboardVisible(view.getPaddingBottom() > 0);
}
super.onLayout(changed, left, top, right, bottom);
}
edittext_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/edittext_pressed" android:state_pressed="true" /> <!-- pressed -->
<item android:drawable="@drawable/edittext_disable" android:state_enabled="false" /> <!-- focused -->
<item android:drawable="@drawable/edittext_default" /> <!-- default -->
</selector>
edittext_default.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_disable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#aaaaaa" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
Python uses the :: to separate the End, the Start, and the Step value.
I was able to achieve this result using the Jenkins Dynamic Parameter Plug-in. I used the Dynamic Choice Parameter option and, for the choices script, I used the following:
proc1 = ['/bin/bash', '-c', "/usr/bin/git ls-remote -h ssh://[email protected]/path/to/repo.git"].execute()
proc2 = ['/bin/bash', '-c', "awk '{print \$2}'"].execute()
proc3 = ['/bin/bash', '-c', "sed s%^refs/heads%origin%"].execute()
all = proc1 | proc2 | proc3
String result = all.text
String filename = "/tmp/branches.txt"
boolean success = new File(filename).write(result)
def multiline = "cat /tmp/branches.txt".execute().text
def list = multiline.readLines()
Try jcabi-xml, with a one liner:
Node node = new XMLDocument("<node>value</node>").node();
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('your View Name');
How about:
public static T As<T>(this object obj)
{
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
}
The SimpleDateFormat class allows you to parse a String
into a java.util.Date
object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime()
.
The full example:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
Note that this gives you a long
and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat
class has tons on information on how to set it up to parse different formats.
I had the same error
[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
however, I totally forgot to run npm install && npm run dev
to compiling the js files.
maybe this helps newbies like me.
You can parse the string using Html Agility pack and get the InnerText.
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )");
string result = htmlDoc.DocumentNode.InnerText;
List<String> listA = new ArrayList<String>();
listA.add("A");
listA.add("B");
List<String> listB = new ArrayList<String>();
listB.add("B");
listB.add("C");
Set<String> newSet = new HashSet<String>(listA);
newSet.addAll(listB);
List<String> newList = new ArrayList<String>(newSet);
System.out.println("New List :"+newList);
is giving you New List :[A, B, C]
1.Remove onclick
method from div
element
2.Remove function change()
from jQuery code and in place of that create an anonymous function like:
$(document).ready(function()
{
$('#co').click(function()
{
$('body').css('background-color','blue');
});
});
The suggestions to use cookies aside, the only comprehensive set of identifying attributes available to interrogate are contained in the HTTP request header. So it is possible to use some subset of these to create a pseudo-unique identifier for a user agent (i.e., browser). Further, most of this information is possibly already being logged in the so-called "access log" of your web server software by default and, if not, can be easily configured to do so. Then, a utlity could be developed that simply scans the content of this log, creating fingerprints of each request comprised of, say, the IP address and User Agent string, etc. The more data available, even including the contents of specific cookies, adds to the quality of the uniqueness of this fingerprint. Though, as many others have stated already, the HTTP protocol doesn't make this 100% foolproof - at best it can only be a fairly good indicator.
The problem is probably somewhere else. Try this code for example:
Sub test()
origNum = "006260006"
creditOrDebit = "D"
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
MsgBox "OK"
End If
End Sub
And you will see that your Or
works as expected. Are you sure that your ElseIf
statement is executed (it will not be executed if any of the if/elseif before is true)?
You can use FusedLocationProvider
For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
...
...
...
implementation 'com.google.android.gms:play-services-location:17.0.0'
}
Permissions in Manifest
Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_ID
)
Then you can use the FusedLocationProvider Client to get the updated location in your desired place.
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
var location: Location? = task.result
if (location == null) {
requestNewLocationData()
} else {
findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
}
}
You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:
private fun requestNewLocationData() {
var mLocationRequest = LocationRequest()
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mLocationRequest.interval = 0
mLocationRequest.fastestInterval = 0
mLocationRequest.numUpdates = 1
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
)
}
If you are using version 4.3 or higher, your code will not work properly. This is what I used. It worked for me.
.btn:focus, .btn:active {
outline: none !important;
box-shadow: none !important;
-webkit-box-shadow: none !important;
}
Adding the below content in the main gradle has solved the problem for me:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
flatDir {
dirs 'libs'
}
}
Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
You can use native function Date.toLocaleTimeString()
:
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
I found it on http://www.w3schools.com/jsref/jsref_tolocaletimestring.asp
var d = new Date();_x000D_
var n = d.toLocaleTimeString();_x000D_
alert("The time is: \n"+n);
_x000D_
Have you tried using the MD5 implementation in hashlib? Note that hashing algorithms typically act on binary data rather than text data, so you may want to be careful about which character encoding is used to convert from text to binary data before hashing.
The result of a hash is also binary data - it looks like Flickr's example has then been converted into text using hex encoding. Use the hexdigest
function in hashlib to get this.
K8s completely works on the fundamental of the namespace. if you like to release all the resource related to specified namespace.
you can use the below mentioned :
kubectl delete namespace k8sdemo-app
Did you check for DataReaders that are not closed and response.redirects before closing the connection or a datareader. Connections stay open when you dont close them before a redirect.
WebElement webElement = driver.findElement(By.xpath(""));
//Enter the xpath or ID.
webElement.sendKeys("");
//Input the string to pass.
webElement.sendKeys(Keys.TAB);
//This will enter the string which you want to pass and will press "Tab" button .
You can open the Windows event viewer to try to get more information about the errors : in the "Application" section of the Windows logs, there is a good chance you will find error messages from Apache. (At least I found what was wrong in my case there !)
Could it be that you have an error in your CSS file? A parenthesis left unclosed, a missing semicolon etc?
It's possible that your configuration variables are cached. Verify your config/app.php
as well as your .env
file then try
php artisan cache:clear
on the command line.
The MERGE statement merges data between two tables. Using DUAL allows us to use this command. Note that this is not protected against concurrent access.
create or replace
procedure ups(xa number)
as
begin
merge into mergetest m using dual on (a = xa)
when not matched then insert (a,b) values (xa,1)
when matched then update set b = b+1;
end ups;
/
drop table mergetest;
create table mergetest(a number, b number);
call ups(10);
call ups(10);
call ups(20);
select * from mergetest;
A B
---------------------- ----------------------
10 2
20 1
you can just find-out loaded config file by executing below command,
php -i | grep 'php.ini'
Then add below lines to correct php.ini file
extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so
Then restart web server,
service httpd restart
labelName.font = labelName.font.withSize(15)
Should get you the latest wanted versions compatible for your app. But not the latest versions.
Here is a way to do it without adding an ID to the form elements.
<form method="post">
...
<select name="List">
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
<select name="List">
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
...
</form>
public ActionResult OrderProcessor()
{
string[] ids = Request.Form.GetValues("List");
}
Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:
public class OrderModel
{
public string[] List { get; set; }
}
public ActionResult OrderProcessor(OrderModel model)
{
string[] ids = model.List;
}
Hope this helps.
I'm giving this example because this actually work for my use case.
I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:
BoundingBox boundingBox = faceDetail.getBoundingBox();
The code below uses it to crop the image:
import com.amazonaws.services.rekognition.model.BoundingBox;
private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));
Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));
BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);
return clippedImg;
}
Well there are 2 methods:
Method 1: A well-known method for renaming database schema is by dumping the schema using Mysqldump and restoring it in another schema, and then dropping the old schema (if needed).
From Shell
mysqldump emp > emp.out
mysql -e "CREATE DATABASE employees;"
mysql employees < emp.out
mysql -e "DROP DATABASE emp;"
Although the above method is easy, it is time and space consuming. What if the schema is more than a 100GB? There are methods where you can pipe the above commands together to save on space, however it will not save time.
To remedy such situations, there is another quick method to rename schemas, however, some care must be taken while doing it.
Method 2: MySQL has a very good feature for renaming tables that even works across different schemas. This rename operation is atomic and no one else can access the table while its being renamed. This takes a short time to complete since changing a table’s name or its schema is only a metadata change. Here is procedural approach at doing the rename:
If there are views, triggers, functions, stored procedures
in the schema, those will need to be recreated too. MySQL’s “RENAME TABLE” fails if there are triggers exists on the tables. To remedy this we can do the following things :
1) Dump the triggers, events and stored routines in a separate file.
This done using -E, -R flags (in addition to -t -d which
dumps the triggers) to the mysqldump command. Once triggers are
dumped, we will need to drop them from the schema, for RENAME TABLE
command to work.
$ mysqldump <old_schema_name> -d -t -R -E > stored_routines_triggers_events.out
2) Generate a list of only “BASE” tables. These can be found using a query on information_schema.TABLES table.
mysql> select TABLE_NAME from information_schema.tables where
table_schema='<old_schema_name>' and TABLE_TYPE='BASE TABLE';
3) Dump the views in an out file. Views can be found using a query on the same information_schema.TABLES table.
mysql> select TABLE_NAME from information_schema.tables where
table_schema='<old_schema_name>' and TABLE_TYPE='VIEW';
$ mysqldump <database> <view1> <view2> … > views.out
4) Drop the triggers on the current tables in the old_schema.
mysql> DROP TRIGGER <trigger_name>;
...
5) Restore the above dump files once all the “Base” tables found in step #2 are renamed.
mysql> RENAME TABLE <old_schema>.table_name TO <new_schema>.table_name;
...
$ mysql <new_schema> < views.out
$ mysql <new_schema> < stored_routines_triggers_events.out
Intricacies with above methods :
We may need to update the GRANTS
for users such that they match the correct schema_name. These could fixed with a simple UPDATE
on mysql.columns_priv
, mysql.procs_priv
, mysql.tables_priv
, mysql.db tables updating the old_schema name
to new_schema
and calling “Flush privileges;”.
Although “method 2
" seems a bit more complicated than the “method 1
", this is totally scriptable. A simple bash script to carry out the above steps in proper sequence, can help you save space and time while renaming database schemas next time.
The Percona Remote DBA team have written a script called “rename_db” that works in the following way :
[root@dba~]# /tmp/rename_db
rename_db <server> <database> <new_database>
To demonstrate the use of this script, used a sample schema “emp”, created test triggers, stored routines on that schema. Will try to rename the database schema using the script, which takes some seconds to complete as opposed to time consuming dump/restore method.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| emp |
| mysql |
| performance_schema |
| test |
+--------------------+
[root@dba ~]# time /tmp/rename_db localhost emp emp_test
create database emp_test DEFAULT CHARACTER SET latin1
drop trigger salary_trigger
rename table emp.__emp_new to emp_test.__emp_new
rename table emp._emp_new to emp_test._emp_new
rename table emp.departments to emp_test.departments
rename table emp.dept to emp_test.dept
rename table emp.dept_emp to emp_test.dept_emp
rename table emp.dept_manager to emp_test.dept_manager
rename table emp.emp to emp_test.emp
rename table emp.employees to emp_test.employees
rename table emp.salaries_temp to emp_test.salaries_temp
rename table emp.titles to emp_test.titles
loading views
loading triggers, routines and events
Dropping database emp
real 0m0.643s
user 0m0.053s
sys 0m0.131s
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| emp_test |
| mysql |
| performance_schema |
| test |
+--------------------+
As you can see in the above output the database schema “emp” was renamed to “emp_test” in less than a second.
Lastly, This is the script from Percona that is used above for “method 2
".
#!/bin/bash
# Copyright 2013 Percona LLC and/or its affiliates
set -e
if [ -z "$3" ]; then
echo "rename_db <server> <database> <new_database>"
exit 1
fi
db_exists=`mysql -h $1 -e "show databases like '$3'" -sss`
if [ -n "$db_exists" ]; then
echo "ERROR: New database already exists $3"
exit 1
fi
TIMESTAMP=`date +%s`
character_set=`mysql -h $1 -e "show create database $2\G" -sss | grep ^Create | awk -F'CHARACTER SET ' '{print $2}' | awk '{print $1}'`
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
STATUS=$?
if [ "$STATUS" != 0 ] || [ -z "$TABLES" ]; then
echo "Error retrieving tables from $2"
exit 1
fi
echo "create database $3 DEFAULT CHARACTER SET $character_set"
mysql -h $1 -e "create database $3 DEFAULT CHARACTER SET $character_set"
TRIGGERS=`mysql -h $1 $2 -e "show triggers\G" | grep Trigger: | awk '{print $2}'`
VIEWS=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'" -sss`
if [ -n "$VIEWS" ]; then
mysqldump -h $1 $2 $VIEWS > /tmp/${2}_views${TIMESTAMP}.dump
fi
mysqldump -h $1 $2 -d -t -R -E > /tmp/${2}_triggers${TIMESTAMP}.dump
for TRIGGER in $TRIGGERS; do
echo "drop trigger $TRIGGER"
mysql -h $1 $2 -e "drop trigger $TRIGGER"
done
for TABLE in $TABLES; do
echo "rename table $2.$TABLE to $3.$TABLE"
mysql -h $1 $2 -e "SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE"
done
if [ -n "$VIEWS" ]; then
echo "loading views"
mysql -h $1 $3 < /tmp/${2}_views${TIMESTAMP}.dump
fi
echo "loading triggers, routines and events"
mysql -h $1 $3 < /tmp/${2}_triggers${TIMESTAMP}.dump
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
if [ -z "$TABLES" ]; then
echo "Dropping database $2"
mysql -h $1 $2 -e "drop database $2"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.columns_priv where db='$2'" -sss` -gt 0 ]; then
COLUMNS_PRIV=" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.procs_priv where db='$2'" -sss` -gt 0 ]; then
PROCS_PRIV=" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.tables_priv where db='$2'" -sss` -gt 0 ]; then
TABLES_PRIV=" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.db where db='$2'" -sss` -gt 0 ]; then
DB_PRIV=" UPDATE mysql.db set db='$3' WHERE db='$2';"
fi
if [ -n "$COLUMNS_PRIV" ] || [ -n "$PROCS_PRIV" ] || [ -n "$TABLES_PRIV" ] || [ -n "$DB_PRIV" ]; then
echo "IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:"
if [ -n "$COLUMNS_PRIV" ]; then echo "$COLUMNS_PRIV"; fi
if [ -n "$PROCS_PRIV" ]; then echo "$PROCS_PRIV"; fi
if [ -n "$TABLES_PRIV" ]; then echo "$TABLES_PRIV"; fi
if [ -n "$DB_PRIV" ]; then echo "$DB_PRIV"; fi
echo " flush privileges;"
fi
Here:
df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880
Simply call the ordinal()
method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.
You shouldn't depend on the int
value of an enum
, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.
Regarding the example you provided in the question, Font.PLAIN
works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum
is not the right tool for the job, better stick to numeric constants.
I had the same problem with woff-fonts, multiple subdomains had to have access. To allow subdomains I added something like this to my httpd.conf:
SetEnvIf Origin "^(.*\.example\.com)$" ORIGIN_SUB_DOMAIN=$1
<FilesMatch "\.woff$">
Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
</FilesMatch>
For multiple domains you could just change the regex in SetEnvIf
.