Open Anaconda Prompt (base):
conda update -n base -c defaults conda
conda create -n python38 python=3.8
conda activate python38
python
This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.
Required Gradle version is here
more compatibility you can see from here. Android Plugin for Gradle Release Notes
if you have the android studio version 4.0.1
then your top level gradle file must be like this
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and the gradle version should be
and your app gradle look like this
It's the "null coalescing operator", added in php 7.0. The definition of how it works is:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
So it's actually just isset()
in a handy operator.
Those two are equivalent1:
$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';
Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce
In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
And original RFC https://wiki.php.net/rfc/isset_ternary
EDIT: As this answer gets a lot of views, little clarification:
1There is a difference: In case of ??
, the first expression is evaluated only once, as opposed to ? :
, where the expression is first evaluated in the condition section, then the second time in the "answer" section.
You can add some code like this
ListView.builder{
shrinkWrap: true,
}
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
In my case, I was transport class component from parent and use it inside as a prop var, using typescript and Formik, and run well like this:
Parent 1
import Parent2 from './../components/Parent2/parent2'
import Parent3 from './../components/Parent3/parent3'
export default class Parent1 extends React.Component {
render(){
<React.Fragment>
<Parent2 componentToFormik={Parent3} />
</React.Fragment>
}
}
Parent 2
export default class Parent2 extends React.Component{
render(){
const { componentToFormik } = this.props
return(
<Formik
render={(formikProps) => {
return(
<React.fragment>
{(new componentToFormik(formikProps)).render()}
</React.fragment>
)
}}
/>
)
}
}
I tried to restart my Windows machine and reinstalled the "npm i".
It worked for me.
Another option is to add it to the jest.config.js
file after the module.exports
definition:
process.env = Object.assign(process.env, {
VAR_NAME: 'varValue',
VAR_NAME_2: 'varValue2'
});
This way it's not necessary to define the environment variables in each .spec
file and they can be adjusted globally.
In my case, I was using a service in a sub module (NOT the root AppModule), and the HttpClientModule was imported only in the module.
So I have to modify the default scope of the service, by changing 'providedIn' to 'any' in the @Injectable decorator.
By default, if you using angular-cli to generate the service, the 'providedIn' was set to 'root'.
Hope this helps.
This can be installed via conda with the command conda install -c anaconda python=3.7
as per https://anaconda.org/anaconda/python.
Though not all packages support 3.7 yet, running conda update --all
may resolve some dependency failures.
Edit (as suggested in comments and other people), Visual Studio Code has evolved and provides this functionality in-built as the command "Organize imports", with the following default keyboard shortcuts:
option+Shift+O for Mac
Alt + Shift + O for Windows
Original answer:
I hope this visual studio code extension will suffice your need: https://marketplace.visualstudio.com/items?itemName=rbbit.typescript-hero
It provides following features:
For Mac: control+option+o
For Win: Ctrl+Alt+o
I think your tensorflow is not installed for local environment.The best way of installing tensorflow is to create virtualenv as describe in the tensorflow installation guide Tensorflow Installation .After installing you can activate the invironment and can run anypython script under that environment.
I had today a similar error message. What was peculiar is that it did not break the Application. It was running smoothly but the command prompt (Windows machine) indicated there was an error. I did not update the Typescript version but found another culprit. It turned there was a tiny omission of symbol - closing ")", which I believe The Typescript is compensating for. Just for reference the code is the following:
[new Object('First Characteristic','Second Characteristic',
'Third Characteristic'*]
* notice here the ending ")" is missing.
Once brought back no more issues on the command prompt!
For future visitors: In the new HttpClient
(Angular 4.3+), the response
object is JSON by default, so you don't need to do response.json().data
anymore. Just use response
directly.
Example (modified from the official documentation):
import { HttpClient } from '@angular/common/http';
@Component(...)
export class YourComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://api.github.com/users')
.subscribe(response => console.log(response));
}
}
Don't forget to import it and include the module under imports in your project's app.module.ts:
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module after BrowserModule.
HttpClientModule,
...
],
...
Or get the number of unique values for each column:
df.nunique()
dID 3
hID 5
mID 3
uID 5
dtype: int64
New in pandas 0.20.0
pd.DataFrame.agg
df.agg(['count', 'size', 'nunique'])
dID hID mID uID
count 8 8 8 8
size 8 8 8 8
nunique 3 5 3 5
You've always been able to do an agg
within a groupby
. I used stack
at the end because I like the presentation better.
df.groupby('mID').agg(['count', 'size', 'nunique']).stack()
dID hID uID
mID
A count 5 5 5
size 5 5 5
nunique 3 5 5
B count 2 2 2
size 2 2 2
nunique 2 2 2
C count 1 1 1
size 1 1 1
nunique 1 1 1
PowerBI Embedded requires TLS 1.2.
The answer above by Etienne Faucher is your solution. quick link to above answer... quick link to above answer... ( https://stackoverflow.com/a/45442874 )
PowerBI Requires TLS 1.2 June 2020 - This Is your Answer - Consider Forcing your IIS runtime to get up to 4.6 to force the default TLS 1.2 behavior you are looking for from the framework. The above answer gives you a config change only solution.
Symptoms: Forced Closed Rejected TCP/IP Connection to Microsoft PowerBI Embedded that just shows up all of a sudden across your systems.
These PowerBI Calls just stop working with a Hard TCP/IP Close error like a firewall would block a connection. Usually the auth steps work - it is when you hit the service for specific workspace and report id's that it fails.
This is the 2020 note from Microsoft PowerBI about TLS 1.2 required
PowerBIClient
methods that show this problem
GetReportsInGroupAsync GetReportsInGroupAsAdminAsync GetReportsAsync GetReportsAsAdminAsync Microsoft.PowerBI.Api HttpClientHandler Force TLS 1.1 TLS 1.2
Search Error Terms to help people find this: System.Net.Http.HttpRequestException: An error occurred while sending the request System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");
To use the EF core SqlServer provider and compile the above code install the EF SqlServer package
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
After compilation before running the code do the following for the first time
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update
To run the code
dotnet run
I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).
If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:
// Any Tr element will be green if its (row.age > 20)
<ReactTable
getTrProps={(state, rowInfo, column) => {
return {
style: {
background: rowInfo.row.selected ? 'green' : 'red'
}
}
}}
/>
I'm surprised no one mentioned the HTML entities  
and  
which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than
.
 
 
Along with <space>
and  
, these are the five entities HTML provides for horizontal white space.
Note that except for
, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With
it would wrap to a new line as a block even if the text before
could fit on the previous line.
Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John
Doe), addresses or references (see eq.
5), breaking as a block is usually undesired.
Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
For me, none of the suggestions about removing bottom constraints nor setting scroll container to true seemed to work. What worked: expand the height of individual/nested views in my layout so they "spanned" beyond the parent by using the "Expand Vertically" option of the Constraint Layout Editor as shown below.
For any approach, it is important that the dotted preview lines extend vertically beyond the parent's top or bottom dimensions
Nothing works from this tread. "forRoot" doesn't help.
Sorry. Sorted this out. I've managed to make it work by setting correct "routes" for this "forRoot" router setup routine
import {RouterModule, Routes} from '@angular/router';
import {AppComponent} from './app.component';
const appRoutes: Routes = [
{path: 'UI/part1/Details', component: DetailsComponent}
];
@NgModule({
declarations: [
AppComponent,
DetailsComponent
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot(appRoutes)
],
providers: [DetailsService],
bootstrap: [AppComponent]
})
Also may be helpful (spent some time to realize this) Optional route part:
const appRoutes: Routes = [
{path: 'UI/part1/Details', component: DetailsComponent},
{path: ':project/UI/part1/Details', component: DetailsComponent}
];
Second rule allows to open URLs like
hostname/test/UI/part1/Details?id=666
and
hostname/UI/part1/Details?id=666
Been working as a frontend developer since 2012 but never stuck in a such over-complicated thing as angular2 (I have 3 years experience with enterprise level ExtJS)
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
i had same issue i resolve this use under
go to gmail.com
my account
and enable
Allow less secure apps: ON
it start works
If adding pypi.python.org as a trusted host does not work, you try adding files.pythonhosted.org. For example
python -m pip install --upgrade --trusted-host files.pythonhosted.org <package-name>
i faced the same issue in react native .63 version. I tried above all methods but didn't worked. So, I tried like this deleted android/ios folders in my old project tree and initiated a new project with similar name in another folder, later copied android/ios folders from new project to old project and reset cache using react-native start --reset-cache and run react-native run-android and my attempt was successfull.
I was getting this npm ERR! code ELIFECYCLE
error while running a build. Clearing the cache and removing the package-lock.json files did not fix it.
In my case there was an Angular build running on a Docker image that was causing this. The root cause turned out to be running the build on Docker in MacOS, which runs the Docker inside a Linux VM, and has by default 2GB memory allocated.
Giving Docker more memory fixed this issue for me. Have to say, the error message could have been quite a bit more clear..
A helpful answer for me was Call retries were exceeded exception while ng build
This is a constraint of browsers. You should use div or article or something like that in the render method of App because that way you can put whatever you like inside it. Paragraph tags are limited to only containing a limited set of tags (mostly tags for formatting text. You cannot have a div inside a paragraph
<p><div></div></p>
is not valid HTML. Per the tag omission rules listed in the spec, the <p>
tag is automatically closed by the <div>
tag, which leaves the </p>
tag without a matching <p>
. The browser is well within its rights to attempt to correct it by adding an open <p>
tag after the <div>
:
<p></p><div></div><p></p>
You can't put a <div>
inside a <p>
and get consistent results from various browsers. Provide the browsers with valid HTML and they will behave better.
You can put <div>
inside a <div>
though so if you replace your <p>
with <div class="p">
and style it appropriately, you can get what you want.
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
You can also Use below method if you have to replace string between specific index
def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
try:
singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
except Exception as e:
exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
BuiltIn.log_to_console(exception)
return singleLine
Check you have configuration named "production" for ng build --prod, since it is shorthand for ng build --configuration=production No answer solved my problem, because the problem was sitting right in front of the screen. I think this might be quite common... I've internationalized the app with i18n renaming all configurations to e.g. production-en. Then I built with ng build --prod assuming, that the default optimization is used and should be close to optimal, but in fact just ng build has been executed resulting in 7mb bundle instead of 250kb.
<div class="dropdown">
<button data-toggle="dropdown">
Sample Button
</button>
<ul class="dropdown-menu">
<li>A</li>
<li>B</li>
<li class="dropdown-divider"></li>
<li>C</li>
</ul>
</div>
This is the sample code for the horizontal divider in bootstrap 4. Output looks like this:
class="dropdown-divider" used in bootstrap 4, while class="divider" used in bootstrap 3 for horizontal divider
Solution that worked for me:
If you're still getting this error message:
TS7016: Could not find a declaration file for module './myjsfile'
Then you might need to add the following to tsconfig.json
{
"compilerOptions": {
...
"allowJs": true,
"checkJs": false,
...
}
}
This prevents typescript from trying to apply module types to the imported javascript.
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
Post the string with raw JSON, and do not forget the double quotation marks!
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
Other answers mainly get all name of object, to get value of property, you can use yourObj[name]
, for example:
var propNames = Object.getOwnPropertyNames(yourObj);
propNames.forEach(
function(propName) {
console.log(
'name: ' + propName
+ ' value: ' + yourObj[propName]);
}
);
This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?
Inspecting this
within the component, we have this.$options.propsData
. If the prop is present here, the user has explicitly set it; default values aren't shown.
This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.
here's my 2 cents worth:
forpromise()
function forpromise(lo, hi, st, res, fn) {_x000D_
if (typeof res === 'function') {_x000D_
fn = res;_x000D_
res = undefined;_x000D_
}_x000D_
if (typeof hi === 'function') {_x000D_
fn = hi;_x000D_
hi = lo;_x000D_
lo = 0;_x000D_
st = 1;_x000D_
}_x000D_
if (typeof st === 'function') {_x000D_
fn = st;_x000D_
st = 1;_x000D_
}_x000D_
return new Promise(function(resolve, reject) {_x000D_
_x000D_
(function loop(i) {_x000D_
if (i >= hi) return resolve(res);_x000D_
const promise = new Promise(function(nxt, brk) {_x000D_
try {_x000D_
fn(i, nxt, brk);_x000D_
} catch (ouch) {_x000D_
return reject(ouch);_x000D_
}_x000D_
});_x000D_
promise._x000D_
catch (function(brkres) {_x000D_
hi = lo - st;_x000D_
resolve(brkres)_x000D_
}).then(function(el) {_x000D_
if (res) res.push(el);_x000D_
loop(i + st)_x000D_
});_x000D_
})(lo);_x000D_
_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
//no result returned, just loop from 0 thru 9_x000D_
forpromise(0, 10, function(i, next) {_x000D_
console.log("iterating:", i);_x000D_
next();_x000D_
}).then(function() {_x000D_
_x000D_
_x000D_
console.log("test result 1", arguments);_x000D_
_x000D_
//shortform:no result returned, just loop from 0 thru 4_x000D_
forpromise(5, function(i, next) {_x000D_
console.log("counting:", i);_x000D_
next();_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 2", arguments);_x000D_
_x000D_
_x000D_
_x000D_
//collect result array, even numbers only_x000D_
forpromise(0, 10, 2, [], function(i, collect) {_x000D_
console.log("adding item:", i);_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 3", arguments);_x000D_
_x000D_
//collect results, even numbers, break loop early with different result_x000D_
forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
console.log("adding item:", i);_x000D_
if (i === 8) return break_("ending early");_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 4", arguments);_x000D_
_x000D_
// collect results, but break loop on exception thrown, which we catch_x000D_
forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
console.log("adding item:", i);_x000D_
if (i === 4) throw new Error("failure inside loop");_x000D_
collect("result-" + i);_x000D_
}).then(function() {_x000D_
_x000D_
console.log("test result 5", arguments);_x000D_
_x000D_
})._x000D_
catch (function(err) {_x000D_
_x000D_
console.log("caught in test 5:[Error ", err.message, "]");_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
});
_x000D_
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
Simple JPA update..
Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);
1 ) Copy the initialAdminPassword in Specified path.
2 ) Login with following Credentials
User Name : admin
Password : <da12906084fd405090a9fabfd66342f0>
3 ) Once you login into the jenkins application you can click on admin profile and reset the password.
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
To print your context ,you can write code like this :
FILE *fp;
char *of;
sprintf(of,"%s%s",text1,text2);
fp=fopen(of,'w');
fprintf(fp,"your print line");
add plt.figure(figsize=(16,5))
before the sns.heatmap and play around with the figsize numbers till you get the desired size
...
plt.figure(figsize = (16,5))
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
Firebase Notifications doesn't have an API to send messages. Luckily it is built on top of Firebase Cloud Messaging, which has precisely such an API.
With Firebase Notifications and Cloud Messaging, you can send so-called downstream messages to devices in three ways:
You'll note that there is no way to send to all devices explicitly. You can build such functionality with each of these though, for example: by subscribing the app to a topic when it starts (e.g. /topics/all
) or by keeping a list of all device IDs, and then sending the message to all of those.
For sending to a topic you have a syntax error in your command. Topics are identified by starting with /topics/
. Since you don't have that in your code, the server interprets allDevices
as a device id. Since it is an invalid format for a device registration token, it raises an error.
From the documentation on sending messages to topics:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
I solved this problem by creating a public git repo with the accepted license files. Then I use wget
to fetch these licenses on any machine I need into a [sdk-dir]/licenses directory before running ./gradlew to build my project.
You can now use ts-node, which makes your life as simple as
npm install -D ts-node
npm install -D typescript
ts-node script.ts
I too had the same problem.
I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.
Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2
This worked for me:
1-
$ npm install -g n
$ n 9.11.2
2-
delete 'node_modules' from the route directory
3-
$ npm install
Still not sure how node/purgecss worked prior to updating.. but this did the trick.
OS_ACTIVITY_MODE didn't work for me (it may have been because I typo'd disable
as disabled
, but isn't that more natural?!?), or at least didn't prevent a great deal of messages. So here's the real deal with the environment variables.
https://llvm.org/svn/llvm-project/lldb/trunk/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp
lldb_private::Error
PlatformDarwin::LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) {
// Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr
// if the OS_ACTIVITY_DT_MODE environment variable is set. (It doesn't
// require any specific value; rather, it just needs to exist).
// We will set it here as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag
// is not set. Xcode makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
// LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
// specifically want it unset.
const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
auto &env_vars = launch_info.GetEnvironmentEntries();
if (!env_vars.ContainsEnvironmentVariable(disable_env_var)) {
// We want to make sure that OS_ACTIVITY_DT_MODE is set so that
// we get os_log and NSLog messages mirrored to the target process
// stderr.
if (!env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE"))
env_vars.AppendArgument(llvm::StringRef("OS_ACTIVITY_DT_MODE=enable"));
}
// Let our parent class do the real launching.
return PlatformPOSIX::LaunchProcess(launch_info);
}
So setting OS_ACTIVITY_DT_MODE
to "NO" in the environment variables (GUI method explained in Schemes screenshot in main answer) makes it work for me.
As far as NSLog
being the dumping ground for system messages, errors, and your own debugging: a real logging approach is probably called for anyway, e.g. https://github.com/fpillet/NSLogger .
OR
Drink the new Kool-Aid: http://asciiwwdc.com/2016/sessions/721 https://developer.apple.com/videos/play/wwdc2016/721/ It's not surprising that there are some hitches after overhauling the entire logging API.
ADDENDUM
Anyway, NSLog
is just a shim:
https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/
NSLog / CFLog
NSLog is now just a shim to os_log in most circumstances.
Only makes sense now to quote the source for the other env variable. Quite a disparate place, this time from Apple internals. Not sure why they are overlapping. [Incorrect comment about NSLog
removed]
[Edited 22 Sep]: I wonder what "release" and "stream" do differently than "debug". Not enough source.
e = getenv("OS_ACTIVITY_MODE");
if (e) {
if (strcmp(e, "release") == 0) {
mode = voucher_activity_mode_release;
} else if (strcmp(e, "debug") == 0) {
mode = voucher_activity_mode_debug;
} else if (strcmp(e, "stream") == 0) {
mode = voucher_activity_mode_stream;
} else if (strcmp(e, "disable") == 0) {
mode = voucher_activity_mode_disable;
}
}
The FirebaseInstanceId.getInstance().getInstanceId()
is deprecated. Based on firebase document, you can retrieve the current registration token using following code:
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
I had the same problem before. Here was my solution:
I encountered the same issue after updating the maven-jar-plugin
to its latest version (at the time of writing), 3.0.2
.
Eclipse 4.5.2
started flagging the pom.xml
file with the org.apache.maven.archiver.MavenArchiver.getManifest
error and a Maven > Update Project.. would not fix it.
Easy solution: downgrade to 2.6 version
Indeed a possible solution is to get back to version 2.6
, a further update of the project would then remove any error. However, that's not the ideal scenario and a better solution is possible: update the m2e
extensions (Eclipse Maven integration).
Better solution: update Eclipse m2e extensions
From Help > Install New Software.., add a new repository (via the Add.. option), pointing to the following URL:
https://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/
Then follow the update wizard as usual. Eclipse would then require a restart. Afterwards, a further Update Project.. on the concerned Maven project would remove any error and your Maven build could then enjoy the benefit of the latest maven-jar-plugin
version.
Additonal notes
The reason for this issue is that from version 3.0.0
on, the concerned component, the maven-archiver
and the related plexus-archiver
has been upgraded to newer versions, breaking internal usages (via reflections) of the m2e
integration in Eclipse. The only solution is then to properly update Eclipse, as described above.
Also note: while Eclipse would initially report errors, the Maven build (e.g. from command line) would keep on working perfectly, this issue is only related to the Eclipse-Maven integration, that is, to the IDE.
The following code solved the problem (with jQuery).
var vhHeight = $("body").height();
var chromeNavbarHeight = vhHeight - window.innerHeight;
$('body').css({ height: window.innerHeight, marginTop: chromeNavbarHeight });
And the other elements use %
as a unit to replace vh
.
After reading Byte Commander's answer, I want to introduce a tiny possible improvement:
You can generate a regexp that will match either n
words, as long as your n
is predetermined. For instance, if I want to match between 1 and 3 words, the regexp:
^([A-Z]+)(?:,([A-Z]+))?(?:,([A-Z]+))?$
will match the next sentences, with one, two or three capturing groups.
HELLO,LITTLE,WORLD
HELLO,WORLD
HELLO
You can see a fully detailed explanation about this regular expression on Regex101.
As I said, it is pretty easy to generate this regexp for any groups you want using your favorite language. Since I'm not much of a swift guy, here's a ruby example:
def make_regexp(group_regexp, count: 3, delimiter: ",")
regexp_str = "^(#{group_regexp})"
(count - 1).times.each do
regexp_str += "(?:#{delimiter}(#{group_regexp}))?"
end
regexp_str += "$"
return regexp_str
end
puts make_regexp("[A-Z]+")
That being said, I'd suggest not using regular expression in that case, there are many other great tools from a simple split
to some tokenization patterns depending on your needs. IMHO, a regular expression is not one of them. For instance in ruby I'd use something like str.split(",")
or str.scan(/[A-Z]+/)
I actually don‘t see your issue. Globally is any package which is in your python3 path‘s site package folder.
If you want to use it just locally then you must configure a virtualenv and reinstall the packages with an activated virtual environment.
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:
Converting an Object to a Map
The
new Map()
constructor accepts an iterable ofentries
. WithObject.entries
, you can easily convert fromObject
toMap
:const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map { foo: "bar", baz: 42 }
the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7
It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare
You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.
While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt
and python-pip
.
Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
php5-mcrypt \
python-pip
However, according to this answer you should think about installing the python3-pip
package instead of the python-pip
package when using Python 3.x.
Furthermore, to make the php5-mcrypt
package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository
command missing in the Ubuntu Docker image so I installed the package software-properties-common
at first to make the command available.
Splitting up the statements and putting apt-get update
and apt-get install
into one RUN
command is also recommended here.
Oh and by the way, you actually don't need the -y
flag at apt-get update
because there is nothing that has to be confirmed automatically.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
apache2 \
curl \
git \
libapache2-mod-php5 \
php5 \
php5-mcrypt \
php5-mysql \
python3.4 \
python3-pip
Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.
I got this from using the Anaconda default environment instead of my custom one with pandas installed.
Changing to the right environment and reopening the Jupyter notebooks did not fix this for me (python 3.7, pandas 0.23.0). Restarting Anaconda did.
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
For Windows users looking for solution of same problem. I just repleced
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
in my /conf/extra/http?-xampp.conf
You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.
In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:
const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
// ...
new FileManagerPlugin({
onEnd: {
copy: [{
source: './dist/*.*',
destination: './public/',
}],
},
}),
],
In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.
function wait(ms, data) {
console.log('Starting task:', data, ms);
return new Promise(resolve => setTimeout(resolve, ms, data));
}
var tasks = [
async () => {
var result = await wait(1000, 'moose');
// do something with result
console.log(result);
},
async () => {
var result = await wait(500, 'taco');
// do something with result
console.log(result);
},
async () => {
var result = await wait(5000, 'burp');
// do something with result
console.log(result);
}
]
await Promise.all(tasks.map(p => p()));
console.log('done');
And the output:
Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done
Echoing the answer, above, a full install of the JDK (8u121 at this writing) from here - http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html - did the trick. Updating via the Mac OS Control Panel did not update the profile variable. Installing via the full installer, did. Then Eclipse was happy.
Given that the only logical difference between the handlers is the value of the button clicked, you can use the this
keyword to refer to the element which raised the event and get the val()
from that. Try this:
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/test/",
data: {
id: $(this).val(), // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
});
"Just because you can doesn't mean you should."
You can probably use async/await in LINQ expressions such that it will behave exactly as you want it to, but will any other developer reading your code still understand its behavior and intent?
(In particular: Should the async operations be run in parallel or are they intentionally sequential? Did the original developer even think about it?)
This is also shown clearly by the question, which seems to have been asked by a developer trying to understand someone else's code, without knowing its intent. To make sure this does not happen again, it may be best to rewrite the LINQ expression as a loop statement, if possible.
Ok, I propose this solution, very simple, using ngx-translate
import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Pipe({
name: 'localizedDate',
pure: false
})
export class LocalizedDatePipe implements PipeTransform {
constructor(private translateService: TranslateService) {
}
transform(value: any): any {
const date = new Date(value);
const options = { weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
return date.toLocaleString(this.translateService.currentLang, options);
}
}
make sure you don't have env variable NODE_ENV
set to 'production'.
If you do, dev dependencies will not be installed without the --dev
flag
setState
return a Promise
In addition to passing a callback
to setState()
method, you can wrap it around an async
function and use the then()
method -- which in some cases might produce a cleaner code:
(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
.then(() => { console.log('state:', this.state) });
And here you can take this one more step ahead and make a reusable setState
function that in my opinion is better than the above version:
const promiseState = async state =>
new Promise(resolve => this.setState(state, resolve));
promiseState({...})
.then(() => promiseState({...})
.then(() => {
... // other code
return promiseState({...});
})
.then(() => {...});
This works fine in React 16.4, but I haven't tested it in earlier versions of React yet.
Also worth mentioning that keeping your callback code in componentDidUpdate
method is a better practice in most -- probably all, cases.
I just wanted to leave the following which enhances the accepted answer above.
In addition to the accepted answer, you can make your own life a bit easier by specifying an alias
path in Webpack, so you don't have to worry where the image is located relative to the file you're currently in. Please see example below:
Webpack file:
module.exports = {
resolve: {
modules: ['node_modules'],
alias: {
public: path.join(__dirname, './public')
}
},
}
Use:
<img src={require("public/img/resto.ong")} />
Python 3 was working successfully, but without pip3. I tried advice from Stack Overflow, Quora and others (numerous installs and uninstalls).
Python 3 was always fine, but without pip3. Finally I downloaded Python3 from: https://www.python.org/downloads/
By simple mouse clicks and everything (Python 3 + pip3), it is working fine now.
In bootstrap-3.3.7.js you will see the following code.
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
So the bootstrap is going to replace the remote content into <div class="modal-content">
element. This is the default behavior by framework. So the problem is in your remote content itself, it should contain <div class="modal-header">
, <div class="modal-body">
, <div class="modal-footer">
by design.
I had a similar problem after copying the angular2-quickstart folder (including node_modules) to create the angular2-tour-of-heroes folder. This was wierd because the original was compiling fine but the copy was not...
npm run tsc
I was able to resolve the issue by deleting the node_modules folder and re-running npm install.
This was a surprise to me, so I did a diff between the 2 folders...
diff -rw angular2-quickstart/node_modules/ angular2-tour-of-heroes/node_modules/
there were a LOT of differences, a lot of 'where' diffs in the package.json files like this:-
diff -rw angular2-quickstart/node_modules/yargs/package.json angular2-tour-of-heroes/node_modules/yargs/package.json
5c5
< "/Users/michael/Tutorials/angular2/angular2-quickstart/node_modules/lite-server"
---
> "/Users/michael/Tutorials/angular2/angular2-tour-of-heroes/node_modules/lite-server"
...which kind of makes sense but there were also some like this:-
diff -rw angular2-quickstart/node_modules/utf-8-validate/build/gyp-mac-tool angular2-tour-of-heroes/node_modules/utf-8-validate/build/gyp-mac-tool
607c607,608
< return {k: self._ExpandVariables(data[k], substitutions) for k in data}
---
> return dict((k, self._ExpandVariables(data[k],
> substitutions)) for k in data)
...which I don't understand at all.
Oh well, Hope this helps.
Code Formatting Shortcut:
VSCode on Windows - Shift + Alt + F
VSCode on MacOS - Shift + Option + F
VSCode on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using preference setting if needed.
column selection with keyboard Ctrl + Shift + Alt + Arrow
Suppose the DataFrames you want to join are df1 and df2, and you are joining them on column 'a', then you have 2 methods
Method 1
df1.join(df2,'a','left_outer')
This is an awsome method and it is highly recommended.
Method 2
df1.join(df2,df1.a == df2.a,'left_outer').drop(df2.a)
On Ver 14.14 Distrib 5.7.19, for macos10.12 (x86_64)
, I logged in as:
mysql -uroot -p
then typed in the generated password by MySQL when you install it. Then..
ALTER USER 'root'@'localhost' IDENTIFIED BY '<new_password>';
Example:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'Ab1234';
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
$ mysql -uroot -p
And you can type in 'Ab1234'
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
So you need to find out what is wrong with those specific row values.
See the docs
Java 6, now support TLS 1.2, check out below
http://www.oracle.com/technetwork/java/javase/overview-156328.html#R160_121
The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization
header with the Bearer
authentication scheme.
This scheme is described by the RFC6750.
Example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.
Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.
Unlike the custom JWT
scheme you mention in your question, the Bearer
one is registered at the IANA.
Concerning the Basic
and Digest
authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.
In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):
http://loredanacirstea.github.io/es6-design-patterns/
Design patterns book in javascript may also be useful for you:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
Design pattern = classes + interface or multiple inheritance
An example of the factory pattern in ES6 JS (to run: node example.js):
"use strict";
// Types.js - Constructors used behind the scenes
// A constructor for defining new cars
class Car {
constructor(options){
console.log("Creating Car...\n");
// some defaults
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
}
// A constructor for defining new trucks
class Truck {
constructor(options){
console.log("Creating Truck...\n");
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
}
// FactoryExample.js
// Define a skeleton vehicle factory
class VehicleFactory {}
// Define the prototypes and utilities for this factory
// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;
// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {
switch(options.vehicleType){
case "car":
this.vehicleClass = Car;
break;
case "truck":
this.vehicleClass = Truck;
break;
//defaults to VehicleFactory.prototype.vehicleClass (Car)
}
return new this.vehicleClass( options );
};
// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
vehicleType: "car",
color: "yellow",
doors: 6 } );
// Test to confirm our car was created using the vehicleClass/prototype Car
// Outputs: true
console.log( car instanceof Car );
// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );
var movingTruck = carFactory.createVehicle( {
vehicleType: "truck",
state: "like new",
color: "red",
wheelSize: "small" } );
// Test to confirm our truck was created with the vehicleClass/prototype Truck
// Outputs: true
console.log( movingTruck instanceof Truck );
// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );
into ~/.bash_profile add:
export ANDROID_HOME="/path/to/android-sdk-macosx"
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"
and then execute it in terminal to take effect immediately;
into /etc/sudoers add: (you can use console: sudo visudo
)
Defaults env_keep += "ANDROID_HOME"
since the building process has to start with sudo
and Node's process.env
get the respective variables.
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
From a new react/redux adopter migrating from (a few years of) ExtJS in mid-2018:
After sliding backward down the redux learning curve I had the same question and thought pure flux would be simpler like OP.
I soon saw the benefits of redux over flux as noted in the answers above, and was working it into my first app.
While getting a grip on the boiler plate again, I tried out a few of the other state management libs, the best I found was rematch.
It was much more intuitive then vanilla redux, it cuts out 90% of the boilerplate and cut out 75% of the time I was spending on redux (something I think a library should be doing), I was able to get a couple enterprise apps going right away.
It also runs with the same redux tooling. This is a good article that covers some of the benefits.
So for anyone else who arrived to this SO post searching "simpler redux", I recommend trying it out as a simple alternative to redux with all the benefits and 1/4 of the boilerplate.
If I am to define the same proptypes for a particular shape multiple times, I like abstract it out to a proptypes file so that if the shape of the object changes, I only have to change the code in one place. It helps dry up the codebase a bit.
Example:
// Inside my proptypes.js file
import PT from 'prop-types';
export const product = {
id: PT.number.isRequired,
title: PT.string.isRequired,
sku: PT.string.isRequired,
description: PT.string.isRequired,
};
// Inside my component file
import PT from 'prop-types';
import { product } from './proptypes;
List.propTypes = {
productList: PT.arrayOf(product)
}
So, $HOME is what I need to modify. However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something. Anyway...**
Adding HOME at the top of the profile
file worked.
HOME="c://path/to/custom/root/"
.
#THE FIX WAS ADDING THE FOLLOWING LINE TO THE TOP OF THE PROFILE FILE
HOME="c://path/to/custom/root/"
# below are the original contents ===========
# To the extent possible under law, ..blah blah
# Some resources...
# Customizing Your Shell: http://www.dsl.org/cookbook/cookbook_5.html#SEC69
# Consistent BackSpace and Delete Configuration:
# http://www.ibb.net/~anne/keyboard.html
# The Linux Documentation Project: http://www.tldp.org/
# The Linux Cookbook: http://www.tldp.org/LDP/linuxcookbook/html/
# Greg's Wiki http://mywiki.wooledge.org/
# Setup some default paths. Note that this order will allow user installed
# software to override 'system' software.
# Modifying these default path settings can be done in different ways.
# To learn more about startup files, refer to your shell's man page.
MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
MANPATH="/usr/local/man:/usr/share/man:/usr/man:/share/man:${MANPATH}"
INFOPATH="/usr/local/info:/usr/share/info:/usr/info:/share/info:${INFOPATH}"
MINGW_MOUNT_POINT=
if [ -n "$MSYSTEM" ]
then
case "$MSYSTEM" in
MINGW32)
MINGW_MOUNT_POINT=/mingw32
PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
;;
MINGW64)
MINGW_MOUNT_POINT=/mingw64
PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
;;
MSYS)
PATH="${MSYS2_PATH}:/opt/bin:${PATH}"
PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/share/pkgconfig:/lib/pkgconfig"
;;
*)
PATH="${MSYS2_PATH}:${PATH}"
;;
esac
else
PATH="${MSYS2_PATH}:${PATH}"
fi
MAYBE_FIRST_START=false
SYSCONFDIR="${SYSCONFDIR:=/etc}"
# TMP and TEMP as defined in the Windows environment must be kept
# for windows apps, even if started from msys2. However, leaving
# them set to the default Windows temporary directory or unset
# can have unexpected consequences for msys2 apps, so we define
# our own to match GNU/Linux behaviour.
ORIGINAL_TMP=$TMP
ORIGINAL_TEMP=$TEMP
#unset TMP TEMP
#tmp=$(cygpath -w "$ORIGINAL_TMP" 2> /dev/null)
#temp=$(cygpath -w "$ORIGINAL_TEMP" 2> /dev/null)
#TMP="/tmp"
#TEMP="/tmp"
case "$TMP" in *\\*) TMP="$(cygpath -m "$TMP")";; esac
case "$TEMP" in *\\*) TEMP="$(cygpath -m "$TEMP")";; esac
test -d "$TMPDIR" || test ! -d "$TMP" || {
TMPDIR="$TMP"
export TMPDIR
}
# Define default printer
p='/proc/registry/HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/Windows/Device'
if [ -e "${p}" ] ; then
read -r PRINTER < "${p}"
PRINTER=${PRINTER%%,*}
fi
unset p
print_flags ()
{
(( $1 & 0x0002 )) && echo -n "binary" || echo -n "text"
(( $1 & 0x0010 )) && echo -n ",exec"
(( $1 & 0x0040 )) && echo -n ",cygexec"
(( $1 & 0x0100 )) && echo -n ",notexec"
}
# Shell dependent settings
profile_d ()
{
local file=
for file in $(export LC_COLLATE=C; echo /etc/profile.d/*.$1); do
[ -e "${file}" ] && . "${file}"
done
if [ -n ${MINGW_MOUNT_POINT} ]; then
for file in $(export LC_COLLATE=C; echo ${MINGW_MOUNT_POINT}/etc/profile.d/*.$1); do
[ -e "${file}" ] && . "${file}"
done
fi
}
for postinst in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do
[ -e "${postinst}" ] && . "${postinst}"
done
if [ ! "x${BASH_VERSION}" = "x" ]; then
HOSTNAME="$(/usr/bin/hostname)"
profile_d sh
[ -f "/etc/bash.bashrc" ] && . "/etc/bash.bashrc"
elif [ ! "x${KSH_VERSION}" = "x" ]; then
typeset -l HOSTNAME="$(/usr/bin/hostname)"
profile_d sh
PS1=$(print '\033]0;${PWD}\n\033[32m${USER}@${HOSTNAME} \033[33m${PWD/${HOME}/~}\033[0m\n$ ')
elif [ ! "x${ZSH_VERSION}" = "x" ]; then
HOSTNAME="$(/usr/bin/hostname)"
profile_d zsh
PS1='(%n@%m)[%h] %~ %% '
elif [ ! "x${POSH_VERSION}" = "x" ]; then
HOSTNAME="$(/usr/bin/hostname)"
PS1="$ "
else
HOSTNAME="$(/usr/bin/hostname)"
profile_d sh
PS1="$ "
fi
if [ -n "$ACLOCAL_PATH" ]
then
export ACLOCAL_PATH
fi
export PATH MANPATH INFOPATH PKG_CONFIG_PATH USER TMP TEMP PRINTER HOSTNAME PS1 SHELL tmp temp
test -n "$TERM" || export TERM=xterm-256color
if [ "$MAYBE_FIRST_START" = "true" ]; then
sh /usr/bin/regen-info.sh
if [ -f "/usr/bin/update-ca-trust" ]
then
sh /usr/bin/update-ca-trust
fi
clear
echo
echo
echo "###################################################################"
echo "# #"
echo "# #"
echo "# C A U T I O N #"
echo "# #"
echo "# This is first start of MSYS2. #"
echo "# You MUST restart shell to apply necessary actions. #"
echo "# #"
echo "# #"
echo "###################################################################"
echo
echo
fi
unset MAYBE_FIRST_START
pill ${this.props.styleName}
will get "pill undefined" when you don't set the props
I prefer
className={ "pill " + ( this.props.styleName || "") }
or
className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.
Try it out on Regexr.com, doesn't work in NP++(?):
find: (?<=print)( ')(.*)(')
replace: ('$2')
for variables:
(?<=print)( )(.*)(\n)
('$2')\n
for label and variable:
(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
If you are willing to use custom table header as table header, try the followings....
Updated for swift 3.0
Step 1
Create UITableViewHeaderFooterView for custom header..
import UIKit
class MapTableHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var testView: UIView!
}
Step 2
Add custom header to UITableView
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//register the header view
let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
}
extension BranchViewController : UITableViewDelegate{
}
extension BranchViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView
return headerView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
// retuen no of rows in sections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// retuen your custom cells
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func numberOfSections(in tableView: UITableView) -> Int {
// retuen no of sections
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// retuen height of row
}
}
You can also try using multiprocessing.Process
with daemon=True
; the process.start()
method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.
I experienced similar problem while working with falcon framework and using daemon
process helped.
You'd need to do the following:
from multiprocessing import Process
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
heavy_process = Process( # Create a daemonic process with heavy "my_func"
target=my_func,
daemon=True
)
heavy_process.start()
return Response(
mimetype='application/json',
status=200
)
# Define some heavy function
def my_func():
time.sleep(10)
print("Process finished")
You should get a response immediately and, after 10s you should see a printed message in the console.
NOTE: Keep in mind that daemonic
processes are not allowed to spawn any child processes.
Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.
Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:
!ipython nbconvert <notebook name>.ipynb --to html
EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html
now.
It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.
After some googling I found this link:
The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged
So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.
You can also solve this by setting an endpoint which waits for the service to be up by using netcat (using the docker-wait script). I like this approach as you still have a clean command
section in your docker-compose.yml
and you don't need to add docker specific code to your application:
version: '2'
services:
db:
image: postgres
django:
build: .
command: python manage.py runserver 0.0.0.0:8000
entrypoint: ./docker-entrypoint.sh db 5432
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
Then your docker-entrypoint.sh
:
#!/bin/sh
postgres_host=$1
postgres_port=$2
shift 2
cmd="$@"
# wait for the postgres docker to be running
while ! nc $postgres_host $postgres_port; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
# run the command
exec $cmd
This is nowadays documented in the official docker documentation.
PS: You should install netcat
in your docker instance if this is not available. To do so add this to your Docker
file :
RUN apt-get update && apt-get install netcat-openbsd -y
A more robust answer is to use use mkdirp.
var mkdirp = require('mkdirp');
mkdirp('/path/to/dir', function (err) {
if (err) console.error(err)
else console.log('dir created')
});
Then proceed to write the file into the full path with:
fs.writeFile ('/path/to/dir/file.dat'....
You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.
Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an api call brings next 10 users.Its good when you don't want to load enitire data at once as it would take more time and would give bad user experience.
Eager loading - is good as other people suggested when there are not much relations and fetch entire data at once in single call to database
Because Option 2 creates a new List
reference, and then creates an n
element array from the List
(option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use <
(not <=
). Like,
String[] out = new String[n];
for(int i = 0; i < n; i++) {
out[i] = in.get(i);
}
Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.
Since unable to run adb at all on my development machine, I found a different approach.
Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.
Master-machine : computer where development goes on, with only USB-C connectors
Slave-machine: another computer with USB and in same WiFi
adb usb && adb tcpip 5555
from thereOn master machine
deko$: adb devices
List of devices attached
deko$: adb connect 10.0.20.153:5555
connected to 10.0.20.153:5555
Now Android Studio or Xamarin can install and run app on the phone
Sidenote:
I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.
Adding the meta tag to ignore this policy was not helping us, because our webserver was injecting the Content-Security-Policy
header in the response.
In our case we are using Ngnix as the web server for a Tomcat 9 Java-based application. From the web server, it is directing the browser not to allow inline scripts
, so for a temporary testing we have turned off Content-Security-Policy
by commenting.
How to turn it off in ngnix
By default, ngnix ssl.conf file will have this adding a header to the response:
#> grep 'Content-Security' -ir /etc/nginx/global/ssl.conf add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'; script-src 'self'; img-src 'self'; style-src 'self'; base-uri 'self'; form-action 'self';";
If you just comment this line and restart ngnix, it should not be adding the header to the response.
If you are concerned about security or in production please do not follow this, use these steps as only for testing purpose and moving on.
Type android on your command line and install "Android SDK Build-tools"
I removed android platforms and installed again then worked. I wrote these lines in command window:
cordova platform remove android
then
cordova platform add android
In case someone has a similar issue. My resolution was to delete the key that was not working and got a new key for my domain. And this now works with all my sub-domains as well without having to explicitly specify them in the recaptcha admin area.
I use json_decode($response->getBody())
now instead of $response->json()
.
I suspect this might be a casualty of PSR-7 compliance.
As Tariq Khan suggested, I did the same thing and it worked out..
FIX UBUNTU 14.10 UNICORN APT-GET UPDATE
Backup the repo first
$ sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup
$ sudo vi /etc/apt/sources.list
rename us.archive or archive in http://us.archive.ubuntu.com/ubuntu/ as http://old-release.ubuntu.com/ubuntu/
rename http://security.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages as http://old-releases.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages
$ sudo apt-get update
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
You can use Newtonsoft.Json
, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding
which is a dependency of Microsoft.AspNet.Mvc
. So, you don't need to add a dependency in your project.json.
#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);
Note, using a WebAPI controller you don't need to deal with JSON.
Json.NET has been removed from the ASP.NET Core 3.0 shared framework.
You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader
and Utf8JsonWriter
. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.
To get started, use the JsonSerializer
class in the System.Text.Json.Serialization
namespace. See the documentation for information and samples.
To use Json.NET in an ASP.NET Core 3.0 project:
services.AddMvc()
.AddNewtonsoftJson();
Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.
Well, you're getting a java.lang.NoClassDefFoundError
. In your pom.xml
, hibernate-core
version is 3.3.2.GA
and declared after hibernate-entitymanager
, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final
from hibernate-entitymanager
.
You're using spring-boot
as parent, so no need to declare version of some dependencies, since they are managed by spring-boot
.
Also, hibernate-commons-annotations
is inherited from hibernate-entitymanager
and hibernate-annotations
is an old version of hibernate-commons-annotations
, you can remove both.
Finally, your pom.xml
can look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Let me know if you have a problem.
For latest mac os, Below shortcuts works for me.
Jump to beginning of the line == shift + fn + RightArrow
Jump to ending of the line == shift + fn + LeftArrow
while 1:
root.update()
... is (very!) roughly similar to:
root.mainloop()
The difference is, mainloop
is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop
is a much cleaner solution. After all, calling mainloop
is essentially this under the covers:
while the_window_has_not_been_destroyed():
wait_until_the_event_queue_is_not_empty()
event = event_queue.pop()
event.handle()
... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?
Put in the simplest terms possible: always call mainloop
as the last logical line of code in your program. That's how Tkinter was designed to be used.
I've been searching answer but couldn't find but finally I could fix this by adding play-service-ads dependency let's try this
*) File -> Project Structure... -> Under the module you can find app and there is a option called dependencies and you can add com.google.android.gms:play-services-ads:x.x.x dependency to your project
I faced this problem when I try to import eclipse project into android studio
There exists the javascript-snippet, which you can add as browser-bookmark and then activate on any site to track & modify the requests. It looks like:
For further instructions, review the github page.
Might not be the case, but this was the solution to my "pre-receive hook declined" error:
There are some repositories that only allow modifications through Pull Request. This means that you have to
Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:
containing the same property you are referring
The registry change mechanism worked for me after a struggle. Actually my application was running as 32bit. So I had to change the value under path.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319
The value type needs to be DWORD and value above 0 .Better use 1.
Swift 3
you want to download file bite by bite and show in progress view so you want to try this code
import UIKit
class ViewController: UIViewController,URLSessionDownloadDelegate,UIDocumentInteractionControllerDelegate {
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var btndown: UIButton!
var urlLink: URL!
var defaultSession: URLSession!
var downloadTask: URLSessionDownloadTask!
//var backgroundSession: URLSession!
@IBOutlet weak var progress: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
defaultSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
progress.setProgress(0.0, animated: false)
}
func startDownloading () {
let url = URL(string: "http://publications.gbdirect.co.uk/c_book/thecbook.pdf")!
downloadTask = defaultSession.downloadTask(with: url)
downloadTask.resume()
}
@IBAction func btndown(_ sender: UIButton) {
startDownloading()
}
func showFileWithPath(path: String){
let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreview(animated: true)
}
}
// MARK:- URLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print(downloadTask)
print("File download succesfully")
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.pdf"))
if fileManager.fileExists(atPath: destinationURLForFile.path){
showFileWithPath(path: destinationURLForFile.path)
print(destinationURLForFile.path)
}
else{
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
// show file
showFileWithPath(path: destinationURLForFile.path)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
downloadTask = nil
progress.setProgress(0.0, animated: true)
if (error != nil) {
print("didCompleteWithError \(error?.localizedDescription ?? "no value")")
}
else {
print("The task finished successfully")
}
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController
{
return self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
use of this code you want to download file store automatically in Document Directory in your application
this code 100% Working
Late answer, but you can also use:
import time
ym = time.strftime("%Y-%m")
I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:
<script dangerouslySetInnerHTML={{ __html: `</script>
<link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>
Your problem is the typo in the function CreateDectionary().You should change it to CreateDictionary(). collect2: error: ld returned 1 exit status is the same problem in both C and C++, usually it means that you have unresolved symbols. In your case is the typo that i mentioned before.
The question is old, but it seems that there are people who have the same concerns.
What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?
The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.
As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.
self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)
extension is
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: alpha)
}
}
However, the actual view was
Calculating it,
So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.
self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)
Or can anyone tell me what I'm missing?
I got this error when I tried adding a column from a different table. Indeed I got duplicate index values along the way. But it turned out I was just doing it wrong: I actually needed to df.join
the other table.
This pointer might help someone in a similar situation.
From Microsoft's Website:
.NET Core refers to several technologies including .NET Core, ASP.NET Core and Entity Framework Core.
These technologies are different than native .NET in that they run using CoreCLR runtime (used in the Universal Windows Platform).
As you mentioned in your question, .NET Core is not only open-source, but portable as well [runs on MacOS, Windows, and Linux]
The internals of .NET Core are also optimised to not use different modules from its core library unless it is required by the application.
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor
:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
To Print key-value pair, for example:
players = {
'lebron': 'lakers',
'giannis': 'milwakee bucks',
'durant': 'brooklyn nets',
'kawhi': 'clippers',
}
for player,club in players.items():
print(f"\n{player.title()} is the leader of {club}")
The above code, key-value pair:
'lebron': 'lakers', - Lebron is key and lakers is value
for loop - specify key, value in dictionary.item():
Now Print (Player Name is the leader of club).
the Output is:
#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
Tested on macOS Mojave 10.14.5.
Reason and Solution:
we use sdk/tools/emulator
, we should use sdk/emulator
.
WM-C02WM0T3HTD8:~ zgong$ emulator -avd Pixel_3_XL_API_Q_x86
PANIC: Unknown AVD name [Pixel_3_XL_API_Q_x86], use -list-avds to see valid list.
HOME is defined but there is no file Pixel_3_XL_API_Q_x86.ini in $HOME/.android/avd
(Note: Directories are searched in the order $ANDROID_AVD_HOME, $ANDROID_SDK_HOME/avd, and $HOME/.android/avd)
WM-C02WM0T3HTD8:~ zgong$ emulator -avd Pixel_3_XL_API_Q
PANIC: Missing emulator engine program for 'x86' CPU.
We could check the emulator location:
WM-C02WM0T3HTD8:~ zgong$ which emulator
/Users/zgong/Library/Android/sdk/tools/emulator
I did a bunch of googling and while most of the answers were about setting the paths correctly in terminal, it turns out it was actually to do with a shift in a recent version of the SDK, where the emulator app is located in /emulator instead of /tools. Leaving this here in case anyway runs into the same problem.
We need to use as below:
{sdk location}/emulator -avd {avd name}
Here is the real output:
WM-C02WM0T3HTD8:~ zgong$ /Users/zgong/Library/Android/sdk/emulator/emulator -avd Pixel_3_XL_API_Q
pc_memory_init: above 4g size: 40000000
emulator: WARNING: UpdateCheck: Failure: Error
emulator: WARNING: UpdateCheck: failed to get the latest version, skipping check (current version '29.2.1-5889189')
emulator: WARNING: UpdateCheck: Failure: Error
WebSocketServer listening on port 55850
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
Installed Qt WebEngine locales directory not found at location /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/translations/qtwebengine_locales. Trying application directory...
Qt WebEngine locales directory not found at location /Users/zgong/Library/Android/sdk/emulator/lib64/qt/libexec/qtwebengine_locales. Trying fallback directory... Translations MAY NOT not be correct.
Installed Qt WebEngine locales directory not found at location /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/translations/qtwebengine_locales. Trying application directory...
Qt WebEngine locales directory not found at location /Users/zgong/Library/Android/sdk/emulator/lib64/qt/libexec/qtwebengine_locales. Trying fallback directory... Translations MAY NOT not be correct.
Path override failed for key ui::DIR_LOCALES and path '/Users/zgong/.QtWebEngineProcess'
Path override failed for key ui::DIR_LOCALES and path '/Users/zgong/.QtWebEngineProcess'
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
[0403/154905.171893:WARNING:resource_bundle_qt.cpp(116)] locale_file_path.empty() for locale
[0403/154905.171871:WARNING:resource_bundle_qt.cpp(116)] locale_file_path.empty() for locale
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine ICU data not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
Installed Qt WebEngine locales directory not found at location /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/translations/qtwebengine_locales. Trying application directory...
Qt WebEngine locales directory not found at location /Users/zgong/Library/Android/sdk/emulator/lib64/qt/libexec/qtwebengine_locales. Trying fallback directory... Translations MAY NOT not be correct.
Path override failed for key ui::DIR_LOCALES and path '/Users/zgong/.QtWebEngineProcess'
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64/resources. Trying parent directory...
Qt WebEngine resources not found at /Users/joshuaduong/qt-build-5.12.1/install-darwin-x86_64. Trying application directory...
[0403/154907.393116:WARNING:resource_bundle_qt.cpp(116)] locale_file_path.empty() for locale
Build cordova release APK file in cmd.
KEY STORE FILE PATH: keystore file path (F:/cordova/myApp/xxxxx.jks)
KEY STORE PASSWORD: xxxxx
KEY STORE ALIAS: xxxxx
KEY STORE ALIAS PASSWORD: xxxxx
PATH OF zipalign.exe: zipalign.exe file path (C:\Users\xxxx\AppData\Local\Android\sdk\build-tools\25.0.2\zipalign)
ANDROID UNSIGNED APK NAME: android-release-unsigned.apk
ANDROID RELEASE APK NAME: android-release.apk
Run below steps in cmd (run as administrator)
With influx, you can only delete by time
For example, the following are invalid:
#Wrong
DELETE FROM foo WHERE time < '2014-06-30' and duration > 1000 #Can't delete if where clause has non time entity
This is how I was able to delete the data
DELETE FROM foo WHERE time > '2014-06-30' and time < '2014-06-30 15:16:01'
Update: this worked on influx 8. Supposedly it doesn't work on influx 9
string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"
With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.
If you have not changed the defaults of Spring Boot (meaning you are using @EnableAutoConfiguration
or @SpringBootApplication
and have not changed any Property Source handling), then it will look for properties with the following order (highest overrides lowest):
/config
subdir of the current directory/config
package The list above is mentioned in this part of the documentation
What that means is that if a property is found for example application.properties
under src/resources
is will be overridden by a property with the same name found in application.properties
in the /config
directory that is "next" to the packaged jar.
This default order used by Spring Boot allows for very easy configuration externalization which in turn makes applications easy to configure in multiple environments (dev, staging, production, cloud etc)
To see the whole set of features provided by Spring Boot for property reading (hint: there is a lot more available than reading from application.properties
) check out this part of the documentation.
As one can see from my short description above or from the full documentation, Spring Boot apps are very DevOps friendly!
In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this
mdataset.remove(holder.getadapterposition());
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:
s = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
You can use pydash:
import pydash as _
_.get(example_dict, 'key1.key2', default='Default')
Turns out that I just have to convert @column
name testName to all small letters, since it was initially in camel case.
Although I was not able to use the official answer, the question was able to help me solve my problem by letting me know what to investigate.
Change:
@Column(name="testName")
private String testName;
To:
@Column(name="testname")
private String testName;
This is not an answer but a feedback with few compilers of 2021. On Intel CoffeeLake 9900k.
With Microsoft compiler (VS2019), toolset v142:
unsigned 209695540000 1.8322 sec 28.6152 GB/s uint64_t 209695540000 3.08764 sec 16.9802 GB/s
With Intel compiler 2021:
unsigned 209695540000 1.70845 sec 30.688 GB/s uint64_t 209695540000 1.57956 sec 33.1921 GB/s
According to Mysticial's answer, Intel compiler is aware of False Data Dependency, but not Microsoft compiler.
For intel compiler, I used /QxHost
(optimize of CPU's architecture which is that of the host) /Oi
(enable intrinsic functions) and #include <nmmintrin.h>
instead of #include <immintrin.h>
.
Full compile command: /GS /W3 /QxHost /Gy /Zi /O2 /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" //fprofile-instr-use "x64\Release\" /Fp"x64\Release\Benchmark.pch"
.
The decompiled (by IDA 7.5) assembly from ICC:
int __cdecl main(int argc, const char **argv, const char **envp)
{
int v6; // er13
_BYTE *v8; // rsi
unsigned int v9; // edi
unsigned __int64 i; // rbx
unsigned __int64 v11; // rdi
int v12; // ebp
__int64 v13; // r14
__int64 v14; // rbx
unsigned int v15; // eax
unsigned __int64 v16; // rcx
unsigned int v17; // eax
unsigned __int64 v18; // rcx
__int64 v19; // rdx
unsigned int v20; // eax
int result; // eax
std::ostream *v23; // rbx
char v24; // dl
std::ostream *v33; // rbx
std::ostream *v41; // rbx
__int64 v42; // rdx
unsigned int v43; // eax
int v44; // ebp
__int64 v45; // r14
__int64 v46; // rbx
unsigned __int64 v47; // rax
unsigned __int64 v48; // rax
std::ostream *v50; // rdi
char v51; // dl
std::ostream *v58; // rdi
std::ostream *v60; // rdi
__int64 v61; // rdx
unsigned int v62; // eax
__asm
{
vmovdqa [rsp+98h+var_58], xmm8
vmovapd [rsp+98h+var_68], xmm7
vmovapd [rsp+98h+var_78], xmm6
}
if ( argc == 2 )
{
v6 = atol(argv[1]) << 20;
_R15 = v6;
v8 = operator new[](v6);
if ( v6 )
{
v9 = 1;
for ( i = 0i64; i < v6; i = v9++ )
v8[i] = rand();
}
v11 = (unsigned __int64)v6 >> 3;
v12 = 0;
v13 = Xtime_get_ticks_0();
v14 = 0i64;
do
{
if ( v6 )
{
v15 = 4;
v16 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 8]);
v16 = v15;
v15 += 4;
}
while ( v11 > v16 );
v17 = 4;
v18 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v18])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 8]);
v18 = v17;
v17 += 4;
}
while ( v11 > v18 );
}
v12 += 2;
}
while ( v12 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v13);
std::operator___std::char_traits_char___(std::cout, "unsigned\t");
v23 = (std::ostream *)std::ostream::operator<<(std::cout, v14);
std::operator___std::char_traits_char____0(v23, v24);
__asm
{
vmovq xmm0, rbp
vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
vpunpckldq xmm0, xmm0, xmm8
vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v33 = (std::ostream *)std::ostream::operator<<(v23);
std::operator___std::char_traits_char___(v33, " sec \t");
__asm
{
vmovq xmm0, r15
vpunpckldq xmm0, xmm0, xmm8
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm0, xmm1, xmm0
vmulsd xmm7, xmm0, cs:__real@40c3880000000000
vdivsd xmm1, xmm7, xmm6
}
v41 = (std::ostream *)std::ostream::operator<<(v33);
std::operator___std::char_traits_char___(v41, " GB/s");
LOBYTE(v42) = 10;
v43 = std::ios::widen((char *)v41 + *(int *)(*(_QWORD *)v41 + 4i64), v42);
std::ostream::put(v41, v43);
std::ostream::flush(v41);
v44 = 0;
v45 = Xtime_get_ticks_0();
v46 = 0i64;
do
{
if ( v6 )
{
v47 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v47])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 24]);
v47 += 4i64;
}
while ( v47 < v11 );
v48 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v48])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 24]);
v48 += 4i64;
}
while ( v48 < v11 );
}
v44 += 2;
}
while ( v44 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v45);
std::operator___std::char_traits_char___(std::cout, "uint64_t\t");
v50 = (std::ostream *)std::ostream::operator<<(std::cout, v46);
std::operator___std::char_traits_char____0(v50, v51);
__asm
{
vmovq xmm0, rbp
vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v58 = (std::ostream *)std::ostream::operator<<(v50);
std::operator___std::char_traits_char___(v58, " sec \t");
__asm { vdivsd xmm1, xmm7, xmm6 }
v60 = (std::ostream *)std::ostream::operator<<(v58);
std::operator___std::char_traits_char___(v60, " GB/s");
LOBYTE(v61) = 10;
v62 = std::ios::widen((char *)v60 + *(int *)(*(_QWORD *)v60 + 4i64), v61);
std::ostream::put(v60, v62);
std::ostream::flush(v60);
free(v8);
result = 0;
}
else
{
std::operator___std::char_traits_char___(std::cerr, "usage: array_size in MB");
LOBYTE(v19) = 10;
v20 = std::ios::widen((char *)&std::cerr + *((int *)std::cerr + 1), v19);
std::ostream::put(std::cerr, v20);
std::ostream::flush(std::cerr);
result = -1;
}
__asm
{
vmovaps xmm6, [rsp+98h+var_78]
vmovaps xmm7, [rsp+98h+var_68]
vmovaps xmm8, [rsp+98h+var_58]
}
return result;
}
and disassembly of main:
.text:0140001000 .686p
.text:0140001000 .mmx
.text:0140001000 .model flat
.text:0140001000
.text:0140001000 ; ===========================================================================
.text:0140001000
.text:0140001000 ; Segment type: Pure code
.text:0140001000 ; Segment permissions: Read/Execute
.text:0140001000 _text segment para public 'CODE' use64
.text:0140001000 assume cs:_text
.text:0140001000 ;org 140001000h
.text:0140001000 assume es:nothing, ss:nothing, ds:_data, fs:nothing, gs:nothing
.text:0140001000
.text:0140001000 ; =============== S U B R O U T I N E =======================================
.text:0140001000
.text:0140001000
.text:0140001000 ; int __cdecl main(int argc, const char **argv, const char **envp)
.text:0140001000 main proc near ; CODE XREF: __scrt_common_main_seh+107?p
.text:0140001000 ; DATA XREF: .pdata:ExceptionDir?o
.text:0140001000
.text:0140001000 var_78 = xmmword ptr -78h
.text:0140001000 var_68 = xmmword ptr -68h
.text:0140001000 var_58 = xmmword ptr -58h
.text:0140001000
.text:0140001000 push r15
.text:0140001002 push r14
.text:0140001004 push r13
.text:0140001006 push r12
.text:0140001008 push rsi
.text:0140001009 push rdi
.text:014000100A push rbp
.text:014000100B push rbx
.text:014000100C sub rsp, 58h
.text:0140001010 vmovdqa [rsp+98h+var_58], xmm8
.text:0140001016 vmovapd [rsp+98h+var_68], xmm7
.text:014000101C vmovapd [rsp+98h+var_78], xmm6
.text:0140001022 cmp ecx, 2
.text:0140001025 jnz loc_14000113E
.text:014000102B mov rcx, [rdx+8] ; String
.text:014000102F call cs:__imp_atol
.text:0140001035 mov r13d, eax
.text:0140001038 shl r13d, 14h
.text:014000103C movsxd r15, r13d
.text:014000103F mov rcx, r15 ; size
.text:0140001042 call ??_U@YAPEAX_K@Z ; operator new[](unsigned __int64)
.text:0140001047 mov rsi, rax
.text:014000104A test r15d, r15d
.text:014000104D jz short loc_14000106E
.text:014000104F mov edi, 1
.text:0140001054 xor ebx, ebx
.text:0140001056 mov rbp, cs:__imp_rand
.text:014000105D nop dword ptr [rax]
.text:0140001060
.text:0140001060 loc_140001060: ; CODE XREF: main+6C?j
.text:0140001060 call rbp ; __imp_rand
.text:0140001062 mov [rsi+rbx], al
.text:0140001065 mov ebx, edi
.text:0140001067 inc edi
.text:0140001069 cmp rbx, r15
.text:014000106C jb short loc_140001060
.text:014000106E
.text:014000106E loc_14000106E: ; CODE XREF: main+4D?j
.text:014000106E mov rdi, r15
.text:0140001071 shr rdi, 3
.text:0140001075 xor ebp, ebp
.text:0140001077 call _Xtime_get_ticks_0
.text:014000107C mov r14, rax
.text:014000107F xor ebx, ebx
.text:0140001081 jmp short loc_14000109F
.text:0140001081 ; ---------------------------------------------------------------------------
.text:0140001083 align 10h
.text:0140001090
.text:0140001090 loc_140001090: ; CODE XREF: main+A2?j
.text:0140001090 ; main+EC?j ...
.text:0140001090 add ebp, 2
.text:0140001093 cmp ebp, 2710h
.text:0140001099 jz loc_140001184
.text:014000109F
.text:014000109F loc_14000109F: ; CODE XREF: main+81?j
.text:014000109F test r13d, r13d
.text:01400010A2 jz short loc_140001090
.text:01400010A4 mov eax, 4
.text:01400010A9 xor ecx, ecx
.text:01400010AB nop dword ptr [rax+rax+00h]
.text:01400010B0
.text:01400010B0 loc_1400010B0: ; CODE XREF: main+E7?j
.text:01400010B0 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010B6 add rcx, rbx
.text:01400010B9 lea edx, [rax-3]
.text:01400010BC popcnt rdx, qword ptr [rsi+rdx*8]
.text:01400010C2 add rdx, rcx
.text:01400010C5 lea ecx, [rax-2]
.text:01400010C8 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010CE add rcx, rdx
.text:01400010D1 lea edx, [rax-1]
.text:01400010D4 xor ebx, ebx
.text:01400010D6 popcnt rbx, qword ptr [rsi+rdx*8]
.text:01400010DC add rbx, rcx
.text:01400010DF mov ecx, eax
.text:01400010E1 add eax, 4
.text:01400010E4 cmp rdi, rcx
.text:01400010E7 ja short loc_1400010B0
.text:01400010E9 test r13d, r13d
.text:01400010EC jz short loc_140001090
.text:01400010EE mov eax, 4
.text:01400010F3 xor ecx, ecx
.text:01400010F5 db 2Eh
.text:01400010F5 nop word ptr [rax+rax+00000000h]
.text:01400010FF nop
.text:0140001100
.text:0140001100 loc_140001100: ; CODE XREF: main+137?j
.text:0140001100 popcnt rcx, qword ptr [rsi+rcx*8]
.text:0140001106 add rcx, rbx
.text:0140001109 lea edx, [rax-3]
.text:014000110C popcnt rdx, qword ptr [rsi+rdx*8]
.text:0140001112 add rdx, rcx
.text:0140001115 lea ecx, [rax-2]
.text:0140001118 popcnt rcx, qword ptr [rsi+rcx*8]
.text:014000111E add rcx, rdx
.text:0140001121 lea edx, [rax-1]
.text:0140001124 xor ebx, ebx
.text:0140001126 popcnt rbx, qword ptr [rsi+rdx*8]
.text:014000112C add rbx, rcx
.text:014000112F mov ecx, eax
.text:0140001131 add eax, 4
.text:0140001134 cmp rdi, rcx
.text:0140001137 ja short loc_140001100
.text:0140001139 jmp loc_140001090
.text:014000113E ; ---------------------------------------------------------------------------
.text:014000113E
.text:014000113E loc_14000113E: ; CODE XREF: main+25?j
.text:014000113E mov rsi, cs:__imp_?cerr@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cerr
.text:0140001145 lea rdx, aUsageArraySize ; "usage: array_size in MB"
.text:014000114C mov rcx, rsi ; std::ostream *
.text:014000114F call std__operator___std__char_traits_char___
.text:0140001154 mov rax, [rsi]
.text:0140001157 movsxd rcx, dword ptr [rax+4]
.text:014000115B add rcx, rsi
.text:014000115E mov dl, 0Ah
.text:0140001160 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:0140001166 mov rcx, rsi
.text:0140001169 mov edx, eax
.text:014000116B call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001171 mov rcx, rsi
.text:0140001174 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000117A mov eax, 0FFFFFFFFh
.text:014000117F jmp loc_1400013E2
.text:0140001184 ; ---------------------------------------------------------------------------
.text:0140001184
.text:0140001184 loc_140001184: ; CODE XREF: main+99?j
.text:0140001184 call _Xtime_get_ticks_0
.text:0140001189 sub rax, r14
.text:014000118C imul rbp, rax, 64h ; 'd'
.text:0140001190 mov r14, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001197 lea rdx, aUnsigned ; "unsigned\t"
.text:014000119E mov rcx, r14 ; std::ostream *
.text:01400011A1 call std__operator___std__char_traits_char___
.text:01400011A6 mov rcx, r14
.text:01400011A9 mov rdx, rbx
.text:01400011AC call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:01400011B2 mov rbx, rax
.text:01400011B5 mov rcx, rax ; std::ostream *
.text:01400011B8 call std__operator___std__char_traits_char____0
.text:01400011BD vmovq xmm0, rbp
.text:01400011C2 vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
.text:01400011CA vpunpckldq xmm0, xmm0, xmm8
.text:01400011CF vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
.text:01400011D7 vsubpd xmm0, xmm0, xmm7
.text:01400011DB vpermilpd xmm1, xmm0, 1
.text:01400011E1 vaddsd xmm6, xmm1, xmm0
.text:01400011E5 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:01400011ED mov r12, cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z ; std::ostream::operator<<(double)
.text:01400011F4 mov rcx, rbx
.text:01400011F7 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:01400011FA mov rbx, rax
.text:01400011FD lea rdx, aSec ; " sec \t"
.text:0140001204 mov rcx, rax ; std::ostream *
.text:0140001207 call std__operator___std__char_traits_char___
.text:014000120C vmovq xmm0, r15
.text:0140001211 vpunpckldq xmm0, xmm0, xmm8
.text:0140001216 vsubpd xmm0, xmm0, xmm7
.text:014000121A vpermilpd xmm1, xmm0, 1
.text:0140001220 vaddsd xmm0, xmm1, xmm0
.text:0140001224 vmulsd xmm7, xmm0, cs:__real@40c3880000000000
.text:014000122C vdivsd xmm1, xmm7, xmm6
.text:0140001230 mov rcx, rbx
.text:0140001233 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001236 mov rbx, rax
.text:0140001239 lea rdx, aGbS ; " GB/s"
.text:0140001240 mov rcx, rax ; std::ostream *
.text:0140001243 call std__operator___std__char_traits_char___
.text:0140001248 mov rax, [rbx]
.text:014000124B movsxd rcx, dword ptr [rax+4]
.text:014000124F add rcx, rbx
.text:0140001252 mov dl, 0Ah
.text:0140001254 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:014000125A mov rcx, rbx
.text:014000125D mov edx, eax
.text:014000125F call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001265 mov rcx, rbx
.text:0140001268 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000126E xor ebp, ebp
.text:0140001270 call _Xtime_get_ticks_0
.text:0140001275 mov r14, rax
.text:0140001278 xor ebx, ebx
.text:014000127A jmp short loc_14000128F
.text:014000127A ; ---------------------------------------------------------------------------
.text:014000127C align 20h
.text:0140001280
.text:0140001280 loc_140001280: ; CODE XREF: main+292?j
.text:0140001280 ; main+2DB?j ...
.text:0140001280 add ebp, 2
.text:0140001283 cmp ebp, 2710h
.text:0140001289 jz loc_14000131D
.text:014000128F
.text:014000128F loc_14000128F: ; CODE XREF: main+27A?j
.text:014000128F test r13d, r13d
.text:0140001292 jz short loc_140001280
.text:0140001294 xor eax, eax
.text:0140001296 db 2Eh
.text:0140001296 nop word ptr [rax+rax+00000000h]
.text:01400012A0
.text:01400012A0 loc_1400012A0: ; CODE XREF: main+2D6?j
.text:01400012A0 xor ecx, ecx
.text:01400012A2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012A8 add rcx, rbx
.text:01400012AB xor edx, edx
.text:01400012AD popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012B4 add rdx, rcx
.text:01400012B7 xor ecx, ecx
.text:01400012B9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:01400012C0 add rcx, rdx
.text:01400012C3 xor ebx, ebx
.text:01400012C5 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:01400012CC add rbx, rcx
.text:01400012CF add rax, 4
.text:01400012D3 cmp rax, rdi
.text:01400012D6 jb short loc_1400012A0
.text:01400012D8 test r13d, r13d
.text:01400012DB jz short loc_140001280
.text:01400012DD xor eax, eax
.text:01400012DF nop
.text:01400012E0
.text:01400012E0 loc_1400012E0: ; CODE XREF: main+316?j
.text:01400012E0 xor ecx, ecx
.text:01400012E2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012E8 add rcx, rbx
.text:01400012EB xor edx, edx
.text:01400012ED popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012F4 add rdx, rcx
.text:01400012F7 xor ecx, ecx
.text:01400012F9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:0140001300 add rcx, rdx
.text:0140001303 xor ebx, ebx
.text:0140001305 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:014000130C add rbx, rcx
.text:014000130F add rax, 4
.text:0140001313 cmp rax, rdi
.text:0140001316 jb short loc_1400012E0
.text:0140001318 jmp loc_140001280
.text:014000131D ; ---------------------------------------------------------------------------
.text:014000131D
.text:014000131D loc_14000131D: ; CODE XREF: main+289?j
.text:014000131D call _Xtime_get_ticks_0
.text:0140001322 sub rax, r14
.text:0140001325 imul rbp, rax, 64h ; 'd'
.text:0140001329 mov rdi, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001330 lea rdx, aUint64T ; "uint64_t\t"
.text:0140001337 mov rcx, rdi ; std::ostream *
.text:014000133A call std__operator___std__char_traits_char___
.text:014000133F mov rcx, rdi
.text:0140001342 mov rdx, rbx
.text:0140001345 call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:014000134B mov rdi, rax
.text:014000134E mov rcx, rax ; std::ostream *
.text:0140001351 call std__operator___std__char_traits_char____0
.text:0140001356 vmovq xmm0, rbp
.text:014000135B vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
.text:0140001363 vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
.text:014000136B vpermilpd xmm1, xmm0, 1
.text:0140001371 vaddsd xmm6, xmm1, xmm0
.text:0140001375 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:014000137D mov rcx, rdi
.text:0140001380 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001383 mov rdi, rax
.text:0140001386 lea rdx, aSec ; " sec \t"
.text:014000138D mov rcx, rax ; std::ostream *
.text:0140001390 call std__operator___std__char_traits_char___
.text:0140001395 vdivsd xmm1, xmm7, xmm6
.text:0140001399 mov rcx, rdi
.text:014000139C call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:014000139F mov rdi, rax
.text:01400013A2 lea rdx, aGbS ; " GB/s"
.text:01400013A9 mov rcx, rax ; std::ostream *
.text:01400013AC call std__operator___std__char_traits_char___
.text:01400013B1 mov rax, [rdi]
.text:01400013B4 movsxd rcx, dword ptr [rax+4]
.text:01400013B8 add rcx, rdi
.text:01400013BB mov dl, 0Ah
.text:01400013BD call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:01400013C3 mov rcx, rdi
.text:01400013C6 mov edx, eax
.text:01400013C8 call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:01400013CE mov rcx, rdi
.text:01400013D1 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:01400013D7 mov rcx, rsi ; Block
.text:01400013DA call cs:__imp_free
.text:01400013E0 xor eax, eax
.text:01400013E2
.text:01400013E2 loc_1400013E2: ; CODE XREF: main+17F?j
.text:01400013E2 vmovaps xmm6, [rsp+98h+var_78]
.text:01400013E8 vmovaps xmm7, [rsp+98h+var_68]
.text:01400013EE vmovaps xmm8, [rsp+98h+var_58]
.text:01400013F4 add rsp, 58h
.text:01400013F8 pop rbx
.text:01400013F9 pop rbp
.text:01400013FA pop rdi
.text:01400013FB pop rsi
.text:01400013FC pop r12
.text:01400013FE pop r13
.text:0140001400 pop r14
.text:0140001402 pop r15
.text:0140001404 retn
.text:0140001404 main endp
Coffee lake specification update "POPCNT instruction may take longer to execute than expected".
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
On Mac OS X, for anyone having:
-bash: /usr/local/bin/composer: Permission denied
problem, while trying to move downloaded composer.phar
using:
mv composer.phar /usr/local/bin/composer
this is the cause:
System Integrity Protection
and this is the solution:
csrutil disable
and hit enter. You should see a msg returned saying that:
the System Integrity Protection is off.
/usr/bin
and NOT /usr/local/bin
because for some reason it just didn't work there.csrutil enable
The above 6 steps are copied from here, so all the credit belongs to the user Vasheer there.
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
It IS possible, using something like the below example that I put together with the help of work from (https://gist.github.com/bitinn/1700068a276fb29740a7) that didn't quite work on iOS 11:
Here's the modified code that works on iOS 11.03, please comment if it worked for you.
The key is adding some size to BODY so the browser can scroll, ex: height: calc(100% + 40px);
Full sample below & link to view in your browser (please test!)
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeHots iOS WebApp Minimal UI via Scroll Test</title>
<style>
html, body {
height: 100%;
}
html {
background-color: red;
}
body {
background-color: blue;
/* important to allow page to scroll */
height: calc(100% + 40px);
margin: 0;
}
div.header {
width: 100%;
height: 40px;
background-color: green;
overflow: hidden;
}
div.content {
height: 100%;
height: calc(100% - 40px);
width: 100%;
background-color: purple;
overflow: hidden;
}
div.cover {
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
display: none;
}
@media screen and (width: 320px) {
html {
height: calc(100% + 72px);
}
div.cover {
display: block;
}
}
</style>
<script>
var timeout;
function interceptTouchMove(){
// and disable the touchmove features
window.addEventListener("touchmove", (event)=>{
if (!event.target.classList.contains('scrollable')) {
// no more scrolling
event.preventDefault();
}
}, false);
}
function scrollDetect(event){
// wait for the result to settle
if( timeout ) clearTimeout(timeout);
timeout = setTimeout(function() {
console.log( 'scrolled up detected..' );
if (window.scrollY > 35) {
console.log( ' .. moved up enough to go into minimal UI mode. cover off and locking touchmove!');
// hide the fixed scroll-cover
var cover = document.querySelector('div.cover');
cover.style.display = 'none';
// push back down to designated start-point. (as it sometimes overscrolls (this is jQuery implementation I used))
window.scrollY = 40;
// and disable the touchmove features
interceptTouchMove();
// turn off scroll checker
window.removeEventListener('scroll', scrollDetect );
}
}, 200);
}
// listen to scroll to know when in minimal-ui mode.
window.addEventListener('scroll', scrollDetect, false );
</script>
</head>
<body>
<div class="header">
<p>header zone</p>
</div>
<div class="content">
<p>content</p>
</div>
<div class="cover">
<p>scroll to soft fullscreen</p>
</div>
</body>
Full example link here: https://repos.codehot.tech/misc/ios-webapp-example2.html
Swifter Swift has a pretty sweet way to do this without any work really. Just provide the pattern that should be matched and what attributes to apply to it. They're great for a lot of things check them out.
``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``
If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.
You can do this in one step, just easier to read when separated.
I have found a nice tutorial about this topic:
https://springframework.guru/using-the-h2-database-console-in-spring-boot-with-spring-security/
Basically the correct JDBC URL for me was: jdbc:h2:mem:testdb
Albeit from the useless _T
and incorrectly spelled histories. If you are using SQL*Plus
, it does not accept create table statements with empty new lines between create table <name> (
and column definitions.
Bootstrap 4: navbar Active State working, just use .navbar-nav .nav-link classes
$(function () {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".navbar-nav .nav-link").each(function () {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
//for making parent of submenu active
$(this).closest("li").parent().parent().addClass("active");
}
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Other</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
_x000D_
Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:
"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage
which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh
"thought" that it is run in the regular terminal and since it may be accomplished by simple posix
functions, it is beyond what simple bash
offers.
First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like choices.py
:
STATUS_CHOICES = (
(1, _("Not relevant")),
(2, _("Review")),
(3, _("Maybe relevant")),
(4, _("Relevant")),
(5, _("Leading candidate"))
)
RELEVANCE_CHOICES = (
(1, _("Unread")),
(2, _("Read"))
)
Now you need to import them on the models, so the code is easy to understand like this(models.py):
from myApp.choices import *
class Profile(models.Model):
user = models.OneToOneField(User)
status = models.IntegerField(choices=STATUS_CHOICES, default=1)
relevance = models.IntegerField(choices=RELEVANCE_CHOICES, default=1)
And you have to import the choices in the forms.py too:
forms.py:
from myApp.choices import *
class CViewerForm(forms.Form):
status = forms.ChoiceField(choices = STATUS_CHOICES, label="", initial='', widget=forms.Select(), required=True)
relevance = forms.ChoiceField(choices = RELEVANCE_CHOICES, required=True)
Anyway you have an issue with your template, because you're not using any {{form.field}}
, you generate a table but there is no inputs only hidden_fields.
When the user is staff you should generate as many input fields as users you can manage. I think django form is not the best solution for your situation.
I think it will be better for you to use html form, so you can generate as many inputs using the boucle: {% for user in users_list %}
and you generate input with an ID related to the user, and you can manage all of them in the view.
*Note : This will show popup once per browser as the data is stored in browser memory.
Try HTML localStorage.
Methods :
localStorage.getItem('key');
localStorage.setItem('key','value');
$j(document).ready(function() {
if(localStorage.getItem('popState') != 'shown'){
$j('#popup').delay(2000).fadeIn();
localStorage.setItem('popState','shown')
}
$j('#popup-close, #popup').click(function() // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hidden.
});
});
If you just used git init
and have added your files with git add .
or something similar and have added your remote branch it might be that you just haven't committed (git commit -m 'commit message'
) anything locally to push to the remote... I just had this error and that was my issue.
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
The tsc -v
command run technically reads the TypeScript compiler version within the SDK directory set within the Windows Path
variable. This doesn't necessarily reflect the latest version installed as the Path
variable is not updated with subsequent installations.
The version that VS.NET uses to compile the TypeScript is what's in the project's configuration:
<TypeScriptToolsVersion>1.5</TypeScriptToolsVersion>
To help explain this more in detail I created the following post which has the specifics on the TypeScript versions installed, and which version VS.NET uses to compile the TypeScript files.
Which Version of TypeScript is Installed and Which Version is Visual Studio Using?
I also added a feature request on Microsoft Connect to make viewing and switching the TypeScript targeted version in VS.NET easier. This isn't really a TypeScript feature request as much as it is a VS.NET IDE enhancement.
Allow switching TypeScript configured version from Project Properties IDE
This might help some who come across this error. If you are working across a VPN and it becomes disconnected, you can also get this error. The simple fix is to reconnect your VPN.
If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.
In Sourcetree:
Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.
A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes
if (c == '\n')
Most importantly you need to mount the drive
net use z: \\yourserver\sharename
Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:
"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.
Then run your batch script with the following changes
copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
have you tried this?
-
name: Jack
age: 32
-
name: Claudia
age: 25
I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}]
(I use the YAML
Ruby class).
Just catch the submit event and prevent that, then do ajax
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
This happened with me when I was trying to access my site from a remote location:
At first, applicationhost.config (VS2015) contained the standard:
<binding protocol="http" bindingInformation="*:64376:localhost" />
In order to access my site from a remote location within the network, I added (step 1):
<binding protocol="http" bindingInformation="*:64376:192.168.10.132" />
Then, I entered into CMD with Admin rights (step 2):
netsh http add urlacl url=http://*:64376/ user=Everyone
As step 3, I added it a rule to the firewall.
netsh advfirewall firewall add rule name=”IISExpressWeb” dir=in protocol=tcp localport=64376 profile=private,domain remoteip=localsubnet action=allow
Then, I got this error when trying to run the solution again.
Solution: I seemed to have done everything right, but it did not work until I ran netsh
also for the existing localhost rule:
netsh http add urlacl url=http://localhost:64376/ user=Everyone
Now, it works again.
Try this:
.navbar {
position: relative;
}
.brand {
position: absolute;
left: 50%;
margin-left: -50px !important; /* 50% of your logo width */
display: block;
}
Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.
See fiddle
You get the error because if
can only evaluate a logical
vector of length 1.
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
This is about the HTML parse mechanism.
The HTML parser will parse the HTML content from top to bottom. In your script logic,
jQuery('#datetimepicker')
will return an empty instance because the element has not loaded yet.
You can use
$(function(){ your code here });
or
$(document).ready(function(){ your code here });
to parse HTML element firstly, and then do your own script logics.
You can use the Material Components Library and the MaterialButton
component.
Use the app:icon
and app:iconGravity="start"
attributes.
Something like:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/..."
app:iconGravity="start"
../>
I want to share an approach commented about and briefly discussed but show an actual example that I am currently using to help unit test EF-based services.
First, I would love to use the in-memory provider from EF Core, but this is about EF 6. Furthermore, for other storage systems like RavenDB, I'd also be a proponent of testing via the in-memory database provider. Again--this is specifically to help test EF-based code without a lot of ceremony.
Here are the goals I had when coming up with a pattern:
I agree with previous statements that EF is still an implementation detail and it's okay to feel like you need to abstract it in order to do a "pure" unit test. I also agree that ideally, I would want to ensure the EF code itself works--but this involves a sandbox database, in-memory provider, etc. My approach solves both problems--you can safely unit test EF-dependent code and create integration tests to test your EF code specifically.
The way I achieved this was through simply encapsulating EF code into dedicated Query and Command classes. The idea is simple: just wrap any EF code in a class and depend on an interface in the classes that would've originally used it. The main issue I needed to solve was to avoid adding numerous dependencies to classes and setting up a lot of code in my tests.
This is where a useful, simple library comes in: Mediatr. It allows for simple in-process messaging and it does it by decoupling "requests" from the handlers that implement the code. This has an added benefit of decoupling the "what" from the "how". For example, by encapsulating the EF code into small chunks it allows you to replace the implementations with another provider or totally different mechanism, because all you are doing is sending a request to perform an action.
Utilizing dependency injection (with or without a framework--your preference), we can easily mock the mediator and control the request/response mechanisms to enable unit testing EF code.
First, let's say we have a service that has business logic we need to test:
public class FeatureService {
private readonly IMediator _mediator;
public FeatureService(IMediator mediator) {
_mediator = mediator;
}
public async Task ComplexBusinessLogic() {
// retrieve relevant objects
var results = await _mediator.Send(new GetRelevantDbObjectsQuery());
// normally, this would have looked like...
// var results = _myDbContext.DbObjects.Where(x => foo).ToList();
// perform business logic
// ...
}
}
Do you start to see the benefit of this approach? Not only are you explicitly encapsulating all EF-related code into descriptive classes, you are allowing extensibility by removing the implementation concern of "how" this request is handled--this class doesn't care if the relevant objects come from EF, MongoDB, or a text file.
Now for the request and handler, via MediatR:
public class GetRelevantDbObjectsQuery : IRequest<DbObject[]> {
// no input needed for this particular request,
// but you would simply add plain properties here if needed
}
public class GetRelevantDbObjectsEFQueryHandler : IRequestHandler<GetRelevantDbObjectsQuery, DbObject[]> {
private readonly IDbContext _db;
public GetRelevantDbObjectsEFQueryHandler(IDbContext db) {
_db = db;
}
public DbObject[] Handle(GetRelevantDbObjectsQuery message) {
return _db.DbObjects.Where(foo => bar).ToList();
}
}
As you can see, the abstraction is simple and encapsulated. It's also absolutely testable because in an integration test, you could test this class individually--there are no business concerns mixed in here.
So what does a unit test of our feature service look like? It's way simple. In this case, I'm using Moq to do mocking (use whatever makes you happy):
[TestClass]
public class FeatureServiceTests {
// mock of Mediator to handle request/responses
private Mock<IMediator> _mediator;
// subject under test
private FeatureService _sut;
[TestInitialize]
public void Setup() {
// set up Mediator mock
_mediator = new Mock<IMediator>(MockBehavior.Strict);
// inject mock as dependency
_sut = new FeatureService(_mediator.Object);
}
[TestCleanup]
public void Teardown() {
// ensure we have called or expected all calls to Mediator
_mediator.VerifyAll();
}
[TestMethod]
public void ComplexBusinessLogic_Does_What_I_Expect() {
var dbObjects = new List<DbObject>() {
// set up any test objects
new DbObject() { }
};
// arrange
// setup Mediator to return our fake objects when it receives a message to perform our query
// in practice, I find it better to create an extension method that encapsulates this setup here
_mediator.Setup(x => x.Send(It.IsAny<GetRelevantDbObjectsQuery>(), default(CancellationToken)).ReturnsAsync(dbObjects.ToArray()).Callback(
(GetRelevantDbObjectsQuery message, CancellationToken token) => {
// using Moq Callback functionality, you can make assertions
// on expected request being passed in
Assert.IsNotNull(message);
});
// act
_sut.ComplexBusinessLogic();
// assertions
}
}
You can see all we need is a single setup and we don't even need to configure anything extra--it's a very simple unit test. Let's be clear: This is totally possible to do without something like Mediatr (you would simply implement an interface and mock it for tests, e.g. IGetRelevantDbObjectsQuery
), but in practice for a large codebase with many features and queries/commands, I love the encapsulation and innate DI support Mediatr offers.
If you're wondering how I organize these classes, it's pretty simple:
- MyProject
- Features
- MyFeature
- Queries
- Commands
- Services
- DependencyConfig.cs (Ninject feature modules)
Organizing by feature slices is beside the point, but this keeps all relevant/dependent code together and easily discoverable. Most importantly, I separate the Queries vs. Commands--following the Command/Query Separation principle.
This meets all my criteria: it's low-ceremony, it's easy to understand, and there are extra hidden benefits. For example, how do you handle saving changes? Now you can simplify your Db Context by using a role interface (IUnitOfWork.SaveChangesAsync()
) and mock calls to the single role interface or you could encapsulate committing/rolling back inside your RequestHandlers--however you prefer to do it is up to you, as long as it's maintainable. For example, I was tempted to create a single generic request/handler where you'd just pass an EF object and it would save/update/remove it--but you have to ask what your intention is and remember that if you wanted to swap out the handler with another storage provider/implementation, you should probably create explicit commands/queries that represent what you intend to do. More often than not, a single service or feature will need something specific--don't create generic stuff before you have a need for it.
There are of course caveats to this pattern--you can go too far with a simple pub/sub mechanism. I've limited my implementation to only abstracting EF-related code, but adventurous developers could start using MediatR to go overboard and message-ize everything--something good code review practices and peer reviews should catch. That's a process issue, not an issue with MediatR, so just be cognizant of how you're using this pattern.
You wanted a concrete example of how people are unit testing/mocking EF and this is an approach that's working successfully for us on our project--and the team is super happy with how easy it is to adopt. I hope this helps! As with all things in programming, there are multiple approaches and it all depends on what you want to achieve. I value simplicity, ease of use, maintainability, and discoverability--and this solution meets all those demands.
I am using EF Core with ASP.NET Core V2.2.6. @Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.
So, For those using EF Core with ASP.NET Core V2.2.6 +...
instead of
Update-Database <Name of last good migration>
I had to use:
dotnet ef database update <Name of last good migration>
And instead of
Remove-Migration
I had to use:
dotnet ef migrations remove
For --help
i had to use :
dotnet ef migrations --help
Usage: dotnet ef migrations [options] [command]
Options:
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
add Adds a new migration.
list Lists available migrations.
remove Removes the last migration.
script Generates a SQL script from migrations.
Use "migrations [command] --help" for more information about a command.
This let me role back to the stage where my DB worked as expected, and start from beginning.
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
I came up with this three liner.
Essentially, here's what it does:
inp = pd.read_csv('filename.csv') # read input. Add read_csv arguments as needed
columns = pd.DataFrame({'column_names': inp.columns, 'datatypes': inp.dtypes})
columns.to_csv(inp+'columns_list.csv', encoding='utf-8') # encoding is optional
This made my life much easier in trying to generate schemas on the fly. Hope this helps
Using command prompt in windows you can use below command to get class files.
wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl
if you want to generate source code you should be using below commnad.
wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl
Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.
I had a similar problem, just verify the port where your Mysql server is running, that will solve the problem
For example, my code was:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/bddventas","root","");
i change the string to
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bddventas","root","");
and voila!!, this workd because my server was running on that port
Hope this help
You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.
You can use Boost numeric_cast
.
This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double
.
Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t
is greater than INT_MAX
. If you want to detect it use numeric_cast
or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast
to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.
You can't really compare NA
with another value, so using ==
would not work. Consider the following:
NA == NA
# [1] NA
You can just change your comparison from ==
to %in%
:
ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA "1" NA "1"
Regarding your other question,
I could get this to work with my existing code if I could somehow change the result of
is.na(test$type)
to returnFALSE
instead ofTRUE
, but I'm not sure how to do that.
just use !
to negate the results:
!is.na(test$time)
# [1] TRUE TRUE FALSE TRUE
get()
returned more than one topic -- it returned 2!
The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get()
such as
Model.objects.get(field_name=some_param)
To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.
So instead of using get()
you should use filter()
which will return multiple records. Such as
Model.objects.filter(field_name=some_param)
Please read about how to make queries in django here.
The problem:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.
For Jersey 1.x you have to do it like this:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
For more information check the Jersey 1.x documentation.
If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.xx</version>
</dependency>
For Jersey 2.x you don't need to setup anything in your web.xml
, it is sufficient to supply a class similar to this:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
}
For more information, check the Jersey documentation.
See also:
Set the timeout parameter:
r = requests.get(w, verify=False, timeout=10) # 10 seconds
As long as you don't set stream=True
on that request, this will cause the call to requests.get()
to timeout if the connection takes more than ten seconds, or if the server doesn't send data for more than ten seconds.
Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.
Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.
var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
var byteArray = new Uint8Array(e.target.response);
// var shortArray = new Int16Array(e.target.response);
// var unsignedShortArray = new Int16Array(e.target.response);
// etc.
}
req.send();
The send request fails if the base 64 string is badly formed.
The mime type (application/octet) is probably unnecessary.
Tested in chrome. Should work in other browsers.
This is just my personal opinion and folks from web API team can probably articulate it better but here is my 2c.
First of all, I think it is not a question of one over another. You can use them both depending on what you want to do in your action method but in order to understand the real power of IHttpActionResult
, you will probably need to step outside those convenient helper methods of ApiController
such as Ok
, NotFound
, etc.
Basically, I think a class implementing IHttpActionResult
as a factory of HttpResponseMessage
. With that mind set, it now becomes an object that need to be returned and a factory that produces it. In general programming sense, you can create the object yourself in certain cases and in certain cases, you need a factory to do that. Same here.
If you want to return a response which needs to be constructed through a complex logic, say lots of response headers, etc, you can abstract all those logic into an action result class implementing IHttpActionResult
and use it in multiple action methods to return response.
Another advantage of using IHttpActionResult
as return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.
Of course, as noted by Darrel, you can chain action results and create a powerful micro-pipeline similar to message handlers themselves in the API pipeline. This you will need depending on the complexity of your action method.
Long story short - it is not IHttpActionResult
versus HttpResponseMessage
. Basically, it is how you want to create the response. Do it yourself or through a factory.
func tabGesture_Call
{
let tapRec = UITapGestureRecognizer(target: self, action: "handleTap:")
tapRec.delegate = self
self.view.addGestureRecognizer(tapRec)
//where we want to gesture like: view, label etc
}
func handleTap(sender: UITapGestureRecognizer)
{
NSLog("Touch..");
//handling code
}
I encountered the issue with the error:
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
Here is what I was doing and what finally worked.
Disclaimer: I am just getting my hands into Node, Angular after many years in the Java, Linux world among others...
Environment Description: Windows 8.1 64-bit; Cygwin; cygwin bash shell
Command used that led to error: npm install -g karma
Error: gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.
Discovery: 'which python' on bash shell clearly shows '/usr/bin/python'. Now that is annoying!
Solution: This is only applicable to those using the environment similar to what I have, i.e. using cygwin and bash shell. Hope it helps in other environments as well but keep in mind that your kettle of tea may look a little different than mine.
export PYTHON="C:/cygwin64/bin/python2.7.exe (or whatever is the version on your system)"
You should be fine now and gyp will find the python executable.
I hope this helps someone stumbling on the same or similar issue.
I dont know what do you exactly mean but hope it help you.
by this directive you can access the DOM element inside controller
this is sample that help you to focus element inside controller
.directive('scopeElement', function () {
return {
restrict:"A", // E-Element A-Attribute C-Class M-Comments
replace: false,
link: function($scope, elem, attrs) {
$scope[attrs.scopeElement] = elem[0];
}
};
})
now, inside HTML
<input scope-element="txtMessage" >
then, inside controller :
.controller('messageController', ['$scope', function ($scope) {
$scope.txtMessage.focus();
}])
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
You can make PHP and JavaScript work together by generating the following line in each page template:
<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>
Then you can refer to document.mybaseurl anywhere in your JavaScript. This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
table_ages <- subset(infert, select=c("age"))
summary(table_ages)
# age
# Min. :21.00
# 1st Qu.:28.00
# Median :31.00
# Mean :31.50
# 3rd Qu.:35.25
# Max. :44.00
This is probably what they're looking for. summary(...)
applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.
Note that
summary(infert$age)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 21.00 28.00 31.00 31.50 35.25 44.00
The numbers are the same but the format is different. This is because table_ages
is a data frame with one column (ages), whereas infert$age
is a numeric vector. Try typing summary(infert)
.
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
Building on @user3114046's answer:
x <- data.frame(q=1,w=2,e=3)
x
# q w e
#1 1 2 3
names(x)[match(oldnames,names(x))] <- newnames
x
# A w B
#1 1 2 3
This won't be reliant on a specific ordering of columns in the x
dataset.
If you want only portrait mode, in iOS 9 (Xcode 7) you can:
When using VS2019, MVC5 - look under Migrations folder for file Configuration.cs Edit : AutomaticMigrationsEnabled = true
I've read all of the above answers but it seems like they have no common strategy. I found a good article about best practices in Design API from Microsoft Documents. I think you should refer.
In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as
/customers/1/orders/99/products.
However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI/customers/1/orders
to find all the orders for customer 1, and then/orders/99/products
to find the products in this order.
.
Tip
Avoid requiring resource URIs more complex than
collection/item/collection
.
I used ToString() on a date with mm instead of MM.
As Jose answered, screen -d -r
should do the trick. This is a combination of two commands, as taken from the man page.
screen -d
detaches the already-running screen session, and screen -r
reattaches the existing session. By running screen -d -r
, you force screen to detach it and then resume the session.
If you use the capital -D -RR
, I quote the man page because it's too good to pass up.
Attach here and now. Whatever that means, just do it.
Note: It is always a good idea to check the status of your sessions by means of "screen -list".
you can read empList
directly in forEach
tag.Try this
<table>
<c:forEach items="${sessionScope.empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
</table>
You can use the Session object
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')
File.AppendAllText
does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText
will fail, throwing the exception you see.
I suggest you used str.Write
or str.WriteLine
instead, as you already do elsewhere in your code.
Your file is created but contains nothing because the exception is thrown before str.Flush()
and str.Close()
are called.
-SurfacePro3-
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
I know this is very old thread running, but still EF has not fixed this. For people using auto-generated DbContext
can use the following code to set the timeout manually.
public partial class SampleContext : DbContext
{
public SampleContext()
: base("name=SampleContext")
{
this.SetCommandTimeOut(180);
}
public void SetCommandTimeOut(int Timeout)
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
objectContext.CommandTimeout = Timeout;
}
A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.
...
constructor(props){
...
//create a ref
this.someRefName = React.createRef();
}
onScroll(){
let offsetTop = this.someRefName.current.offsetTop;
}
render(){
...
<Component ref={this.someRefName} />
}
You just want to set the field separator as .
using the -F
option and print the first field:
$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0
Same thing but using cut:
$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0
Or with sed
:
$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0
Even grep
:
$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0
Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you
You can also use the read-only property key
. It also respects special keys like shift etc. and is supported by IE9.
When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift'
or 'Multiply'
.
event.key
'x'
'X'
'F5'
Yet another non-bash-4 (i.e., bash 3, Mac-compatible) way:
val_of_key() {
case $1 in
'A1') echo 'aaa';;
'B2') echo 'bbb';;
'C3') echo 'ccc';;
*) echo 'zzz';;
esac
}
for x in 'A1' 'B2' 'C3' 'D4'; do
y=$(val_of_key "$x")
echo "$x => $y"
done
Prints:
A1 => aaa
B2 => bbb
C3 => ccc
D4 => zzz
The function with the case
acts like an associative array. Unfortunately it cannot use return
, so it has to echo
its output, but this is not a problem, unless you are a purist that shuns forking subshells.
Set the "long" type of id instead of java.lang.Integer. And add getters and setters to your fields.
HEAD
is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD
is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD
can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.
And @
alone is a shortcut for HEAD
, since Git 1.8.5
ORIG_HEAD
is previous state of HEAD
, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1}
is roughly equivalent to ORIG_HEAD
(HEAD@{1}
is always last value of HEAD
, ORIG_HEAD
is last value of HEAD
before dangerous operation).
For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary
Split() Variation
I just want to add this variation for reference. Urls are often strings and so it's simpler to use the Split()
method than Uri.GetLeftPart()
. And Split()
can also be made to work with relative, empty, and null values whereas Uri throws an exception. Additionally, Urls may also contain a hash such as /report.pdf#page=10
(which opens the pdf at a specific page).
The following method deals with all of these types of Urls:
var path = (url ?? "").Split('?', '#')[0];
Example Output:
page.html ---> page.html
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
This is exactly what the OUTPUT
clause in SQL Server 2005 onwards is excellent for.
EXAMPLE
CREATE TABLE [dbo].[test_table](
[LockId] [int] IDENTITY(1,1) NOT NULL,
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')
UPDATE test_table
SET StartTime = '2011 JUL 01'
OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed
WHERE
StartTime > '2009 JUL 09'
Results in the following being returned
LockId StartTime EndTime
-------------------------------------------------------
4 2011-07-01 00:00:00.000 2009-07-10 00:00:00.000
5 2011-07-01 00:00:00.000 2009-07-11 00:00:00.000
6 2011-07-01 00:00:00.000 2009-07-12 00:00:00.000
7 2011-07-01 00:00:00.000 2009-07-13 00:00:00.000
In your particular case, since you cannot use aggregate functions with OUTPUT
, you need to capture the output of INSERTED.*
in a table variable or temporary table and count the records. For example,
DECLARE @temp TABLE (
[LockId] [int],
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL
)
UPDATE test_table
SET StartTime = '2011 JUL 01'
OUTPUT INSERTED.* INTO @temp
WHERE
StartTime > '2009 JUL 09'
-- now get the count of affected records
SELECT COUNT(*) FROM @temp
"command + L" for MAC OS X.
"control + L" for Ubuntu
Clears the last line on the interactive session
It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:
System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84
I would recommend doing it in collectionView: willDisplay:
Then you can be sure that the collection view delegate delivers something.
Here my example:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
/// this is done to set the index on start to 1 to have at index 0 the last image to have a infinity loop
if !didScrollToSecondIndex {
self.scrollToItem(at: IndexPath(row: 1, section: 0), at: .left, animated: false)
didScrollToSecondIndex = true
}
}
The following code works for me. I am using Swift 5
let path = Bundle.main.path(forResource: "yourJSONfileName", ofType: "json")
var jsonData = try! String(contentsOfFile: path!).data(using: .utf8)!
Then, if your Person Struct (or Class) is Decodable (and also all of its properties), you can simply do:
let person = try! JSONDecoder().decode(Person.self, from: jsonData)
I avoided all the error handling code to make the code more legible.
On top of @mise's answer, After I installed MacOS Mojave, I also had to change files ownership on all my MAMP directory and contents).
From the Finder, I went in Application/MAMP
, showed files info (cmd
+ i
) and in permissions section added myself with read & write perms, then from the little gear applied to all the children.
Using HttpClient 3.x, you need to do this:
Protocol easyHttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyHttps);
An implementation of EasySSLProtocolSocketFactory can be found here.
You can try also using below script
<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>
<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html>
Try this regex
/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
It works best for me.
const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);
console.log(dates);
// you get the whole from-to date ranges as per parameters
var onlyStartDates = dates.map(dateObj => dateObj["to"]);
console.log(onlyStartDates);
// moreover, if you want only from dates then you can grab by "map" function
function getDatesFromDateRange( startDate, endDate, format, counter ) {
startDate = moment(startDate, format);
endDate = moment(endDate, format);
let dates = [];
let fromDate = startDate.clone();
let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
do {
dates.push({
"from": fromDate.format(format),
"to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
});
fromDate = moment(toDate, format).add(1, "day").clone();
toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
} while ( fromDate < endDate );
return dates;
}
Please note, .clone() is essential in momentjs else it'll override the value. It seems in your case.
It's more generic, to get bunch of dates that fall between dates.
trying doing this in python import sys !conda install --yes --prefix {sys.prefix} graphviz import graphviz
Short answer, yes, sort of. You can use Objective-C++, which you can read about at Apple Developer Connection.
If you know C++ already, learning Objective-C would be pretty simple, if you decided to give that a try. More info on that topic is at the ADC as well.
Your best bet is to throw
an Error
wrapping the value, which results in a rejected promise with an Error
wrapping the value:
} catch (error) {
throw new Error(400);
}
You can also just throw
the value, but then there's no stack trace information:
} catch (error) {
throw 400;
}
Alternately, return a rejected promise with an Error
wrapping the value, but it's not idiomatic:
} catch (error) {
return Promise.reject(new Error(400));
}
(Or just return Promise.reject(400);
, but again, then there's no context information.)
In your case, as you're using TypeScript
and foo
's return value is Promise<A>
, you'd use this:
return Promise.reject<A>(400 /*or Error*/ );
In an async
/await
situation, that last is probably a bit of a semantic mis-match, but it does work.
If you throw an Error
, that plays well with anything consuming your foo
's result with await
syntax:
try {
await foo();
} catch (error) {
// Here, `error` would be an `Error` (with stack trace, etc.).
// Whereas if you used `throw 400`, it would just be `400`.
}
Stumbled onto this, was strangely hard to find again later. Putting here for posterity:
sudo yum install nodejs npm --enablerepo=epel
EDIT 3: As of July 2016, EDIT 1 no longer works for nodejs 4 (and EDIT 2 neither). This answer (https://stackoverflow.com/a/35165401/78935) gives a true one-liner.
EDIT 1: If you're looking for nodejs 4, please try the EPEL testing repo:
sudo yum install nodejs --enablerepo=epel-testing
EDIT 2: To upgrade from nodejs 0.12 installed through the EPEL repo using the command above, to nodejs 4 from the EPEL testing repo, please follow these steps:
sudo yum rm nodejs
sudo rm -f /usr/local/bin/node
sudo yum install nodejs --enablerepo=epel-testing
The newer packages put the node binaries in /usr/bin
, instead of /usr/local/bin
.
And some background:
The option --enablerepo=epel
causes yum
to search for the packages in the EPEL repository.
EPEL (Extra Packages for Enterprise Linux) is open source and free community based repository project from Fedora team which provides 100% high quality add-on software packages for Linux distribution including RHEL (Red Hat Enterprise Linux), CentOS, and Scientific Linux. Epel project is not a part of RHEL/Cent OS but it is designed for major Linux distributions by providing lots of open source packages like networking, sys admin, programming, monitoring and so on. Most of the epel packages are maintained by Fedora repo.
Via http://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/
html, body {
height:100%;
}
#wrapper {
min-height:100%;
}
Below is the work around to submit Multi values, in case of converting the application from ASP to PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
var Arr_Elements = [];
Arr_Elements = document.getElementsByClassName("MultiElements");
for(var i=0; i<Arr_Elements.length; i++) {
Arr_Elements[i].value = '';
var Element_Name = Arr_Elements[i].name;
var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
var Multi_Elements = [];
Multi_Elements = document.getElementsByName(Element_Name);
var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
if (Main_Element_Type == "CheckBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements[j].checked == true) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
if (Multi_Elements[j].value != '') {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
Arr_Elements[i].value = Multi_Elements_Values;
}
}
</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
<table>
<tr>
<td>Check Box</td>
<td>
<input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
</td>
<td>
<input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
<input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
<input type="hidden" name="SdPart" id="SdPart" value="3451"></input>
<input type="textbox" name="Test11" id="Test11" value="345111"></input>
<!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc
-->
<input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
</td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
testCB.php
<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>
if your input's id is following
<input type='text' id='kg_row1' >
then you can get explode/split the above with the following function of split in jquery
var kg_id = $(this).attr("id");
var getvalues =kg_id.split("_");
var id = getvalues[1];
You will get like this error
Try the following steps
1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter)
Then type this command as show in picture
netstat -aon | find ":8080" | find "LISTENING"
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
There are several ways to do this:
A simple way is using the os module:
import os
os.system("ls -l")
More complex things can be achieved with the subprocess module: for example:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
Let's start with a basic function which we will be pointing to:
int addInt(int n, int m) {
return n+m;
}
First thing, let's define a pointer to a function which receives 2 int
s and returns an int
:
int (*functionPtr)(int,int);
Now we can safely point to our function:
functionPtr = &addInt;
Now that we have a pointer to the function, let's use it:
int sum = (*functionPtr)(2, 3); // sum == 5
Passing the pointer to another function is basically the same:
int add2to3(int (*functionPtr)(int, int)) {
return (*functionPtr)(2, 3);
}
We can use function pointers in return values as well (try to keep up, it gets messy):
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
But it's much nicer to use a typedef
:
typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef
myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}
This is actually the conventional use of the break
statement. If the break
statement wasn't nested in an if
block the for
loop could only ever execute one time.
MSDN lists this as their example for the break
statement.
This matches a word from any length:
var phrase = "an important number comes after this: 123456";
var word = "this: ";
var number = phrase.substr(phrase.indexOf(word) + word.length);
// number = 123456
In your .m file, declare a file global variable:
static int currentID = 1;
then in your init routine, refernce that:
- (id) init
{
self = [super init];
if (self != nil) {
_myID = currentID++; // not thread safe
}
return self;
}
or if it needs to change at some other time (eg in your openConnection method), then increment it there. Remember it is not thread safe as is, you'll need to do syncronization (or better yet, use an atomic add) if there may be any threading issues.
The best option is probably to use a lambda expression that closes over the variables you want to display.
However, be careful in this case, especially if you're calling this in a loop. (I mention this since your variable is an "ID", and this is common in this situation.) If you close over the variable in the wrong scope, you can get a bug. For details, see Eric Lippert's post on the subject. This typically requires making a temporary:
foreach(int id in myIdsToCheck)
{
int tempId = id; // Make a temporary here!
Task.Factory.StartNew( () => CheckFiles(tempId, theBlockingCollection),
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
Also, if your code is like the above, you should be careful with using the LongRunning
hint - with the default scheduler, this causes each task to get its own dedicated thread instead of using the ThreadPool. If you're creating many tasks, this is likely to have a negative impact as you won't get the advantages of the ThreadPool. It's typically geared for a single, long running task (hence its name), not something that would be implemented to work on an item of a collection, etc.
Single quotes are characters (char
), double quotes are null-terminated strings (char *
).
char c = 'x';
char *s = "Hello World";
Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.
After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.
I actually discovered something recently that seems to work for styling individual <option></option>
elements within Chrome, Firefox, and IE using pure CSS.
Maybe, try the following:
HTML:
<select>
<option value="blank">Blank</option>
<option class="white" value="white">White</option>
<option class="red" value="red">Red</option>
<option class="blue" value="blue">Blue</option>
</select>
CSS:
select {
background-color:#000;
color: #FFF;
}
select * {
background-color:#000;
color:#FFF;
}
select *.red { /* This, miraculously, styles the '<option class="red"></option>' elements. */
background-color:#F00;
color:#FFF;
}
select *.white {
background-color:#FFF;
color:#000;
}
select *.blue {
background-color:#06F;
color:#FFF;
}
Strange what throwing caution to the wind does. It doesn't seem to support the :active :hover :focus :link :visited :after :before
, though.
Example on JSFiddle: http://jsfiddle.net/Xd7TJ/2/
You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.
http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters
Rough, untested code follows:
appModule.filter('checked', function() {
return function(input, checked) {
if(!input)return input;
var output = []
for (i in input){
var item = input[i];
if(item.checked == checked)output.push(item);
}
return output
}
});
and the view (i added an "uncheck" button too)
<div id="AddItem">
<h3>Add Item</h3>
<input value="1" type="number" placeholder="1" ng-model="itemAmount">
<input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br/>
<button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
<h3>Checked Items: {{getTotalCheckedItems()}}</h3>
<h4>Checked:</h4>
<table>
<tr ng-repeat="item in items | checked:true" class="item-checked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<i>this item is checked!</i>
<button ng-click="item.checked = false">uncheck item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
<h3>Unchecked Items: {{getTotalItems()}}</h3>
<h4>Unchecked:</h4>
<table>
<tr ng-repeat="item in items | checked:false" class="item-unchecked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<button ng-click="item.checked = true">check item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF ITEMS -->
Then you dont need the toggle methods etc in your controller
I had the same question for macOS.
But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew
.
I fixed my issue with: $ brew uninstall python@2
Some context on here: https://bugs.swift.org/browse/SR-1061
jQuery("#my_image").attr("src", "first.jpg")
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
You need to use an external service... such as http://www.hostip.info/ if you google search for "geo-ip" you can get more results.
The Host-IP API is HTTP based so you can use it either in PHP or JavaScript depending on your needs.
Had the same issue with arrays, here is how to do it if you're manipulating arrays too :
array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")
ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"
This will output :
ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
Indeed you can access the information from the session even when the session is being destroyed on an HttpSessionLisener by doing:
public void sessionDestroyed(HttpSessionEvent hse) {
SecurityContextImpl sci = (SecurityContextImpl) hse.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
// be sure to check is not null since for users who just get into the home page but never get authenticated it will be
if (sci != null) {
UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
// do whatever you need here with the UserDetails
}
}
or you could also access the information anywhere you have the HttpSession object available like:
SecurityContextImpl sci = (SecurityContextImpl) session().getAttribute("SPRING_SECURITY_CONTEXT");
the last assuming you have something like:
HttpSession sesssion = ...; // can come from request.getSession(false);
I struggled with all the answers here, starting with Pascal's solution, which is getting harder with the Java compiler not binding against rt.jar
by default any more (and using internal classes makes it specific to that runtime implementation).
The answer from edubriguenti brought me close. The way the handler is hooked up in the final bit of code didn't work for me, though - it was never called.
I ended up using a variation of his handler class, but wired it into the javax.xml.ws.Service
instance like this:
Service service = Service.create(url, qname);
service.setHandlerResolver(
portInfo -> Collections.singletonList(new SOAPHeaderHandler(handlerArgs))
);
String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();
Now to convert character array into String , there are two ways.
Arrays.toString(c);
Returns the string [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]
.
And:
String.valueOf(c)
Returns the string wwwwww3333dfevvv
.
In Summary: pay attention to Arrays.toString(c)
, because you'll get "[w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]"
instead of "wwwwww3333dfevvv"
.
Add to the main __init__.py
in YourClassParentDir, e.g.:
from .YourClass import YourClass
Then, you will have an instance of your class ready when you import it into another script:
from YourClassParentDir import YourClass
You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
componentDidUpdate(prevProps){
if (this.state.authToken==null&&prevProps.authToken==null) {
AccountKit.getCurrentAccessToken()
.then(token => {
if (token) {
AccountKit.getCurrentAccount().then(account => {
this.setState({
authToken: token,
loggedAccount: account
});
});
} else {
console.log("No user account logged");
}
})
.catch(e => console.log("Failed to get current access token", e));
}
}
Use a lambda expression
MyClass result = list.Find(x => x.GetId() == "xy");
Note: C# has a built-in syntax for properties. Instead of writing getter and setter methods (as you might be used to from Java), write
private string _id;
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
value
is a contextual keyword known only in the set accessor. It represents the value assigned to the property.
Since this pattern is often used, C# provides auto-implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).
public string Id { get; set; }
You can simply use properties as if you were accessing a field:
var obj = new MyClass();
obj.Id = "xy"; // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id; // Calls the getter.
Using properties, you would search for items in the list like this
MyClass result = list.Find(x => x.Id == "xy");
You can also use auto-implemented properties if you need a read-only property:
public string Id { get; private set; }
This enables you to set the Id
within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter
public string Id { get; protected set; }
And finally, you can declare properties as virtual
and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.
Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer
public string Id { get; } = "A07"; // Evaluated once when object is initialized.
You can also initialize getter-only properties within the constructor instead. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.
This works also with read-write auto-properties:
public string Id { get; set; } = "A07";
Beginning with C# 6.0 you can also write properties as expression-bodied members
public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }
See: .NET Compiler Platform ("Roslyn")
New Language Features in C# 6
Starting with C# 7.0, both, getter and setter, can be written with expression bodies:
public string Name
{
get => _name; // getter
set => _name = value; // setter
}
Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0
is equivalent to x = (y = (z = 0))
and has the same effect as the statements x = 0; y = 0; z = 0;
.
The next version of the language, C# 9.0, probably available in November 2020, will allow read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.
public string Name { get; init; }
var c = new C { Name = "c-sharp" };
Exists = IsObject(CurrentDb.TableDefs(tablename))
You can save a string raw as is by using FileReader.
Save the string in a blob and call readAsArrayBuffer(). Then the onload-event results an arraybuffer, which can converted in a Uint8Array. Unfortunately this call is asynchronous.
This little function will help you:
function stringToBytes(str)
{
let reader = new FileReader();
let done = () => {};
reader.onload = event =>
{
done(new Uint8Array(event.target.result), str);
};
reader.readAsArrayBuffer(new Blob([str], { type: "application/octet-stream" }));
return { done: callback => { done = callback; } };
}
Call it like this:
stringToBytes("\u{1f4a9}").done(bytes =>
{
console.log(bytes);
});
output: [240, 159, 146, 169]
explanation:
JavaScript use UTF-16 and surrogate-pairs to store unicode characters in memory. To save unicode character in raw binary byte streams an encoding is necessary. Usually and in the most case, UTF-8 is used for this. If you not use an enconding you can't save unicode character, just ASCII up to 0x7f.
FileReader.readAsArrayBuffer() uses UTF-8.
Although there are some useful algorithmic explanations here, I think it may help to add some simple 'real life' reasoning as to why it works this way, which I have found useful when introducing the subject to young newcomers:
With something like 'range(1,10)' confusion can arise from thinking that pair of parameters represents the "start and end".
It is actually start and "stop".
Now, if it were the "end" value then, yes, you might expect that number would be included as the final entry in the sequence. But it is not the "end".
Others mistakenly call that parameter "count" because if you only ever use 'range(n)' then it does, of course, iterate 'n' times. This logic breaks down when you add the start parameter.
So the key point is to remember its name: "stop". That means it is the point at which, when reached, iteration will stop immediately. Not after that point.
So, while "start" does indeed represent the first value to be included, on reaching the "stop" value it 'breaks' rather than continuing to process 'that one as well' before stopping.
One analogy that I have used in explaining this to kids is that, ironically, it is better behaved than kids! It doesn't stop after it supposed to - it stops immediately without finishing what it was doing. (They get this ;) )
Another analogy - when you drive a car you don't pass a stop/yield/'give way' sign and end up with it sitting somewhere next to, or behind, your car. Technically you still haven't reached it when you do stop. It is not included in the 'things you passed on your journey'.
I hope some of that helps in explaining to Pythonitos/Pythonitas!
Voilà:
body {
background-color: #000; /*Default bg, similar to the background's base color*/
background-image: url("bg.png");
background-position: right bottom; /*Positioning*/
background-repeat: no-repeat; /*Prevent showing multiple background images*/
}
The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position
I tried what kohske wrote as an answer and I got error again, so I did some search and found this which worked for me (R 3.0.2):
require(splines) # package
detach(package:splines)
or also
library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)
I experienced this when I updated my JDK manually and removed the previous JDK
Integer
for example) and press ALT + ENTER (or click the light bulb icon)Configure
/opt/jdk1.7.0_51
instead of /opt/jdk1.7.0_65
)And everything should be back to life :)
# Unordered list
* Item 1
* Item 2
* Item 3
* Item 3a
* Item 3b
* Item 3c
# Ordered list
1. Step 1
2. Step 2
3. Step 3
1. Step 3.1
2. Step 3.2
3. Step 3.3
# List in list
1. Step 1
2. Step 2
3. Step 3
* Item 3a
* Item 3b
* Item 3c
Here's a screenshot from that updated repo:
Example in Swift:
import UIKit
class ViewController: UIViewController {
@IBOutlet var myUIImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func myAction(sender: UIButton) {
let newImg: UIImage? = UIImage(named: "profile-picture-name")
self.myUIImageView.image = newImg
}
@IBAction func myAction2(sender: UIButton) {
self.myUIImageView.image = nil
self.myUIImageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://url/image.png")!)!)
}
}
In the case of trying to install a command line application as a Windows service try the 'NSSM' utility. Related ServerFault details found here.
You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float
The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.
eg.
<div class="c">
<div class="l">
</div>
<div class="m">
World
</div>
<div style="clear: both" />
</div>
You can try the following :
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowFullscreen">true</item>
</style>
The accepted answer may be the best and most stable way to get a version number into an application statically, but does not actually answer the original question: How to retrieve the artifact's version number from pom.xml? Thus, I want to offer an alternative showing how to do it dynamically during runtime:
You can use Maven itself. To be more exact, you can use a Maven library.
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.3.9</version>
</dependency>
And then do something like this in Java:
package de.scrum_master.app;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.FileReader;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader("pom.xml"));
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
}
}
The console log is as follows:
de.scrum-master.stackoverflow:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.stackoverflow
my-artifact
1.0-SNAPSHOT
Update 2017-10-31: In order to answer Simon Sobisch's follow-up question I modified the example like this:
package de.scrum_master.app;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Application {
public static void main(String[] args) throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
if ((new File("pom.xml")).exists())
model = reader.read(new FileReader("pom.xml"));
else
model = reader.read(
new InputStreamReader(
Application.class.getResourceAsStream(
"/META-INF/maven/de.scrum-master.stackoverflow/aspectj-introduce-method/pom.xml"
)
)
);
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
}
}
This is a bit of a pain on Windows. Here's what I do.
Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11
, then let the installer install public JRE in the default place (c:\program files\blah
). This will setup your default JRE for the majority of things.
Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18
, but don't install the public JREs.
When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED
and then set PATH=%JAVA_HOME%\bin;%PATH%
. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME
variable.
The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe
, which usually overrides most other settings.
Janky at best
<a href="file://///server/folders/x/x/filename.ext">right click </a></td>
and then right click, select "copy location" option, and then paste into url.
If you are using the GUI to do this you must deselect the following option allowing the table to be dropped,
Prior Swift 3.0 :
String(data: yourData, encoding: NSUTF8StringEncoding)
For Swift 4.0:
String(data: yourData, encoding: .utf8)
In php.ini :
extension_dir ="c:/wamp64/bin/php/php7.4.9/ext/"
Make sure the PHP version is correct.
There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody
javadocs, @ResponseBody
javadocs
Usage examples would be something like this:
Using a JavaScript-library like JQuery, you would post a JSON-Object like this:
{ "firstName" : "Elmer", "lastName" : "Fudd" }
Your controller method would look like this:
// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}
// domain / value objects
public class UserStats{
private String firstName;
private String lastName;
// + getters, setters
}
public class Description{
private String description;
// + getters, setters, constructor
}
Now if you have Jackson on your classpath (and have an <mvc:annotation-driven>
setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody
annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody
annotation). So the Browser / Client would see this JSON result:
{ "description" : "Elmer Fudd hates wacky wabbits" }
See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852
Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.
Ever since Spring 4.x, you usually won't use @ResponseBody
on method level, but rather @RestController
on class level, with the same effect.
Here is a quote from the official Spring MVC documentation:
@RestController
is a composed annotation that is itself meta-annotated with@Controller
and@ResponseBody
to indicate a controller whose every method inherits the type-level@ResponseBody
annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
In HTML5 better use this:
{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}
This is how I would do it, in order to get in the var4 restriction:
dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )
Rgds, Rainer
There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.
Using tr command:
tr '\n' ',' < somefile
Using awk:
awk -F'\n' '{if(NR == 1) {printf $0} else {printf ","$0}}' somefile
If you are using a simulator in Android Studio on Mac you can go to View -> Tool Windows -> Device File Explorer
. Here you can use a finder-like structure.
This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.
plt.colorbar(im,fraction=0.046, pad=0.04)
It also does not require sharing the axis which can get the plot out of square.
CSV Export does not escape your data. Watch out for strings which end in \
because the resulting \"
will look like an escaped "
and not a \
. Then you have the wrong number of "
and your entire row is broken.
Use mysqladmin
to kill the runaway query:
Run the following commands:
mysqladmin -uusername -ppassword pr
Then note down the process id.
mysqladmin -uusername -ppassword kill pid
The runaway query should no longer be consuming resources.
Adding this since this was not mentioned.
SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');
Because that's what actually works for me. Adding date() function on both comparison values.
Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.
When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)
Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.
Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.
AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)
I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.
Installing Guzzle
Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.
php composer.phar require guzzlehttp/guzzle
Using Guzzle to send a POST request
The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:
// Initialize Guzzle client
$client = new GuzzleHttp\Client();
// Create a POST request
$response = $client->request(
'POST',
'http://example.org/',
[
'form_params' => [
'key1' => 'value1',
'key2' => 'value2'
]
]
);
// Parse the response object, e.g. read the headers, body, etc.
$headers = $response->getHeaders();
$body = $response->getBody();
// Output headers and body for debugging purposes
var_dump($headers, $body);
with DataFrame: df_data
>>> df_data
id name value
0 a ampha 1
1 b beta 2
2 c ce 3
I tried:
>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True
but:
>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False
So fun :D
try this
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
}
</script>
foreach(DataRow row in dataTable.Rows)
{
if(row.IsNull("myColumn"))
throw new Exception("Empty value!")
}
Add -m to the recommended answer above to prune empty directories.
SELECT t1.col table1col, t2.col table2col
FROM table1 t1
JOIN table2 t2 on t1.table1Id = x and t2.table2Id = y
If you will try to load such a large file through phpmyadmin then you would need to change upload_file_size in php.ini to your requirements and then after uploading you will have to revert it back. What will happen? If you would like to load a 3GB file. You will have to change those parameters in php.ini again.
The best solution to solve this issue to open command prompt in windows.
Find path of wamp mysql directory.
Usually, it is C:/wamp64/bin/mysql/mysqlversion/bin/mysql.exe
Execute mysql -u root
You will be in mysql command prompt
Switch database with use command.
mysql> use database_name
mysql> source [file_path]
In case of Windows, here is the example.
mysql> source C:/sqls/sql1GB.sql
That's it. If you will have a database over 10GB or 1000GB. This method will still work for you.
An round button with box-shadow https://v2.vuetifyjs.com/en/components/floating-action-buttons/
.btn {
height: 50px;
width: 50px;
line-height: 50px;
font-size: 2em;
border-radius: 50%;
background-color: red;
color: white;
text-align: center;
border: none;
cursor: pointer;
position: fixed;
z-index: 1;
bottom: 10%;
right: 4%;
box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2), 0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12);
}
_x000D_
<div class="btn">+</div>
_x000D_
Check if you are able to connect to eclipse market place url (http://marketplace.eclipse.org/) from browser. If its working then the issue is because of proxy server using in your network. We have to update eclipse with proxy server details used in our network.
Go to :- Windows-> Preference -> General -> Network Connections.
And edit HTTP ,with proxy details.
Click OK
Done.
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
,?\s*'.+?'|,?\s*".+?"|[^"']+?(?=,)|[^"']+
This regex works with single and double quotes and also for one quote inside another!
For mysqlnd only:
mysqli_options($conn, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
Otherwise:
$row = $result->fetch_assoc();
while ($field = $result->fetch_field()) {
switch (true) {
case (preg_match('#^(float|double|decimal)#', $field->type)):
$row[$field->name] = (float)$row[$field->name];
break;
case (preg_match('#^(bit|(tiny|small|medium|big)?int)#', $field->type)):
$row[$field->name] = (int)$row[$field->name];
break;
}
}
void QWidget::setWindowTitle ( const QString & )
EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.
There are many good answers here, but none mentiones that there are highly optimized implementations of the Collection API classes/interfaces specifically for enums:
These enum specific classes only accept Enum
instances (the EnumMap
only accept Enum
s only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.
What does this mean?
If our Enum
type has no more that 64 elements (most of real-life Enum
examples will qualify for this), the implementations store the elements in a single long
value, each Enum
instance in question will be associated with a bit of this 64-bit long long
. Adding an element to an EnumSet
is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the Set
is just one bitmask test! Now you gotta love Enum
s for this!
You should use this:
<Link to={this.props.myroute} onClick={hello}>Here</Link>
Or (if method hello
lays at this class):
<Link to={this.props.myroute} onClick={this.hello}>Here</Link>
Update: For ES6 and latest if you want to bind some param with click method, you can use this:
const someValue = 'some';
....
<Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>
dir, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
this is for golang version: go version go1.13.7 linux/amd64
works for me, for go run main.go
. If I run go build -o fileName
, and put the final executable in some other folder, then that path is given while running the executable.
If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::ostreambuf_iterator<char>(output));
}
If you need that data in a buffer to modify it or something, do this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
// copies all data into buffer
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
}
Following rajibchowdhury's answer (upvoted), use git rm
command which is advised is for removing the special entry in the index indicating a submodule (a 'folder' with a special mode 160000
).
If that special entry path isn't referenced in the .gitmodule
(like 'Classes/Support/Three20
' in the original question), then you need to remove it, in order to avoid the "No submodule mapping found in .gitmodules
for path" error message.
You can check all the entries in the index which are referencing submodules:
git ls-files --stage | grep 160000
Previous answer (November 2010)
It is possible that you haven't declared your initial submodule correctly (i.e. without any tail '/' at the end, as described in my old answer, even though your .gitmodule
has paths which looks ok in it).
This thread mentions:
do you get the same error when running 'git submodule init' from a fresh clone?
If so, you have something wrong.If you have no submodules, delete
.gitmodules
, and any references to submodules in .git/config, and ensure the Pikimal dir does not have a.git
dir in it.
If that fixes the problem, check in and do the same on your cruise working copy.
Obviously, don't delete your main .gitmodules
file, but look after other extra .gitmodules
files in your working tree.
Still in the topic of "incorrect submodule initialization", Jefromi mentions submodules which actually are gitlinks.
See How to track untracked content? in order to convert such a directory to a real submodule.
References are not pointers.
8.3.2/1:
A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
1.9/4:
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)
As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.
It's called dependency injection via constructor injection: class A
gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.
There's an interesting introduction on wikipedia.
For const-correctness I'd write:
using T = int;
class A
{
public:
A(const T &thing) : m_thing(thing) {}
// ...
private:
const T &m_thing;
};
but a problem with this class is that it accepts references to temporary objects:
T t;
A a1{t}; // this is ok, but...
A a2{T()}; // ... this is BAD.
It's better to add (requires C++11 at least):
class A
{
public:
A(const T &thing) : m_thing(thing) {}
A(const T &&) = delete; // prevents rvalue binding
// ...
private:
const T &m_thing;
};
Anyway if you change the constructor:
class A
{
public:
A(const T *thing) : m_thing(*thing) { assert(thing); }
// ...
private:
const T &m_thing;
};
it's pretty much guaranteed that you won't have a pointer to a temporary.
Also, since the constructor takes a pointer, it's clearer to users of A
that they need to pay attention to the lifetime of the object they pass.
Somewhat related topics are:
To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.
void main(void){
int* test;
test = tester();
printf("%d",*test);
system("pause");
return;
}
int* tester(void){
int *retMe;
retMe = new int;//<----Here retMe is getting malloc for integer type
*retMe = 12;<---- Initializes retMe... Note * dereferences retMe
return retMe;
}
To check mongodb version use the mongod command with --version
option.
To check MongoDB Server version, Open the command line via your terminal program and execute the following command:
Path :
C:\Program Files\MongoDB\Server\3.2\bin
Open Cmd and
execute the following command:
mongod --version
To Check MongoDB Shell version, Type:
mongo --version
Try this. It is working and tested.
for k in "${array[@]}"
do
echo $k
done
# For accessing with the echo command: echo ${array[0]}, ${array[1]}
Here you will find a better solution OLTP vs. OLAP
OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.
OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.
This will do it:
[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
//Your code goes in here
NSLog(@"Main Thread Code");
}];
Hope this helps!
For what it's worth, I do this:
<!-- Favicon - Generic -->
<link rel="icon" href="path/favicon-32_x_32.png" sizes="32x32">
<link rel="icon" href="path/favicon-57_x_57.png" sizes="57x57">
<link rel="icon" href="path/favicon-76_x_76.png" sizes="76x76">
<link rel="icon" href="path/favicon-96_x_96.png" sizes="96x96">
<link rel="icon" href="path/favicon-128_x_128.png" sizes="128x128">
<link rel="icon" href="path/favicon-192_x_192.png" sizes="192x192">
<link rel="icon" href="path/favicon-228_x_228.png" sizes="228x228">
<!-- Favicon - Android -->
<link rel="shortcut icon" href="path/favicon-196_x_196.png" sizes="196x196">
<!-- Favicon - iOS -->
<link rel="apple-touch-icon" href="path/favicon-120_x_120.png" sizes="120x120">
<link rel="apple-touch-icon" href="path/favicon-152_x_152.png" sizes="152x152">
<link rel="apple-touch-icon" href="path/favicon-180_x_180.png" sizes="180x180">
And I still keep the favicon.ico in root.
Needs ensure library but you can compare list by:
ensure([1, 2]).contains_only([2, 1])
This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github
Override windowClosing Method.
public void windowClosing(WindowEvent e)
It is invoked when a window is in the process of being closed. The close operation can be overridden at this point.
$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
// If this is your connection then you have to assign null
// to your connection variable as follows:
$conn=null;
// By this way you can close connection in PDO.
Remove the appropriate entr(y|ies) under HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\Repositories
.
Remove HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\General\LastUsedRepository
if it's the same as the repo you are trying to remove.
It seems like Visual Studio tracks all of the git repositories that it has seen. Even if you close the project that was referencing a repository, old entries may still appear in the list.
This problem is not new to Visual Studio:
Remove Git binding from Visual Studio 2013 solution?
This all seems like a lot of work for something that should probably be a built-in feature. The above "solutions" mention making modifications to the .git file etc.; I don't like the idea of having to change things outside of Visual Studio to affect things inside Visual Studio. Although my solution needs to make a few registry edits (and is external to VS), at least these only affect VS. Here is the work-around (read: hack):
Be sure to have Visual Studio 2015 closed before following these steps.
1. Open regedit.exe and navigate to
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\Repositories
You might see multiple "hash" values that represent the repositories that VS is tracking.
2. Find the git repository you want to remove from the list. Look at the name
and path
values to verify the correct repository to delete:
3. Delete the key (and corresponding subkeys).
(Optional: before deleting, you can right click and choose Export to back up this key in case you make a mistake.) Now, right click on the key (in my case this is AE76C67B6CD2C04395248BFF8EBF96C7AFA15AA9
and select Delete).
4. Check that the LastUsedRepository
key points to "something else."
If the repository mapping you are trying to remove in the above steps is stored in LastUsedRepository
, then you'll need to remove this key, also. First navigate to:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\General
and delete the key LastUsedRepository
(the key will be re-created by VS if needed). If you are worried about removing the key, you can just modify the value and set it to an empty string:
When you open Visual Studio 2015 again, the git repository binding should not appear in the list anymore.
The example from jQuery's website animates size AND font but you could easily modify it to fit your needs
$("#go").click(function(){
$("#block").animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
I would recommend this article on how to do bulk inserts using EF.
Entity Framework and slow bulk INSERTs
He explores these areas and compares perfomance:
How about this?
LinkedHashSet<Integer> test = new LinkedHashSet<Integer>();
Random random = new Random();
do{
test.add(random.nextInt(1000) + 1);
}while(test.size() != 1000);
The user can then iterate through the Set
using a for loop.
prepend
parent.prepend(newChild) // [newChild, child1, child2]
This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.
The equivalent for adding to the end is append
, replacing the old appendChild
parent.append(newChild) // [child1, child2, newChild]
...
).Examples:
parent.prepend(newChild, "foo") // [newChild, "foo", child1, child2]
const list = ["bar", newChild]
parent.append(...list, "fizz") // [child1, child2, "bar", newChild, "fizz"]
Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";
int main()
{
size_t wcsChars = wcslen( wcsString);
size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Wide chars in wcsString: %u\n", wcsChars);
printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
}
And the output:
Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18
I wrote a dom adapter for my jackson based json processing framework long time ago. It uses the nu.xom library. The resulting dom tree works with the java xpath and xslt facilities. I made some implementation choices that are pretty straightforward. For example the root node is always called "root", arrays go into an ol node with li sub elements (like in html), and everything else is just a sub node with a primitive value or another object node.
Usage:
JsonObject sampleJson = sampleJson();
org.w3c.dom.Document domNode = JsonXmlConverter.getW3cDocument(sampleJson, "root");
overflow-x: auto;
overflow-y : hidden;
Apply the styling above to the parent div.
Since expression is boolean:
return expression;
I know maybe it is unnecessary, but I made a function which converts float to string:
#include <stdio.h>
/** Number on countu **/
int n_tu(int number, int count)
{
int result = 1;
while(count-- > 0)
result *= number;
return result;
}
/*** Convert float to string ***/
void float_to_string(float f, char r[])
{
long long int length, length2, i, number, position, sign;
float number2;
sign = -1; // -1 == positive number
if (f < 0)
{
sign = '-';
f *= -1;
}
number2 = f;
number = f;
length = 0; // Size of decimal part
length2 = 0; // Size of tenth
/* Calculate length2 tenth part */
while( (number2 - (float)number) != 0.0 && !((number2 - (float)number) < 0.0) )
{
number2 = f * (n_tu(10.0, length2 + 1));
number = number2;
length2++;
}
/* Calculate length decimal part */
for (length = (f > 1) ? 0 : 1; f > 1; length++)
f /= 10;
position = length;
length = length + 1 + length2;
number = number2;
if (sign == '-')
{
length++;
position++;
}
for (i = length; i >= 0 ; i--)
{
if (i == (length))
r[i] = '\0';
else if(i == (position))
r[i] = '.';
else if(sign == '-' && i == 0)
r[i] = '-';
else
{
r[i] = (number % 10) + '0';
number /=10;
}
}
}
<label>
for the caption<form enctype='multipart/form-data' action='/uploads.php' method=post>
<label for=b1>
<u>Your</u> caption here
<input style='width:0px' type=file name=upfile id=b1
onchange='optionalExtraProcessing(b1.files[0])'
accept='image/png'>
</label>
</form>
This works without any javascript. You can decorate the label to any degree of complexity, to your heart's content. When you click on the label, the click automatically gets redirected to the file input. The file input itself can be made invisible by any method. If you want the label to appear like a button, there are many solutions, e.g.:
label u {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
class Node:
"""
Class Node
"""
def __init__(self, value):
self.left = None
self.data = value
self.right = None
class Tree:
"""
Class tree will provide a tree as well as utility functions.
"""
def createNode(self, data):
"""
Utility function to create a node.
"""
return Node(data)
def insert(self, node , data):
"""
Insert function will insert a node into tree.
Duplicate keys are not allowed.
"""
#if tree is empty , return a root node
if node is None:
return self.createNode(data)
# if data is smaller than parent , insert it into left side
if data < node.data:
node.left = self.insert(node.left, data)
elif data > node.data:
node.right = self.insert(node.right, data)
return node
def search(self, node, data):
"""
Search function will search a node into tree.
"""
# if root is None or root is the search data.
if node is None or node.data == data:
return node
if node.data < data:
return self.search(node.right, data)
else:
return self.search(node.left, data)
def deleteNode(self,node,data):
"""
Delete function will delete a node into tree.
Not complete , may need some more scenarion that we can handle
Now it is handling only leaf.
"""
# Check if tree is empty.
if node is None:
return None
# searching key into BST.
if data < node.data:
node.left = self.deleteNode(node.left, data)
elif data > node.data:
node.right = self.deleteNode(node.right, data)
else: # reach to the node that need to delete from BST.
if node.left is None and node.right is None:
del node
if node.left == None:
temp = node.right
del node
return temp
elif node.right == None:
temp = node.left
del node
return temp
return node
def traverseInorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
self.traverseInorder(root.left)
print(root.data)
self.traverseInorder(root.right)
def traversePreorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
print(root.data)
self.traversePreorder(root.left)
self.traversePreorder(root.right)
def traversePostorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
self.traversePostorder(root.left)
self.traversePostorder(root.right)
print(root.data)
def main():
root = None
tree = Tree()
root = tree.insert(root, 10)
print(root)
tree.insert(root, 20)
tree.insert(root, 30)
tree.insert(root, 40)
tree.insert(root, 70)
tree.insert(root, 60)
tree.insert(root, 80)
print("Traverse Inorder")
tree.traverseInorder(root)
print("Traverse Preorder")
tree.traversePreorder(root)
print("Traverse Postorder")
tree.traversePostorder(root)
if __name__ == "__main__":
main()
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
Yes it can, abstract classes constructors are generally used for super calls for initialization events common to all the subclasses
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("jdbc:oracle:thin:@machinename:portnum:schemaname","userid","password");
I have made a node module to read large file asynchronously text or JSON. Tested on large files.
var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');
module.exports = FileReader;
function FileReader(){
}
FileReader.prototype.read = function(pathToFile, callback){
var returnTxt = '';
var s = fs.createReadStream(pathToFile)
.pipe(es.split())
.pipe(es.mapSync(function(line){
// pause the readstream
s.pause();
//console.log('reading line: '+line);
returnTxt += line;
// resume the readstream, possibly from a callback
s.resume();
})
.on('error', function(){
console.log('Error while reading file.');
})
.on('end', function(){
console.log('Read entire file.');
callback(returnTxt);
})
);
};
FileReader.prototype.readJSON = function(pathToFile, callback){
try{
this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
}
catch(err){
throw new Error('json file is not valid! '+err.stack);
}
};
Just save the file as file-reader.js, and use it like this:
var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});
It happens when your HTTP request's headers claim that the content is gzip encoded, but it isn't. Turn off gzip encoding setting or make sure the content is in fact encoded.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
you have error in your sql syntax.
please use this query and checkout.
$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");
If you have access to ECMA 5 you can use the some method.
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
TLDR: ssh-add ~/.ssh/yourkey
I've just worked through this problem.
And none of the other answers helped.
I did have a ./ssh/config with all the right stuff, also an earlier repository working fine (same bitbucket account, same key). Then I generated a deploy_key, and after that created a new repository.
After that could not clone the new repo.
I wish I knew how/why ssh agent was messing this up, but adding the key solved it. I mean adding the key in my local Ubuntu, not in bitbucket admin. The command is just
~/.ssh$ ssh-add myregualrkey
Hope this helps someone.
If you are on an AWS EC2 instance running an Ubuntu instance (tested on Ubuntu 16.x), then these steps might work for you:
sudo apt-get update sudo apt-get --purge remove node -y sudo apt-get --purge remove nodejs -y sudo apt-get --purge remove legacy-node -y sudo rm /usr/bin/node curl -sL https://deb.nodesource.com/setup_6.x | sudo bash - sudo apt-get install nodejs -y node -v
If all is correct the last command shall have an output like : v6.x.x
If not then run the following:
sudo ln -s /usr/bin/nodejs /usr/bin/node
Hopefully this will help. It helped me magically (hehe).
Several methods are covered in
"51} How can I echo lines in different colors in NT scripts?"
http://www.netikka.net/tsneti/info/tscmd051.htm
One of the alternatives: If you can get hold of QBASIC, using colors is relatively easy:
@echo off & setlocal enableextensions
for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
set skip=
findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
qbasic /run %temp_%\tmp$$$.bas
for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
endlocal & goto :EOF
::
CLS 'QB
COLOR 14,0 'QB
PRINT "A simple "; 'QB
COLOR 13,0 'QB
PRINT "color "; 'QB
COLOR 14,0 'QB
PRINT "demonstration" 'QB
PRINT "By Prof. (emer.) Timo Salmi" 'QB
PRINT 'QB
FOR j = 0 TO 7 'QB
FOR i = 0 TO 15 'QB
COLOR i, j 'QB
PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
COLOR 1, 0 'QB
PRINT " "; 'QB
NEXT i 'QB
PRINT 'QB
NEXT j 'QB
SYSTEM 'QB
I'd recommend using a regular expressions instead of string operations for this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\VBS\filediprova.txt"
newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"
Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global = False
re.IgnoreCase = True
text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")
The regular expression will match a line feed (\n
) followed by a line containing the string Test Case
followed by a number (\d
), and the replacement will prepend that with the text you want to insert (variable newtext
). Setting re.Global = False
makes the replacement stop after the first match.
If the line breaks in your text file are encoded as CR-LF
(carriage return + line feed) you'll have to change \n
into \r\n
and vbLf
into vbCrLf
.
If you have to modify several text files, you could do it in a loop like this:
For Each f In fso.GetFolder("C:\VBS").Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
End If
Next
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html
Then you should edit your mysqld.cnf
file, for instance :
vim /etc/mysql/mysql.conf.d/mysqld.cnf
Then, add in the [mysqld] part, the following :
plugin-load-add=validate_password.so
validate_password_policy=LOW
Basically, if you edit your default, it will looks like :
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW
Then, you can restart:
systemctl restart mysql
If you forget the plugin-load-add=validate_password.so
part, you will it an error at restart.
Enjoy !
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
server.contextPath=/mainstay
works for me if i had one war file in JBOSS. Among multiple war files where each contain jboss-web.xml it didn't work. I had to put jboss-web.xml inside WEB-INF directory with content
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
<context-root>mainstay</context-root>
</jboss-web>
pd.to_numeric
with errors='coerce'
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use
pd.__version__ # '0.24.1' pd.to_numeric(s, errors='coerce').astype('Int32') 0 1 1 2 2 3 3 4 4 NaN dtype: Int32
There are other options to choose from as well, read the docs for more.
DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
Bubble sort is definitely the winner The next one on the radar would be insertion sort.
I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.
You should assign setTimeout
to a variable and use clearTimeout
to clear it on keypress.
var timer = '';
$('input#username').keypress(function() {
clearTimeout(timer);
timer = setTimeout(function() {
//Your code here
}, 3000); //Waits for 3 seconds after last keypress to execute the above lines of code
});
Hope this helps.
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10)
. you should have used ' '
.
try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
If ID(and all coulmns) is needed from mytable
SELECT
*
FROM
mytable
WHERE
id NOT IN (
SELECT
A.id
FROM
mytable AS A
JOIN mytable AS B ON A. GROUP = B. GROUP
AND A.age < B.age
)
Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.
char hextob(char ch)
{
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
}
template<typename T>
T hextot(char* hex)
{
T value = 0;
for (size_t i = 0; i < sizeof(T)*2; ++i)
value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
return value;
};
Usage:
int main()
{
char str[4] = {'f','f','f','f'};
std::cout << hextot<int16_t>(str) << "\n";
}
Note: the length of the string must be divisible by 2
Look in C:\Program Files\dotnet\shared\Microsoft.NETCore.App
to see which versions of the runtime have directories there. Source.
A lot of the answers here confuse the SDK with the Runtime, which are different.
If you have several values to replace, you can also use a dictionary:
a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}
print([dic.get(n, n) for n in a])
> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]
The layout to use is indeed "2006-01-02T15:04:05.000Z
" described in RickyA's answer.
It isn't "the time of the first commit of go", but rather a mnemonic way to remember said layout.
See pkg/time:
The reference time used in the layouts is:
Mon Jan 2 15:04:05 MST 2006
which is Unix time
1136239445
.
Since MST is GMT-0700, the reference time can be thought of as
01/02 03:04:05PM '06 -0700
(1,2,3,4,5,6,7, provided you remember that 1 is for the month, and 2 for the day, which is not easy for an European like myself, used to the day-month date format)
As illustrated in "time.parse : why does golang parses the time incorrectly?", that layout (using 1,2,3,4,5,6,7) must be respected exactly.
Adding php5.ini doesn't work at all. But see the 'Disable FastCGI' section in this article on GoDaddy: http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions
Add these lines to .htaccess files (webroot & website installation directory):
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
It saves me a day! Cheers! Thanks DragonLord!
You can now use Object.assign(target, ...sources)
. Following your example, you could use it like this:
class Foo {
name: string;
getName(): string { return this.name };
}
let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));
console.log(foo.getName()); //returns John Doe
Object.assign
is part of ECMAScript 2015 and is currently available in most modern browsers.
I agree that a ternary is extremely clean. Seems that it is very situational though as somethings I need to display div or p or table , so with a table I don't prefer a ternary for obvious reasons. Making a call to a function is typically ideal or in my case I did this:
<div ng-controller="TopNavCtrl">
<div ng-if="info.host ==='servername'">
<table class="table">
<tr ng-repeat="(group, status) in user.groups">
<th style="width: 250px">{{ group }}</th>
<td><input type="checkbox" ng-model="user.groups[group]" /></td>
</tr>
</table>
</div>
<div ng-if="info.host ==='otherservername'">
<table class="table">
<tr ng-repeat="(group, status) in user.groups">
<th style="width: 250px">{{ group }}</th>
<td><input type="checkbox" ng-model="user.groups[group]" /></td>
</tr>
</table>
</div>
</div>
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Use isinstance(obj, basestring)
for an object-to-test obj
.
Docs.
Change Minute parameter to 0.
You can set the cron for every three hours as:
0 */3 * * * your command here ..
you can try :
$("#MediaPlayer").ready(function(){
$("html, body").delay(2000).animate({
scrollTop: $('#MediaPlayer').offset().top
}, 2000);
});
Here in http://www.campaignmonitor.com/css/, a nice explanation to say this is restricted! And a pretty nice guide to know all limitations of CSS in email clients.
As other users have pointed out, we use expression()
. I'd like to answer the original question which involves a comma in the subscript:
How can I write v 1,2 with 1,2 as subscripts?
plot(1:10, 11:20 , main=expression(v["1,2"]))
Also, I'd like to add the reference for those looking to find the full expression
syntax in R
plotting: For more information see the ?plotmath
help page. Running demo(plotmath)
will showcase many expressions and relevant syntax.
Remember to use *
to join different types of text within an expression.
Here is some of the sample output from demo(plotmath)
:
I disagree with this kind of path
GET /companies/{companyId}/departments
If you want to get departments, I think it's better to use a /departments resource
GET /departments?companyId=123
I suppose you have a companies
table and a departments
table then classes to map them in the programming language you use. I also assume that departments could be attached to other entities than companies, so a /departments resource is straightforward, it's convenient to have resources mapped to tables and also you don't need as many endpoints since you can reuse
GET /departments?companyId=123
for any kind of search, for instance
GET /departments?name=xxx
GET /departments?companyId=123&name=xxx
etc.
If you want to create a department, the
POST /departments
resource should be used and the request body should contain the company ID (if the department can be linked to only one company).
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)
export default
is used to create local registration for Vue component.
Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e
Redirect aspx :
<iframe>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.avsapansiyonlar.com/altinkum-tatil-konaklari.aspx");
}
</script>
</iframe>
I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.
//
//
// CSV to object
//
//
const new_line_char = '\n';
const field_separator_char = ',';
function parse_csv(csv_str) {
var result = [];
let line_end_index_moved = false;
let line_start_index = 0;
let line_end_index = 0;
let csr_index = 0;
let cursor_val = csv_str[csr_index];
let found_new_line_char = get_new_line_char(csv_str);
let in_quote = false;
// Handle \r\n
if (found_new_line_char == '\r\n') {
csv_str = csv_str.split(found_new_line_char).join(new_line_char);
}
// Handle the last character is not \n
if (csv_str[csv_str.length - 1] !== new_line_char) {
csv_str += new_line_char;
}
while (csr_index < csv_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === new_line_char) {
if (in_quote === false) {
if (line_end_index_moved && (line_start_index <= line_end_index)) {
result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
line_start_index = csr_index + 1;
} // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
} // Else: just ignore because we are in a quote
}
csr_index++;
cursor_val = csv_str[csr_index];
line_end_index = csr_index;
line_end_index_moved = true;
}
// Handle \r\n
if (found_new_line_char == '\r\n') {
let new_result = [];
let curr_row;
for (var i = 0; i < result.length; i++) {
curr_row = [];
for (var j = 0; j < result[i].length; j++) {
curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
}
new_result.push(curr_row);
}
result = new_result;
}
return result;
}
function parse_csv_line(csv_line_str) {
var result = [];
//let field_end_index_moved = false;
let field_start_index = 0;
let field_end_index = 0;
let csr_index = 0;
let cursor_val = csv_line_str[csr_index];
let in_quote = false;
// Pretend that the last char is the separator_char to complete the loop
csv_line_str += field_separator_char;
while (csr_index < csv_line_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === field_separator_char) {
if (in_quote === false) {
if (field_start_index <= field_end_index) {
result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
field_start_index = csr_index + 1;
} // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
} // Else: just ignore because we are in quote
}
csr_index++;
cursor_val = csv_line_str[csr_index];
field_end_index = csr_index;
field_end_index_moved = true;
}
return result;
}
function parse_csv_field(csv_field_str) {
with_quote = (csv_field_str[0] === '"');
if (with_quote) {
csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
}
return csv_field_str;
}
// Initial method: check the first newline character only
function get_new_line_char(csv_str) {
if (csv_str.indexOf('\r\n') > -1) {
return '\r\n';
} else {
return '\n'
}
}
That's basically a set of 2 simultaneous equations:
x*y = a
X+y = b
(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).
But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.
I wrote a simple wrapper around Google's .Net client library, it exposes a simpler database-like interface, with strongly-typed record types. Here's some sample code:
public class Entity {
public int IntProp { get; set; }
public string StringProp { get; set; }
}
var e1 = new Entity { IntProp = 2 };
var e2 = new Entity { StringProp = "hello" };
var client = new DatabaseClient("[email protected]", "password");
const string dbName = "IntegrationTests";
Console.WriteLine("Opening or creating database");
db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
const string tableName = "IntegrationTests";
Console.WriteLine("Opening or creating table");
table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
table.DeleteAll();
table.Add(e1);
table.Add(e2);
var r1 = table.Get(1);
There's also a LINQ provider that translates to google's structured query operators:
var q = from r in table.AsQueryable()
where r.IntProp > -1000 && r.StringProp == "hello"
orderby r.IntProp
select r;
I think something like
$("#leftDiv").mouseover(function(){$(this).css("overflow","scroll");});
$("#leftDiv").mouseout(function(){$(this).css("overflow","hidden");});
CTRL + I for incremental search. Hit F3 or CTRL + I to cycle through the results.
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
You just wrap your query in another one:
SELECT COUNT(*), SUM(Age)
FROM (
SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS tmp;
This will give two-char long string for a byte.
public String toString(byte b){
final char[] Hex = new String("0123456789ABCDEF").toCharArray();
return "0x"+ Hex[(b & 0xF0) >> 4]+ Hex[(b & 0x0F)];
}
Readonly will allow the user to copy text from it. Disabled will not.
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
The immediate problem is you have is with quoting: by using double quotes ("..."
), your variable references are instantly expanded, which is probably not what you want.
Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.
(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $
of references you do not want expanded with \
; e.g., \$var
).
However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin
input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<
, and the closing one on a line by itself - starting at the very first column; search for Here Documents
in man bash
or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.
If you quote the here-doc delimiter (EOF
in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \
:
echo "creating new script file."
cat <<'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}`
if [ $servicetest > /dev/null ]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi
EOF
As @BruceK notes, you can prefix your here-doc delimiter with -
(applied to this example: <<-"EOF"
) in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern.
Note, however, that this only works with actual tab characters, not leading spaces.
Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):
cat <<-'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service name: " ser
if [[ -n $(getsebool -a | grep "${ser}") ]]; then
echo "We are now going to work with ${ser}."
else
exit 1
fi
EOF
Finally, note that in bash
even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.
Thus, note how in the following #!/bin/bash
has to follow the opening '
immediately in order to become the first line of output:
echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi' > "$servfile"
Afterthoughts regarding the contents of your script:
$(...)
is preferred over `...`
for command substitution nowadays.${ser}
in the grep
command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).[[ -n $servicetest ]]
to test whether $servicetest
is empty (or perform the command substitution directly inside the conditional) - [[ ... ]]
- the preferred form in bash
- protects you from breaking the conditional if the $servicetest
happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ]
or [[ ... ]]
, as no stdout output is passed through; thus, the > /dev/null
is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).There is probably a more efficient solution to your question, but following formula should do the trick:
=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))
In the spirit of a DVCS (as in "Distributed"), you don't cancel something you have published:
Pull requests are essentially patches you have send (normally by email, here by GitHub webapp), and you wouldn't cancel an email either ;)
But since the GitHub Pull Request system also includes a discussion section, that would be there that you could voice your concern to the recipient of those changes, asking him/her to disregards 29 of your 30 commits.
Finally, remember:
That being said, since January 2011 ("Refreshed Pull Request Discussions"), and mentioned in the answer above, you can close a pull request in the comments.
Look for that "Comment and Close" button at the bottom of the discussion page:
Bash doesn't have multi-dimensional array. But you can simulate a somewhat similar effect with associative arrays. The following is an example of associative array pretending to be used as multi-dimensional array:
declare -A arr
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 0 1
If you don't declare the array as associative (with -A
), the above won't work. For example, if you omit the declare -A arr
line, the echo
will print 2 3
instead of 0 1
, because 0,0
, 1,0
and such will be taken as arithmetic expression and evaluated to 0
(the value to the right of the comma operator).
Try this...
function Test()
{
var s1 = new StopWatch();
s1.Start();
// Do something.
s1.Stop();
alert( s1.ElapsedMilliseconds );
}
// Create a stopwatch "class."
StopWatch = function()
{
this.StartMilliseconds = 0;
this.ElapsedMilliseconds = 0;
}
StopWatch.prototype.Start = function()
{
this.StartMilliseconds = new Date().getTime();
}
StopWatch.prototype.Stop = function()
{
this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}
I believe that is is a move operator. operator=
is the assignment operator, say vector x = vector y
. The clear()
function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.
This way,
std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
std::cout << b[i] << ' ';
}
Even though we gave vector a values, vector b has the values. It's the magic of the operator=()
!
Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.
Of course for object parameters (like string
) the object's constructor could do a default initialization.
In your example:
int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value
Just follow these steps to transfer the apk onto the real device(with debugger key) and which is just for testing purpose. (Note: For proper distribution to the market you may need to sign your app with your keys and follow all the steps.)
Good luck !
Using the Property window
Select form ? go to property window ? select "start position" ? select whatever the place you want.
Programmatically
Form form1 = new Form();
form1.StartPosition = FormStartPosition.CenterScreen;
form1.ShowDialog();
Note: Do not directly call Form.CenterToScreen() from your code. Read here.
If you want to do multiple (3+) columns here is a great snippet that works perfectly and validates as valid HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Colums</title>
<!-- Styles -->
<style>
.flex-center {
width: 100%;
align-items: center;/*These two properties center vetically*/
height: 100vh;/*These two properties center vetically*/
display: flex;/*This is the attribute that separates into columns*/
justify-content: center;
text-align: center;
position: relative;
}
.spaceOut {
margin-left: 25px;
margin-right: 25px;
}
</style>
</head>
<body>
<section class="flex-center">
<h4>Tableless Columns Example</h4><br />
<div class="spaceOut">
Column 1<br />
</div>
<div class="spaceOut">
Column 2<br />
</div>
<div class="spaceOut">
Column 3<br />
</div>
<div class="spaceOut">
Column 4<br />
</div>
<div class="spaceOut">
Column 5<br />
</div>
</section>
</body>
</html>
Some of the answers here imply that given a "package" directory (with or without an explicit __init__.py
file), containing a __main__.py
file, there is no difference between running that directory with the -m
switch or without.
The big difference is that without the -m
switch, the "package" directory is first added to the path (i.e. sys.path), and then the files are run normally, without package semantics.
Whereas with the -m
switch, package semantics (including relative imports) are honoured, and the package directory itself is never added to the system path.
This is a very important distinction, both in terms of whether relative imports will work or not, but more importantly in terms of dictating what will be imported in the case of unintended shadowing of system modules.
Example:
Consider a directory called PkgTest
with the following structure
:~/PkgTest$ tree
.
+-- pkgname
¦ +-- __main__.py
¦ +-- secondtest.py
¦ +-- testmodule.py
+-- testmodule.py
where the __main__.py
file has the following contents:
:~/PkgTest$ cat pkgname/__main__.py
import os
print( "Hello from pkgname.__main__.py. I am the file", os.path.abspath( __file__ ) )
print( "I am being accessed from", os.path.abspath( os.curdir ) )
from testmodule import main as firstmain; firstmain()
from .secondtest import main as secondmain; secondmain()
(with the other files defined similarly with similar printouts).
If you run this without the -m
switch, this is what you'll get. Note that the relative import fails, but more importantly note that the wrong testmodule has been chosen (i.e. relative to the working directory):
:~/PkgTest$ python3 pkgname
Hello from pkgname.__main__.py. I am the file ~/PkgTest/pkgname/__main__.py
I am being accessed from ~/PkgTest
Hello from testmodule.py. I am the file ~/PkgTest/pkgname/testmodule.py
I am being accessed from ~/PkgTest
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "pkgname/__main__.py", line 10, in <module>
from .secondtest import main as secondmain
ImportError: attempted relative import with no known parent package
Whereas with the -m switch, you get what you (hopefully) expected:
:~/PkgTest$ python3 -m pkgname
Hello from pkgname.__main__.py. I am the file ~/PkgTest/pkgname/__main__.py
I am being accessed from ~/PkgTest
Hello from testmodule.py. I am the file ~/PkgTest/testmodule.py
I am being accessed from ~/PkgTest
Hello from secondtest.py. I am the file ~/PkgTest/pkgname/secondtest.py
I am being accessed from ~/PkgTest
Note: In my honest opinion, running without -m
should be avoided. In fact I would go further and say that I would create any executable packages
in such a way that they would fail unless run via the -m
switch.
In other words, I would only import from 'in-package' modules explicitly via 'relative imports', assuming that all other imports represent system modules. If someone attempts to run your package without the -m
switch, the relative import statements will throw an error, instead of silently running the wrong module.
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
If we talk about SessionFactory.openSession()
And If we talk about SessionFactory.getCurrentSession()
Sometime some C# approach makes the life easier in Java world..:
class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;
Try the format as dd-mon-yyyy, For example 02-08-2016 should be in the format '08-feb-2016'.
Another way to use .ui in your code is:
from PyQt4 import QtCore, QtGui, uic
class MyWidget(QtGui.QWidget)
...
#somewhere in constructor:
uic.loadUi('MyWidget.ui', self)
both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must compile it too:
pyrcc4.exe -o ui/images_rc.py ui/images/images.qrc
Note, when uic
compiles interface, it adds 'import images_rc' at the end of .py file, so you must compile resources into the file with this name, or rename it in generated code.
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
Recent versions of VSCode (e.g., Version 1.29 at the time of posting this answer) allow you to change the Tab/Space size to 1
(or any number between 1
and 8
). You may change the Tab/Space size from the bottom-right corner as shown in the below image:
Click on Spaces:4
. Then, select Indent Using Spaces or Indent Using Tabs and choose the size 1.
Hope it helps.
I just published this module because I needed this functionality.
https://www.npmjs.org/package/filendir
It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFile
and fs.writeFileSync
(both async and synchronous writes)