You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
This regex should do it.
\b[a-z]+-[a-z]+\b
\b
indicates a word-boundary.
Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search
There are a lot of answered questions in Stack Overflow with more data on this:
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
Working on android studio: 3.6.3 and gradle version:
classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
Adding this line in
gradle.properties file
org.gradle.jvmargs=-Xmx512m
Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.
simple steps:
please, check this doc for more details: https://material-ui.com/customization/theming/
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';
const InputTheme = createMuiTheme({
overrides: {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
}
});
class HigherOrderComponent extends React.Component {
render(){
const { classes } = this.props;
return (
<MuiThemeProvider theme={InputTheme}>
<Button className={classes.root}>Higher-order component</Button>
</MuiThemeProvider>
);
}
}
HigherOrderComponent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default HigherOrderComponent;
_x000D_
This issue is still up on keras git. I hope it gets solved as soon as possible. Until then, try downgrading your numpy version to 1.16.2. It seems to solve the problem.
!pip install numpy==1.16.1
import numpy as np
This version of numpy has the default value of allow_pickle
as True
.
In JSX, the lower-case tag name is considered as html native component. In order to react recognise the function as React component, need to Capitalized the name.
Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.
https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components
Run npm version
, if you see the same error, upgrade npm.
brew upgrade npm
.
==> Upgrading 1 outdated package, with result:
npm 8.1.2 -> 10.3.0
==> Upgrading npm
==> Installing dependencies for node: icu4c
==> Installing node dependency: icu4c
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
Currently my build is working. Here you are the steps I tried until it finally worked:
And If you don't have that Pod, maybe you can try by making the same steps with some old Pod that you may encounter in your project.
Added information: also If you have some code error inside a Pod, first you need to solve that code problem and then try to compile again the project.
I'm going to copy the changes made in my project.pbxproj. I know it's not very helpful but it's the only thing that have changed in the git difference commit:
Removed: BDC9821B1E9BD1B600ADE0EF /* (null) in Sources */ = {isa = PBXBuildFile; };
Added: BDC9821B1E9BD1B600ADE0EF /* BuildFile in Sources */ = {isa = PBXBuildFile; };
I hope this can help,
Regards.
Tried all the above solutions, but none of them worked. This issue comes when trying to add table to a class.
npm i react-native-table-component and then run App.js.
./node_modules/react-native-table-component/components/cell.js SyntaxError: C:\Users\Dileep\finaltest\node_modules\react-native-table-component\components\cell.js: Support for the experimental syntax 'classProperties' isn't currently enabled (5:20):
Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');
Change this line from your code to this -
var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');
or in my case, I gave the encoding in reverse order
var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');
You can use it this way
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Text(
'Card with circular border',
textScaleFactor: 1.2,
),
),
Card(
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Text(
'Card with Beveled border',
textScaleFactor: 1.2,
),
),
Card(
shape: StadiumBorder(
side: BorderSide(
color: Colors.black,
width: 2.0,
),
),
child: Text(
'Card with Beveled border',
textScaleFactor: 1.2,
),
),
If you are using the official mysql docker container, there is a simple solution:
Add the following line to your docker-compose service:
command: --default-authentication-plugin=mysql_native_password
Example configuration:
mysql:
image: mysql:8
networks:
- net_internal
volumes:
- mysql_data:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=db
command: --default-authentication-plugin=mysql_native_password
Using MediaQuery
class:
MediaQueryData queryData;
queryData = MediaQuery.of(context);
MediaQuery: Establishes a subtree in which media queries resolve to the given data.
MediaQueryData: Information about a piece of media (e.g., a window).
To get Device Pixel Ratio:
queryData.devicePixelRatio
To get width and height of the device screen:
queryData.size.width
queryData.size.height
To get text scale factor:
queryData.textScaleFactor
Using AspectRatio
class:
From doc:
A widget that attempts to size the child to a specific aspect ratio.
The widget first tries the largest width permitted by the layout constraints. The height of the widget is determined by applying the given aspect ratio to the width, expressed as a ratio of width to height.
For example, a 16:9 width:height aspect ratio would have a value of 16.0/9.0. If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height.
Now consider a second example, this time with an aspect ratio of 2.0 and layout constraints that require the width to be between 0.0 and 100.0 and the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the biggest allowed) and a height of 50.0 (to match the aspect ratio).
//example
new Center(
child: new AspectRatio(
aspectRatio: 100 / 100,
child: new Container(
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.orange,
)
),
),
),
I have added in Application Class
@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
application.properties I have added
app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30
More details Configure a Custom DataSource
@praneeth-nidarshan has covered mostly all the steps, except some:
$ sudo apt-get install php-pear
sh: phpize: not found
ERROR: `phpize’ failed
$ sudo apt-get install php7.2-dev
$ sudo pecl install mcrypt-1.0.1
extension=mcrypt.so
to your php.ini configuration file; if you don't know where it is, search with:$ sudo php -i | grep 'Configuration File'
This happens because your local module named urllib.py
shadows the installed requests module you are trying to use. The current directory is preapended to sys.path, so the local name takes precedence over the installed name.
An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import.
Rename your file to something else like url.py
.
Then It is working fine.
Hope it helps!
To open a terminal in VS code just type CTRL
+ ~
which will open the terminal. Here are the steps:
Check for the particular component where you need to generate the new component.
Redirect the path to the particular folder/component where you need to generate another component
FOR EXAMPLE: cd src/app/particularComponent
In the place of particularComponent, type the component name in which you need to generate the new component.
ng g c NewComponentName
(Change the name NewComponentName to your required component name.)
If You want to Update an array in a firebase document. You can do this.
var documentRef = db.collection("Your collection name").doc("Your doc name")
documentRef.update({
yourArrayName: firebase.firestore.FieldValue.arrayUnion("The Value you want to enter")});
The Connection for controluser as defined in your configuration failed, right after:
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'you_password';
Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
i like this clever syntax to do async work from an entrypoint
void async function main() {
await doSomeWork()
await doMoreWork()
}()
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
Use UIWindow
or UIView
's safeAreaInsets
.bottom
.top
.left
.right
// #available(iOS 11.0, *)
// height - UIApplication.shared.keyWindow!.safeAreaInsets.bottom
// On iPhoneX
// UIApplication.shared.keyWindow!.safeAreaInsets.top = 44
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 34
// Other devices
// UIApplication.shared.keyWindow!.safeAreaInsets.top = 0
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 0
// example
let window = UIApplication.shared.keyWindow!
let viewWidth = window.frame.size.width
let viewHeight = window.frame.size.height - window.safeAreaInsets.bottom
let viewFrame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
let aView = UIView(frame: viewFrame)
aView.backgroundColor = .red
view.addSubview(aView)
aView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
For others come to here:
If you happen to put your docker command in a file, say run.sh
, check your line separator. In Linux, it should be LR
, otherwise you would get the same error.
When you install the WAMPP in your machine by default the password of PhpMyAdmin is blank. so put root in user Section and left blank of password field. hope it works.
Happy Coding!!
You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.
https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine
You need to install Microsoft Visual C++ 14.0 to install pycrypto:
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.
In the comments you ask about methods of installing pycrypto
that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.
I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto
that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.
After you have installed Visual C++, just re-run the original command:
pip install -U steem
To find out what the various install options mean, run this command:
pip help install
The help for the -U
option says
-U, --upgrade Upgrade all specified packages to the newest available
version. The handling of dependencies depends on the
upgrade-strategy used.
If you do not already have the steem
library installed, you can run the command without the -U
option.
you should do import Map from './Map'
React is just telling you it doesn't know where variable you are importing is.
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
When you use Fabric for public beta releases (signed with prod config), DON'T USE Google Play App Signing. You will must after build two signed apks!
When you distribute to more play stores (samsung, amazon, xiaomi, ...) you will must again build two signed apks.
So be really carefull with Google Play App Signing.
It's not possible to revert it :/ and Google Play did not after accept apks signed with production key. After enable Google Play App Signing only upload key is accepted...
It really complicate CI distribution...
Next issues with upgrade: https://issuetracker.google.com/issues/69285256
Just a MacOS extra update for hjpotter92 answer.
To make sed
recognize the pattern in MacOS, you'll have to add a backslash before the =
sign, like this:
sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql
I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.
1) Create environment variable in your environment.ts
export const environment = {
...
// runtime variables
isContentLoading: false,
isDeployNeeded: false
}
2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template
import { environment } from 'environments/environment';
@Component(...)
export class TestComponent {
...
env = environment;
}
3) Use it in template...
<app-spinner *ngIf='env.isContentLoading'></app-spinner>
in *.ts ...
env.isContentLoading = false
(or just environment.isContentLoading in case you don't need it for template)
You can create your own set of globals within environment.ts like so:
export const globals = {
isContentLoading: false,
isDeployNeeded: false
}
and import directly these variables (y)
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key
instead of event.keyCode
(because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).
onKeyPressed(e) {
console.log(e.key);
}
render() {
let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
return (
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
>
<div className="light-circle">
<div className="image-wrapper">
<img src={IMG_URL+player.img} />
</div>
</div>
</div>
)
}
Removed and added back in the table using Scaffold-DbContext and the error went away
in your CFG file please change the hibernate dialect
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
For MySql 8 you can use following script:
SET GLOBAL validate_password.LENGTH = 4;
SET GLOBAL validate_password.policy = 0;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.special_char_count = 0;
SET GLOBAL validate_password.check_user_name = 0;
ALTER USER 'user'@'localhost' IDENTIFIED BY 'pass';
FLUSH PRIVILEGES;
You should use require_once and include_once. Inside parent.php use
include_once 'database.php';
And inside child1.php and child2.php use
include_once 'parent.php';
The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.
Native Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]
Underscore Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);
The above answer by pl_rock is correct, the only thing I would add is to expect the ARG inside the Dockerfile if not you won't have access to it. So if you are doing
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 --build-arg number_of_replicas=2 --no-cache .
Then inside the Dockerfile you should add
ARG number_of_replicas
ARG number_of_shards
I was running into this problem, so I hope I help someone (myself) in the future.
You probably want to assign the lastname
you are reading out here
lastname = sheet.cell(row=r, column=3).value
to something; currently the program just forgets it
you could do that two lines after, like so
unpaidMembers[name] = lastname, email
your program will still crash at the same place, because .items()
still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))
good news is, python can handle this
for name, (lastname, email) in unpaidMembers.items():
etc.
A somewhat unlikely situation.
I have removed the yarn.lock
file, which referenced an older version of webpack.
So check to see the differences in your yarn.lock
file as a possiblity.
I'm slow to add yet another answer, but the accepted answer and remaining answers mentioning docker login
are missing an edge case to solve the issues others are stating in comments.
docker login <private-repo-host>:<port>
Emphasis on the port
needing to be entered is likely the solution for those still searching. docker login
or docker login <private-repo-host>
may connect without issue, but when it comes time to push images, you'll get the same error as OP.
That is, you can connect w/o defining host or port and still get the:
...
Login Succeeded
In my case, I am using a self hosted GitLab's built in docker-registry, which was setup to use port 4567
. It may be adventagous to verify what port the registry must be accessed from. Without specifying said port docker login <our.gitlab.host>
would login successful, but give the same issue the OP inquired about:
...
The push refers to repository [...]
denied: access forbidden
If you're using docker.io/dockerhub you're likely not going to have this problem, but if you have a self hosted/private registry solution the probability increases you need to explicitly login using both the host and port for the docker registry.
I finally solved this by creating a second object that imitates B.
My schema now looks like this:
I now have B1 (within parent of A) and B2 outside of it.
B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.
I am very late but I found some other way where you don't need to have loops. you can reset array by setting array control to empty.
Below code will reset your array.
this.form.setControl('name', this.fb.array([]))
I am using Linux and have nvm
and working with more than 7 version of node
As of my experience I experienced the same situation with my latest project (actually not hours but minutes as I can't wait hours because of hourly project :))
Disclaimer: don't try below option until you know how cache clean works
npm cache clean --force
and then all working fine for me so it's looks like sometimes npm's cache gets confused with different versions of Node.
Official documentation of Npm cache can be found here
As pointed out, you should not be storing your users' passwords in a format that is decryptable. Reversable encryption provides an easy route for hackers to find out your users' passwords, which extends to putting your users' accounts at other sites at risk should they use the same password there.
PHP provides a pair of powerful functions for random-salted, one-way hash encryption — password_hash()
and password_verify()
. Because the hash is automatically random-salted, there is no way for hackers to utilize precompiled tables of password hashes to reverse-engineer the password. Set the PASSWORD_DEFAULT
option and future versions of PHP will automatically use stronger algorithms to generate password hashes without you having to update your code.
While the previous solutions are very correct, if you absolutely need the feature then you can mimic the situation with custom input using text-field and JavaScript.
For secure usage, you can use any cryptography technique. So this way you will bypass the browser's password saving behavior.
If you want to know more about the idea, we can discuss that on chat. But the gist is discussed in previous answers and you can get the idea.
How about using IIF?
SELECT IIF (EXISTS (SELECT 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx'), 1, 2)
Also, if using EXISTS to check the the existence of rows, don't use *, just use 1. I believe it has the least cost.
The target container should have the white-space:pre
style.
Try it below.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target' style='white-space:pre'>_x000D_
_x000D_
</p>
_x000D_
To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.
dumps(s.decode()).replace("'", '"')[1:-1]
If nothing work then I have one solution @Access(value=AccessType.FIELD) add this line in under model class after you used @Entity then followed by the class and after class when you defining id and all that time you use above line.
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
This means the file isn't really a gzipped tar file -- or any kind of gzipped file -- in spite of being named like one.
When you download a file with wget
, check for indications like Length: unspecified [text/html]
which shows it is plain text (text) and that it is intended to be interpreted as html. Check the wget
output below -
[root@XXXXX opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:39:40-- http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... 23.72.136.27, 23.72.136.67
Connecting to download.oracle.com (download.oracle.com)|23.72.136.27|:80... connected.
HTTP request sent, awaiting response... 302 Not Allowed
Location: http://XXXX/FAQs/URLFiltering/ProxyWarning.html [following]
--2017-10-12 12:39:40-- http://XXXX/FAQs/URLFiltering/ProxyWarning.html
Resolving XXXX (XXXXX)... XXX.XX.XX.XXX
Connecting to XXXX (XXXX)|XXX.XX.XX.XXX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17121 (17K) [text/html]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’
100%[=========================================================================================================================================================================>] 17,121 --.-K/s in 0.05s
2017-10-12 12:39:40 (349 KB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [17121/17121]
This sort of confirms that you haven't received a gzip file.
For a correct file, the wget
output will show something like Length: 185515842 (177M) [application/x-gzip]
as shown in the below output -
[root@txcdtl01ss270n opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:50:06-- http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... XX.XXX.XX.XX, XX.XX.XXX.XX
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz [following]
--2017-10-12 12:50:06-- https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving edelivery.oracle.com (edelivery.oracle.com)... XXX.XX.XXX.XX, 2600:1404:16:188::2d3e, 2600:1404:16:180::2d3e
Connecting to edelivery.oracle.com (edelivery.oracle.com)|XXX.XX.XX.XXX|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61e7f202677f94afd [following]
--2017-10-12 12:50:07-- http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 185515842 (177M) [application/x-gzip]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’
100%[=========================================================================================================================================================================>] 185,515,842 6.60MB/s in 28s
2017-10-12 12:50:34 (6.43 MB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [185515842/185515842]
The above shows a correct gzip
application file has been downloaded.
You can also file
, head
, less
, view
utilities to check the file. For example a HTML file would give below output -
[root@XXXXXX opt]# head jdk-8u144-linux-x64.tar.gz
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/print.css" rel="stylesheet" media="print">
<link href="/css/main.css" rel="stylesheet" media="screen">
<link href="/css/font-awesome.min.css" rel="stylesheet">
The above shows it is indeed an HTML page which we are trying to unzip/untar - something that won't work. If it was indeed a correct zip file (binary in nature) the output of head
would have produced garbage - something like below -
[root@XXXX opt]# head jdk-8u144-linux-x64.tar.gz
x?rY?[ms?F???????t?l???DR??????j
$?$,`0?h?_????/??=?@Q?w+???*?Hbfz?{?~?{?i?x??k?????}????z???w????g?????{???;{s????w?????7?N????i?
?????}
?¿g????????????7??s??????î??????~i??j?/??????#???=??=>???{}??|?????????????3???X???]9??????u?????%g?<^)?H?8?F?R?t?o?L?u??S%?ds5?2_EZn?t^??
?N3??(??<??|'?q???R?N?gq?Uv!???p???rL??M??u??.?Q?5?T??BNw?!$??<>?7G'$?,Mt4WY?Gi"?=??p?)?VIN3????\ek??0??G
?<L?c?e?t-???2???G:?ia??I?<?g3???d?H????[2`?<I?A?6?W??<??C???????h??A0QL?2?4?-*
?x?????t%t1??f?>+A??,Lr?
?Fe:MBH????
C?Q?r?S??<M?b?<,5???@???s???c??sp?f?=g?????k???4?}??kh)?¹Z??#d?*{???-?.N?)?e??s:?H(VQ??3*?$2??r?v?"o?_??!A???????B?l=A?|??@??0??1??5??4g?
?
???Se????H[2?????t??5?Df????$1???b$? h?Op????!Lvb!p??b?8^?Y???n?
O??????|??lW?lu??*?N?M???
?/?^0~?~?#??q????????K??;?d???aw4?????'?~?7??ky?o?????????t?'k??f????!vo???'o??? ?.?Pn\?
?+??K"FA{????n2????v??!/Ok??r4?c5?x$'?.?&w?!?%??o??????2???i
?a0??Ag?d????GH)G7~?g???b??%?b??rt?m~? ?????t0?? <????????????5?q?t??K(??+Z<??=???:1?\?x?p=t?`??G@F?? i?????p8?????H.???dMLE??e[?`?'n??*h[??;?0w'??6A??M?x?fpeB>&???MO???????`?@á/?"?????(??^???n??=????5??@?Mx??d:\YAn???]|?w>??S??FA9?J?k!?@?
Try downloading from the official site and check if their download links have changed. Also check your proxy settings and make sure you have the right proxies enabled to download/wget
it from the correct source.
Hope this helps.
Me help next:
git stash
git pull origin master
git apply
git commit -m "some comment"
git push
You can follow this way. It works at least for me :
in Credential page :
Select option with IP address ( option no. 3 ).
Put your IP address from your provider. If you don't it, search your IP address by using this link : https://www.google.com/search?q=my+ip
Save it.
Change your google map link as follow between the scrip tag :
https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzxxxxxxxx"
Wait for about 5 minutes or more to let your API key to propagate.
Now your google map should works.
In newer versions of pandas (0.20.0+, I believe), this can be done directly:
df.to_json('temp.json', orient='records', lines=True)
Direct compression is also possible:
df.to_json('temp.json.gz', orient='records', lines=True, compression='gzip')
This error occurs when you're trying to target an element that is wrapped in a condition.
So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined
So use [hidden], class.show or class.hide in place of *ngIf.
<button (click)="displayMap()" class="btn btn-primary">Display Map</button>
<div [hidden]="!display">
<div #mapContainer id="map">Content to render when condition is true.</div>
</div>
Looks like ~/.aws/credentials
was not created. Try creating it manually with this content:
[default]
aws_access_key_id = sdfesdwedwedwrdf
aws_secret_access_key = wedfwedwerf3erfweaefdaefafefqaewfqewfqw
(on my test box, if I run aws
command without having credentials file, the error is Unable to locate credentials. You can configure credentials by running "aws configure".
)
Can you try running these two commands from the same shell you are trying to run aws
:
$ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
and then try aws
command.
Put the elements which you want to shift to the centre within this div tag.
<div class="col d-flex justify-content-center">
</div>
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
Override constructor of DbContext Try this :-
public DataContext(DbContextOptions<DataContext> option):base(option) {}
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
In my case i was returning string value from my api eg: "35" and in my HTML i was using
<mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
<mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
{{ state.stateName }}
</mat-option>
</mat-select>
Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below
var x = user.state;
var y: number = +x;
and then assigned it like
this.EditProfileForm.get('states').setValue(y);
Now the correct values is getting setting by default.
I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.
fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)
You can achieve the same using
<select [ngModel]="object">
<option *ngFor="let object of objects;let i= index;" [value]="object.value" selected="i==0">{{object.name}}</option>
</select>
When you create table than you can give like follows.
CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
and when after the table create like this
ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;
Following on example for it.
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
For drop the key
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
Hope this help to learn FOREIGN keys works
I faced the same issue with a Foundation menu. align-self: center;
didn't work for me.
My solution was to wrap the image with a <div style="display: inline-table;">...</div>
Tested Answer By me:
form.html
<input type="text" (keypress)="restrictNumeric($event)">
form.component.ts:
public restrictNumeric(e) {
let input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
if (e.which === 0) {
return true;
}
if (e.which < 33) {
return true;
}
input = String.fromCharCode(e.which);
return !!/[\d\s]/.test(input);
}
In additional to the popular K8s, jasypt or vault solutions, there's also Karmahostage. It enables you to do:
@EncryptedValue("${application.secret}")
private String application;
It works the same way jasypt does, but encryption happens on a dedicated saas solution, with a more fine-grained ACL model attached to it.
I solved this problem using Bootstrap 4 Emdeds Utilities
https://getbootstrap.com/docs/4.3/utilities/embed
In this case you just need to add you image to a div.embbed-responsive
like this:
<div class="card">
<div class="embed-responsive embed-responsive-16by9">
<img alt="Card image cap" class="card-img-top embed-responsive-item" src="img/butterPecan.jpg" />
</div>
<div class="card-block">
<h4 class="card-title">Butter Pecan</h4>
<p class="card-text">Roasted pecans, butter and vanilla come together to make this wonderful ice cream</p>
</div>
</div>
All images will fit the ratio specified by modifier classes:
.embed-responsive-21by9
.embed-responsive-16by9
.embed-responsive-4by3
.embed-responsive-1by1
Aditionally this css enables zoom instead of image stretching
.embed-responsive .card-img-top {
object-fit: cover;
}
To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
transform(itemList: any, searchKeyword: string) {
if (!itemList)
return [];
if (!searchKeyword)
return itemList;
let filteredList = [];
if (itemList.length > 0) {
searchKeyword = searchKeyword.toLowerCase();
itemList.forEach(item => {
//Object.values(item) => gives the list of all the property values of the 'item' object
let propValueList = Object.values(item);
for(let i=0;i<propValueList.length;i++)
{
if (propValueList[i]) {
if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
{
filteredList.push(item);
break;
}
}
}
});
}
return filteredList;
}
}
//Usage
//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>
Don't forget to import the pipe in the app module
We might need to customize the logic to filer with dates.
for php7 you can do that:
sudo apt-get install php-gd php-xml php7.0-mbstring
Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
@Zim provided a great solution above (well deserved up-vote from me), however, it didn't quite fit what I needed since I was implementing this in Jekyll and wanted my card deck to automatically update every time I added a post to my site. Growing a card deck such as this with each new post is straight forward in Jekyll, the challenge was to correctly place the breakpoints. My solution make use of additional liquid tags and modulo mathematics.
While this question is old, I came across it and found it useful, and maybe someday someone will come along wanting to do this with Jekyll.
<div class = "container">
<div class = "card-deck">
{% for post in site.posts %}
<div class = "card border-0 mt-2">
<a href = "{{ post.url }}"><img src = "{{ site.baseurl }}{{ post.image }}" class = "mx-auto" alt = "..."></a>
<div class = "card-body">
<h5 class = "card-title"><a href = "{{ post.url }}">{{ post.title }}</a></h5>
<span>Published: {{ post.date | date_to_long_string }} </span>
<p class = "text-muted">{{ post.excerpt }}</p>
</div>
<div class = "card-footer bg-white border-0"><a href = "{{ post.url }}" class = "btn btn-primary">Read more</a></div>
</div>
<!-- Use modulo to add divs to handle break points -->
{% assign sm = forloop.index | modulo: 2 %}
{% assign md = forloop.index | modulo: 3 %}
{% assign lg = forloop.index | modulo: 4 %}
{% assign xl = forloop.index | modulo: 5 %}
{% if sm == 0 %}
<div class="w-100 d-none d-sm-block d-md-none"><!-- wrap every 2 on sm--></div>
{% endif %}
{% if md == 0 %}
<div class="w-100 d-none d-md-block d-lg-none"><!-- wrap every 3 on md--></div>
{% endif %}
{% if lg == 0 %}
<div class="w-100 d-none d-lg-block d-xl-none"><!-- wrap every 4 on lg--></div>
{% endif %}
{% if xl == 0 %}
<div class="w-100 d-none d-xl-block"><!-- wrap every 5 on xl--></div>
{% endif %}
{% endfor %}
</div>
</div>
This whole code block can be used directly in a website or saved in your Jekyll project _includes
folder.
I am using Eclipse mars, Hibernate 5.2.1, Jdk7 and Oracle 11g.
I get the same error when I run Hibernate code generation tool. I guess it is a versions issue due to I have solved it through choosing Hibernate version (5.1 to 5.0) in the type frame in my Hibernate console configuration.
For mysql 8.0.7, Go to your mysql directory, and then use:
sudo bin/mysql_secure_installation
to configure the password option.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
I've frequently used this pattern to extend the core behavior of Ruby to make it easier to deal with converting arbitrary data types to boolean values, which makes it really easy to deal with varying URL parameters, etc.
class String
def to_boolean
ActiveRecord::Type::Boolean.new.cast(self)
end
end
class NilClass
def to_boolean
false
end
end
class TrueClass
def to_boolean
true
end
def to_i
1
end
end
class FalseClass
def to_boolean
false
end
def to_i
0
end
end
class Integer
def to_boolean
to_s.to_boolean
end
end
So let's say you have a parameter foo
which can be:
Instead of using a bunch of conditionals, you can just call foo.to_boolean
and it will do the rest of the magic for you.
In Rails, I add this to an initializer named core_ext.rb
in nearly all of my projects since this pattern is so common.
## EXAMPLES
nil.to_boolean == false
true.to_boolean == true
false.to_boolean == false
0.to_boolean == false
1.to_boolean == true
99.to_boolean == true
"true".to_boolean == true
"foo".to_boolean == true
"false".to_boolean == false
"TRUE".to_boolean == true
"FALSE".to_boolean == false
"0".to_boolean == false
"1".to_boolean == true
true.to_i == 1
false.to_i == 0
In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:
tasks:
- shell: echo $(cat /etc/issue | awk {'print $7'})
register: echo_content
- shell: echo "It works"
when: echo_content.stdout == "12"
register: out
- debug: var=out.stdout_lines
Try this
Option Explicit
Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long
myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs
Set uniqueRng = GetUniqueValues(ws, myCol)
End Sub
Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long
With ws
.Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo
firstRow = 1
If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row
Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With
End Function
it should be quite fast and without the drawback NeepNeepNeep told about
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
This is a more efficient version of the solution from @Kramb. The existence check is redundant as the update where clause already handles this. Instead you just grab the rowcount and compare to batchsize.
Also note @Kramb solution didn't filter out already updated rows from the next iteration hence it would be an infinite loop.
Also uses the modern batch size syntax instead of using rowcount.
DECLARE @batchSize INT, @rowsUpdated INT
SET @batchSize = 1000;
SET @rowsUpdated = @batchSize; -- Initialise for the while loop entry
WHILE (@batchSize = @rowsUpdated)
BEGIN
UPDATE TOP (@batchSize) TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 and Value <> 'abc1';
SET @rowsUpdated = @@ROWCOUNT;
END
You can either put the classes on the "row" or the "column"? Won't be visible on the cards (border) if you use it on the row. https://v4-alpha.getbootstrap.com/utilities/flexbox/#align-items
<div class="container">
<div class="row">
<div class="col-lg-4 d-flex align-items-stretch">
Some of the other answers here seem 'wacky'. Why would use a min-height or even worse a fixed height?
I thought this issue (equal heights) was part of the reason for progression away from floating block divs?
This is a fast solution with a temporary object.
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
empid = [1, 4, 5],_x000D_
object = {},_x000D_
result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"
For a more web-like feel:
const B = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>
This is what I did to solve my problem. I tested in local MySQL 5.7 ubuntu 18.04.
set global sql_mode="NO_ENGINE_SUBSTITUTION";
Before running this query globally I added a cnf file in /etc/mysql/conf.d directory. The cnf file name is mysql.cnf and codes
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ALLOW_INVALID_DATES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Then I restart mysql
sudo service mysql restart
Hope this can help someone.
There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.
I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:
I solved it by rewriting package.json
with the exact values warnings were about.
Warnings when running npm
:
npm WARN [email protected] requires a peer of es6-shim@^0.33.3 but none was installed.
npm WARN [email protected] requires a peer of [email protected]
In package.json
, write
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
Then, delete node_modules
directory.
Finally, run the command below:
npm install
This worked for me.
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
Use these plugins to optimize your production build:
new webpack.optimize.CommonsChunkPlugin('common'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
})
Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
you should install a x server such as XMing. and keep the x server is running. config your putty like this :Connection-Data-SSH-X11-Enable X11 forwarding should be checked. and X display location : localhost:0
How to set the python version back to 2.7 if you have installed Anaconda3 (Python 3.6) on MacOS High Sierra 10.13.5
Edit the .bash_profile file in your home directory.
vi $HOME/.bash_profile
hash out the line # export PATH="/Users/YOURUSERNAME/anaconda3/bin:$PATH"
Close the shell open again you should see 2.7 when you run python.
Then if you want 3.6 you can simply uncomment your anaconda3 line in your bash profile.
Trying to unlink python will end in tears in Mac OSX.
You will something like this
unlink: /usr/bin/python: Operation not permitted
Hope that helps someone out !! :) :)
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
(Can't comment, not enough reputation, but here is a modified version that worked for me)
To @HamedMP error about the No default session is registered
you can use InteractiveSession
to get rid of this error:
https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession
And to @NumesSanguis issue with Image.show
, you can use the regular PIL .show()
method because fromarray
returns an image object.
I do both below (note I'm using JPEG instead of PNG):
import tensorflow as tf
import numpy as np
from PIL import Image
filename_queue = tf.train.string_input_producer(['my_img.jpg']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.
init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
Resetting the password will only solve the problem temporarily. From MySQL 5.7.4 to 5.7.10 (to encourage better security - see MySQL: Password Expiration Policy) the default default_password_lifetime
variable value is 360 (1 year-ish). For those versions, if you make no changes to this variable (or to individual user accounts) all passwords expire after 360 days.
So from a script you might get the message: "Your password has expired. To log in you must change it using a client that supports expired passwords."
To stop automatic password expiry, log in as root (mysql -u root -p
), then, for clients that automatically connect to the server (e.g. scripts.) change password expiration settings:
ALTER USER 'script'@'localhost' PASSWORD EXPIRE NEVER;
OR you can disable automatic password expiration for all users:
SET GLOBAL default_password_lifetime = 0;
As pointed out by Mertaydin in the comments, to make this permanent add the following line to a my.cnf
file MySQL reads on startup, under the [mysqld]
group of settings. The location of my.cnf
depends on your setup (e.g. Windows, or Homebrew on OS X, or an installer), and whether you want this per-user on Unix or global:
[mysqld]
default_password_lifetime = 0
(There may be other settings here too...)
See the MySQL docs on configuration files.
There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype
Therefore you need only query for NOT TRUE:
SELECT * from table_name WHERE boolean_column IS NOT TRUE;
There are several decisions to make:
The first about resource path:
Model the image as a resource on its own:
Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly
In the root path (/image):
The client is held responsible for establishing the relationship between the image and the user, or;
If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.
Embed the image as part of the user
The second decision is about how to represent the image resource:
This would be my decision track:
Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.
My choice Base64:
Use Mysql
default CURDATE
function to get all the records of the day.
$records = DB::table('users')->select(DB::raw('*'))
->whereRaw('Date(created_at) = CURDATE()')->get();
dd($record);
Note
The difference between Carbon::now
vs Carbon::today
is just time.
e.g
Date printed through Carbon::now
will look like something:
2018-06-26 07:39:10.804786 UTC (+00:00)
While with Carbon::today
:
2018-06-26 00:00:00.0 UTC (+00:00)
To get the only records created today with now
can be fetched as:
Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();
while with today
:
Post::whereDate('created_at', Carbon::today())->get();
UPDATE
As of laravel 5.3, We have default where clause
whereDate / whereMonth / whereDay / whereYear
$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();
OR with DB
facade
$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();
Usage of the above listed where clauses
$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
For me, this was an issue with cyclic dependencies.
IOW, module A required module B, and module B required module A.
So in module B, require('./A')
is an empty object rather than a function.
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
It is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later this creates problems when we reconfigure another version of NodeJS and its modules.
To remove the files, run the following commands:
sudo rm -rf /usr/local/bin/npm
sudo rm -rf /usr/local/share/man/man1/node*
sudo rm -rf /usr/local/lib/dtrace/node.d
rm -rf ~/.npm
rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf /opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*
I have posted a step by step guide with commands on my blog: AMCOS IT Support For Windows and Linux: To completely uninstall node js from Ubuntu.
A note for others who may be using Owl Carousel v 1.3.2:
You can replace the navigation text in the settings where you're enabling the navigation.
navigation:true,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.
int i = 0;
bool bi = !!i;
int j = 1;
bool bj = !!j;
A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.
For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".
A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).
Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.
But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button).
You need to modify the Starter-Application class as shown below.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages="com.nice.application")
@EnableJpaRepositories("com.spring.app.repository")
public class InventoryApp extends SpringBootServletInitializer {..........
And update the Controller, Service and Repository packages structure as I mentioned below.
Example: REST-Controller
package com.nice.controller;
--> It has to be modified as
package com.nice.application.controller;
You need to follow proper package structure for all packages which are in Spring Boot MVC flow.
So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.
# Let's add key:value to a dictionary, the functional way
# Create your dictionary class
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
c += 1
print(dict_obj)
I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"
This will fix your connection to your database.
This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.
I hope this helps you out.
:)
Bitcode is a new feature of iOS 9
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Note: For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required
So you should disabled bitcode until all the frameworks of your app have bitcode enabled.
You can simply read each line from the file and assign it to an array.
#!/bin/bash
i=0
while read line
do
arr[$i]="$line"
i=$((i+1))
done < file.txt
change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/
As you can't import a .txt file, I would suggest to read words this way.
list_ = open("world.txt").read().split()
Is it good to use async action everywhere in ASP.NET MVC?
It's good to do so wherever you can use an async method especially when you have performance issues at the worker process level which happens for massive data and calculation operations. Otherwise, no need because unit testing will need casting.
Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?
Yes, it's better to use async for any DB operation as could as possible to avoid performance issues at the level of worker processes. Note that EF has created many async alternatives for most operations, such as:
.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()
How many times can I use await keywords to query the database asynchronously in one single action method?
The sky is the limit
For Amazon AWS ECS/ECR, you should manage your environment variables (especially secrets) via a private S3 bucket. See blog post How to Manage Secrets for Amazon EC2 Container Service–Based Applications by Using Amazon S3 and Docker.
BATCH LOAD - OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)
$apikey = "whatever-us99";
$list_id = "12ab34dc56";
$email1 = "[email protected]";
$fname1 = "Jack";
$lname1 = "Black";
$email2 = "[email protected]";
$fname2 = "Jill";
$lname2 = "Hill";
$auth = base64_encode( 'user:'.$apikey );
$data1 = array(
"apikey" => $apikey,
"email_address" => $email1,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname1,
'LNAME' => $lname1,
)
);
$data2 = array(
"apikey" => $apikey,
"email_address" => $email2,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname2,
'LNAME' => $lname2,
)
);
$json_data1 = json_encode($data1);
$json_data2 = json_encode($data2);
$array = array(
"operations" => array(
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data1
),
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data2
)
)
);
$json_post = json_encode($array);
$ch = curl_init();
$curlopt_url = "https://us99.api.mailchimp.com/3.0/batches";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post);
print_r($json_post . "\n");
$result = curl_exec($ch);
var_dump($result . "\n");
print_r ($result . "\n");
For Mysql8->
Query:
SELECT properties, properties->"$.price" FROM book where isbn='978-9730228236' and JSON_EXTRACT(properties, "$.price") > 400;
Data:
mysql> select * from book\G;
*************************** 1. row ***************************
id: 1
isbn: 978-9730228236
properties: {"price": 44.99, "title": "High-Performance Java Persistence", "author": "Vlad Mihalcea", "publisher": "Amazon"}
1 row in set (0.00 sec)
in my case it didn't work like following
@Query("select count(e)>0 from MyEntity e where ...")
You can return it as boolean value with following
@Query(value = "SELECT CASE WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")
Not the best way to error log, but you can always set everything to an array for the promiseAll, and store the resulting results into new variables.
If you use graphQL you need to postprocess the response regardless and if it doesn't find the correct reference it'll crash the app, narrowing down where the problem is at
const results = await Promise.all([
this.props.client.query({
query: GET_SPECIAL_DATES,
}),
this.props.client.query({
query: GET_SPECIAL_DATE_TYPES,
}),
this.props.client.query({
query: GET_ORDER_DATES,
}),
]).catch(e=>console.log(e,"error"));
const specialDates = results[0].data.specialDates;
const specialDateTypes = results[1].data.specialDateTypes;
const orderDates = results[2].data.orders;
I've tried this:
<a href="whatsapp://send?abid=phonenumber&text=Hello%2C%20World!">whatsapp</a>
changing 'phonenumber' into a specific phonenumber. This doesn't work completely, but when they click on the link it does open whatsapp and if they click on a contact the message is filled in.
If you want to open a specific person in chat you can, but without text filled in.
<a href="intent://send/phonenumber#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">test</a>
You'll probably have to make a choice between the two.
some links to help you Sharing link on WhatsApp from mobile website (not application) for Android https://www.whatsapp.com/faq/nl/android/28000012
Hope this helps
(I tested this with google chrome on an android phone)
There is a distinct lack of discussion on backwards and forwards compatibility that is built in to PHP's password functions. Notably:
crypt()
, and are inherently backwards-compatible with crypt()
-format hashes, even if they use obsolete and/or insecure hash algorithms.password_needs_rehash()
and a bit of logic into your authentication workflow can keep you your hashes up to date with current and future algorithms with potentially zero future changes to the workflow. Note: Any string that does not match the specified algorithm will be flagged for needing a rehash, including non-crypt-compatible hashes.Eg:
class FakeDB {
public function __call($name, $args) {
printf("%s::%s(%s)\n", __CLASS__, $name, json_encode($args));
return $this;
}
}
class MyAuth {
protected $dbh;
protected $fakeUsers = [
// old crypt-md5 format
1 => ['password' => '$1$AVbfJOzY$oIHHCHlD76Aw1xmjfTpm5.'],
// old salted md5 format
2 => ['password' => '3858f62230ac3c915f300c664312c63f', 'salt' => 'bar'],
// current bcrypt format
3 => ['password' => '$2y$10$3eUn9Rnf04DR.aj8R3WbHuBO9EdoceH9uKf6vMiD7tz766rMNOyTO']
];
public function __construct($dbh) {
$this->dbh = $dbh;
}
protected function getuser($id) {
// just pretend these are coming from the DB
return $this->fakeUsers[$id];
}
public function authUser($id, $password) {
$userInfo = $this->getUser($id);
// Do you have old, turbo-legacy, non-crypt hashes?
if( strpos( $userInfo['password'], '$' ) !== 0 ) {
printf("%s::legacy_hash\n", __METHOD__);
$res = $userInfo['password'] === md5($password . $userInfo['salt']);
} else {
printf("%s::password_verify\n", __METHOD__);
$res = password_verify($password, $userInfo['password']);
}
// once we've passed validation we can check if the hash needs updating.
if( $res && password_needs_rehash($userInfo['password'], PASSWORD_DEFAULT) ) {
printf("%s::rehash\n", __METHOD__);
$stmt = $this->dbh->prepare('UPDATE users SET pass = ? WHERE user_id = ?');
$stmt->execute([password_hash($password, PASSWORD_DEFAULT), $id]);
}
return $res;
}
}
$auth = new MyAuth(new FakeDB());
for( $i=1; $i<=3; $i++) {
var_dump($auth->authuser($i, 'foo'));
echo PHP_EOL;
}
Output:
MyAuth::authUser::password_verify
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$zNjPwqQX\/RxjHiwkeUEzwOpkucNw49yN4jjiRY70viZpAx5x69kv.",1]])
bool(true)
MyAuth::authUser::legacy_hash
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$VRTu4pgIkGUvilTDRTXYeOQSEYqe2GjsPoWvDUeYdV2x\/\/StjZYHu",2]])
bool(true)
MyAuth::authUser::password_verify
bool(true)
As a final note, given that you can only re-hash a user's password on login you should consider "sunsetting" insecure legacy hashes to protect your users. By this I mean that after a certain grace period you remove all insecure [eg: bare MD5/SHA/otherwise weak] hashes and have your users rely on your application's password reset mechanisms.
The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
@foreach($datas as $student)
{{$student}}
@endforeach
[Link here]
@inmyth's answer is correct, just modify the code a bit, to handle empty list.
public class NewsAdapter extends RecyclerView.Adapter<...> {
...
private static List mFeedsList;
...
public void swap(List list){
if (mFeedsList != null) {
mFeedsList.clear();
mFeedsList.addAll(list);
}
else {
mFeedsList = list;
}
notifyDataSetChanged();
}
I am using Retrofit to fetch the list, on Retrofit's onResponse() use,
adapter.swap(feedList);
TL;DR ...and late to the party, but that short explanation might help future googlers..
In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.
A minimal example:
df <- data.frame(a = 1:2); df$a <- 1:3
throws the error
Error in
$<-.data.frame
(*tmp*
, a, value = 1:3) : replacement has 3 rows, data has 2
which is clear, because the vector a
of df
has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).
I know it's an old question, but I needed this solution too, and I acme with another solution.
I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:
HOST=`hostname --fqdn`
Then, I used it across my entrypoint script:
echo "Value: $HOST"
Hope this helps
you can use UILabel
instead if you don't want the user to be able to modify anything in your UITextField
A programmatic solution would be to use enabled
property:
yourTextField.enabled = false
A way to do it in a storyboard:
Uncheck the Enabled checkbox in the properties of your UITextField
In my case the problem was that my application had literally no information filled in the App Store Connect
Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below
public class ProductsController : Controller
{
// GET: Products
public async Task<ActionResult> Index()
{
string apiUrl = "http://localhost:58764/api/values";
using (HttpClient client=new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);
}
}
return View();
}
}
Just use arr.slice(startingIndex, endingIndex)
.
If you do not specify the endingIndex
, it returns all the items starting from the index provided.
In your case arr=arr.slice(1)
.
res
is an HttpResponse object which extends from OutgoingMessage. res.send
calls res.end
which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here
You can use Redirect instead of DefaultRoute
<Redirect from="/" to="searchDashboard" />
Update 2019-08-09 to avoid problem with refresh use this instead, thanks to Ogglas
<Redirect exact from="/" to="searchDashboard" />
Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.
Think of Dockerfile
as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:
/var/www
)By contrast, think of docker-compose.yml
as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,
(This is not a precise explanation but good enough to start with.)
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
Just activate the curl in the php.ini file
;extension=php_curl.dll
to
extension=php_curl.dll
and then composer install
Pandas will recognise a value as null if it is a np.nan
object, which will print as NaN
in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan
objects using replace()
, and then call dropna()
on your DataFrame to delete rows with null tenants.
To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants
column:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
Now we replace any empty strings in the Tenants
column with np.nan
objects, like so:
>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
Now we can drop the null values:
>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
You can use the external library StatusBarUtil:
Add to your module level build.gradle
:
compile 'com.jaeger.statusbarutil:library:1.4.0'
Then you can use the following util for an Activity to make the status bar transparent:
StatusBarUtil.setTransparent(Activity activity)
Example:
I was also struggling with the same problem. I had actually deleted the class and rebuilt it. Someone, the storyboard had dropped the link between prototype cell and the identifier.
I deleted the identifier name and re-typed the identifier name again.
It worked.
To check an ajax request you can use if (Request::ajax())
Note: If you are using laravel 5, then in the controller replace
use Illuminate\Http\Request;
with
use Request;
I hope it'll work.
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
Another option would be using flexbox.
While it's not supported by IE8 and IE9, you could consider:
Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
width: 100%;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
background-color: #4C4;_x000D_
min-height: 50px;_x000D_
width: 100%;_x000D_
}_x000D_
footer {_x000D_
background-color: #4C4;_x000D_
min-height: 30px;_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
JLRishe's answer is correct, so I simply use this in my event handler:
if (event.target instanceof Element) { /*...*/ }
One of the problems that can cause this is when you forget to put the / character in the WebServlet annotation @WebServlet("/example") @WebServlet("example") I hope it works, it worked for me.
That's working for me in Kotlin.
class LEDRecyclerAdapter (var currentPole: Pole): RecyclerView.Adapter<RecyclerView.ViewHolder>() { ... }
adapter.currentPole = pole
adapter.notifyDataSetChanged()
The scroll offset doesn't change.
As indicated in Elasticsearch reference for snapshot module,
The rename_pattern and rename_replacement options can be also used to rename index on restore using regular expression
You can use the Postman interceptor.That you can add into the chrome extension by this link:https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo
This helps you send requests which use browser cookies through the Postman app. It can also send headers which are normally restricted by Chrome but are critical for testing APIs.
And also you can enable by interceptor which is there beside the orange sync icon
From "Find duplicate rows with PostgreSQL" here's smart solution:
select * from (
SELECT id,
ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
FROM tbl
) dups
where
dups.Row > 1
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
This issue might also be caused by a broken Maven repository.
I observe the SEVERE: A child container failed during start
message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml
files), Eclipse starts downloading libraries specified in pom.xml
into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.
So, this is how you could resolve the issue.
rm -rf $HOME/.m2
).mvn package
in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.check if you already added the view
if (textView.getParent() == null)
layout.addView(textView);
In addition to the other answers, a further example of the variability of word size (from one system to the next) is in the paper Smashing The Stack For Fun And Profit by Aleph One:
We must remember that memory can only be addressed in multiples of the word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer is going to take 12 bytes (3 words) of memory.
change below line of code
spring.datasource.driverClassName
to
spring.datasource.driver-class-name
Remember to set the locale to en_US_POSIX
as described in Technical Q&A1480. In Swift 3:
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
print(formatter.string(from: date))
The issue is that if you're on a device which is using a non-Gregorian calendar, the year will not conform to RFC3339/ISO8601 unless you specify the locale
as well as the timeZone
and dateFormat
string.
Or you can use ISO8601DateFormatter
to get you out of the weeds of setting locale
and timeZone
yourself:
let date = Date()
let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds) // this is only available effective iOS 11 and macOS 10.13
print(formatter.string(from: date))
For Swift 2 rendition, see previous revision of this answer.
Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.
Have you considered using factory functions? They usually are a much better alternative to classes or constructor functions in Javascript. Here is an example of how it works:
function car () {
var privateVariable = 4
function privateFunction () {}
return {
color: 'red',
drive: function (miles) {},
stop: function() {}
....
}
}
Thanks to closures you have access to all private functions and variabels inside the returned object, but you can not access them from outside.
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
You cannot.
However, you may want to have a look at one of my projects which allows you to more easily manipulate such "throwing lambdas".
In your case, you would be able to do that:
import static com.github.fge.lambdas.functions.Functions.wrap;
final ThrowingFunction<String, Class<?>> f = wrap(Class::forName);
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(f.orThrow(MyException.class))
.collect(Collectors.toList());
and catch MyException
.
That is one example. Another example is that you could .orReturn()
some default value.
Note that this is STILL a work in progress, more is to come. Better names, more features etc.
sometimes this error came beacause failed to compile in middlest of any build. The best way to try is by doing make clean and again make the whole code .
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
Comparison between different approaches in swift 3.0
1. Sleep
This method does not have a call back. Put codes directly after this line to be executed in 4 seconds. It will stop user from iterating with UI elements like the test button until the time is gone. Although the button is kind of frozen when sleep kicks in, other elements like activity indicator is still spinning without freezing. You cannot trigger this action again during the sleep.
sleep(4)
print("done")//Do stuff here
2. Dispatch, Perform and Timer
These three methods work similarly, they are all running on the background thread with call backs, just with different syntax and slightly different features.
Dispatch is commonly used to run something on the background thread. It has the callback as part of the function call
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
print("done")
})
Perform is actually a simplified timer. It sets up a timer with the delay, and then trigger the function by selector.
perform(#selector(callback), with: nil, afterDelay: 4.0)
func callback() {
print("done")
}}
And finally, timer also provides ability to repeat the callback, which is not useful in this case
Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(callback), userInfo: nil, repeats: false)
func callback() {
print("done")
}}
For all these three method, when you click on the button to trigger them, UI will not freeze and you are allowed to click on it again. If you click on the button again, another timer is set up and the callback will be triggered twice.
In conclusion
None of the four method works good enough just by themselves. sleep
will disable user interaction, so the screen "freezes"(not actually) and results bad user experience. The other three methods will not freeze the screen, but you can trigger them multiple times, and most of the times, you want to wait until you get the call back before allowing user to make the call again.
So a better design will be using one of the three async methods with screen blocking. When user click on the button, cover the entire screen with some translucent view with a spinning activity indicator on top, telling user that the button click is being handled. Then remove the view and indicator in the call back function, telling user that the the action is properly handled, etc.
I am going to use a very simple snippet to illustrate the difference:
test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']
The DataFrame looks like this:
id price
0 1 1
1 2 2
2 3 3
3 1 2
4 2 3
5 3 1
6 1 3
7 2 1
8 3 2
There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.
Now, I want to find the minimum payment made by each customer. There are two ways of doing it:
Using apply
:
grouping.min()
The return looks like this:
id
1 1
2 1
3 1
Name: price, dtype: int64
pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
Using transform
:
grouping.transform(min)
The return looks like this:
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
Name: price, dtype: int64
pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9
Both methods return a Series
object, but the length
of the first one is 3 and the length
of the second one is 9.
If you want to answer What is the minimum price paid by each customer
, then the apply
method is the more suitable one to choose.
If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment
, then you want to use transform
, because:
test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row
Apply
does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.
Below query is appropriate for the last 30 days records
Here, I have used a review table and review_date
is a column from the review table
SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY
Here is the c# version for mono android
/*
* Ported by Jagadeesh Govindaraj (@jaganjan)
*Copyright 2015 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Contact details
*
* Email: se.solovyev @gmail.com
* Site: http://se.solovyev.org
*/
using Android.Content;
using Android.Graphics;
using Android.Support.V4.View;
using Android.Support.V7.Widget;
using Android.Util;
using Android.Views;
using Java.Lang;
using Java.Lang.Reflect;
using System;
using Math = Java.Lang.Math;
namespace Droid.Helper
{
public class WrapLayoutManager : LinearLayoutManager
{
private const int DefaultChildSize = 100;
private static readonly Rect TmpRect = new Rect();
private int _childSize = DefaultChildSize;
private static bool _canMakeInsetsDirty = true;
private static readonly int[] ChildDimensions = new int[2];
private const int ChildHeight = 1;
private const int ChildWidth = 0;
private static bool _hasChildSize;
private static Field InsetsDirtyField = null;
private static int _overScrollMode = ViewCompat.OverScrollAlways;
private static RecyclerView _view;
public WrapLayoutManager(Context context, int orientation, bool reverseLayout)
: base(context, orientation, reverseLayout)
{
_view = null;
}
public WrapLayoutManager(Context context) : base(context)
{
_view = null;
}
public WrapLayoutManager(RecyclerView view) : base(view.Context)
{
_view = view;
_overScrollMode = ViewCompat.GetOverScrollMode(view);
}
public WrapLayoutManager(RecyclerView view, int orientation, bool reverseLayout)
: base(view.Context, orientation, reverseLayout)
{
_view = view;
_overScrollMode = ViewCompat.GetOverScrollMode(view);
}
public void SetOverScrollMode(int overScrollMode)
{
if (overScrollMode < ViewCompat.OverScrollAlways || overScrollMode > ViewCompat.OverScrollNever)
throw new ArgumentException("Unknown overscroll mode: " + overScrollMode);
if (_view == null) throw new ArgumentNullException(nameof(_view));
_overScrollMode = overScrollMode;
ViewCompat.SetOverScrollMode(_view, overScrollMode);
}
public static int MakeUnspecifiedSpec()
{
return View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
}
public override void OnMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec,
int heightSpec)
{
var widthMode = View.MeasureSpec.GetMode(widthSpec);
var heightMode = View.MeasureSpec.GetMode(heightSpec);
var widthSize = View.MeasureSpec.GetSize(widthSpec);
var heightSize = View.MeasureSpec.GetSize(heightSpec);
var hasWidthSize = widthMode != MeasureSpecMode.Unspecified;
var hasHeightSize = heightMode != MeasureSpecMode.Unspecified;
var exactWidth = widthMode == MeasureSpecMode.Exactly;
var exactHeight = heightMode == MeasureSpecMode.Exactly;
var unspecified = MakeUnspecifiedSpec();
if (exactWidth && exactHeight)
{
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
base.OnMeasure(recycler, state, widthSpec, heightSpec);
return;
}
var vertical = Orientation == Vertical;
InitChildDimensions(widthSize, heightSize, vertical);
var width = 0;
var height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter
// entities. This happens because their invalidation happens after "onMeasure" method.
// As a workaround let's clear the recycler now (it should not cause any performance
// issues while scrolling as "onMeasure" is never called whiles scrolling)
recycler.Clear();
var stateItemCount = state.ItemCount;
var adapterItemCount = ItemCount;
// adapter always contains actual data while state might contain old data (f.e. data
// before the animation is done). As we want to measure the view with actual data we
// must use data from the adapter and not from the state
for (var i = 0; i < adapterItemCount; i++)
{
if (vertical)
{
if (!_hasChildSize)
{
if (i < stateItemCount)
{
// we should not exceed state count, otherwise we'll get
// IndexOutOfBoundsException. For such items we will use previously
// calculated dimensions
MeasureChild(recycler, i, widthSize, unspecified, ChildDimensions);
}
else
{
LogMeasureWarning(i);
}
}
height += ChildDimensions[ChildHeight];
if (i == 0)
{
width = ChildDimensions[ChildWidth];
}
if (hasHeightSize && height >= heightSize)
{
break;
}
}
else
{
if (!_hasChildSize)
{
if (i < stateItemCount)
{
// we should not exceed state count, otherwise we'll get
// IndexOutOfBoundsException. For such items we will use previously
// calculated dimensions
MeasureChild(recycler, i, unspecified, heightSize, ChildDimensions);
}
else
{
LogMeasureWarning(i);
}
}
width += ChildDimensions[ChildWidth];
if (i == 0)
{
height = ChildDimensions[ChildHeight];
}
if (hasWidthSize && width >= widthSize)
{
break;
}
}
}
if (exactWidth)
{
width = widthSize;
}
else
{
width += PaddingLeft + PaddingRight;
if (hasWidthSize)
{
width = Math.Min(width, widthSize);
}
}
if (exactHeight)
{
height = heightSize;
}
else
{
height += PaddingTop + PaddingBottom;
if (hasHeightSize)
{
height = Math.Min(height, heightSize);
}
}
SetMeasuredDimension(width, height);
if (_view == null || _overScrollMode != ViewCompat.OverScrollIfContentScrolls) return;
var fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.SetOverScrollMode(_view, fit ? ViewCompat.OverScrollNever : ViewCompat.OverScrollAlways);
}
private void LogMeasureWarning(int child)
{
#if DEBUG
Log.WriteLine(LogPriority.Warn, "LinearLayoutManager",
"Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #SetChildSize() method or don't run RecyclerView animations");
#endif
}
private void InitChildDimensions(int width, int height, bool vertical)
{
if (ChildDimensions[ChildWidth] != 0 || ChildDimensions[ChildHeight] != 0)
{
// already initialized, skipping
return;
}
if (vertical)
{
ChildDimensions[ChildWidth] = width;
ChildDimensions[ChildHeight] = _childSize;
}
else
{
ChildDimensions[ChildWidth] = _childSize;
ChildDimensions[ChildHeight] = height;
}
}
public void ClearChildSize()
{
_hasChildSize = false;
SetChildSize(DefaultChildSize);
}
public void SetChildSize(int size)
{
_hasChildSize = true;
if (_childSize == size) return;
_childSize = size;
RequestLayout();
}
private void MeasureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize,
int[] dimensions)
{
View child = null;
try
{
child = recycler.GetViewForPosition(position);
}
catch (IndexOutOfRangeException e)
{
Log.WriteLine(LogPriority.Warn, "LinearLayoutManager",
"LinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
if (child != null)
{
var p = child.LayoutParameters.JavaCast<RecyclerView.LayoutParams>()
var hPadding = PaddingLeft + PaddingRight;
var vPadding = PaddingTop + PaddingBottom;
var hMargin = p.LeftMargin + p.RightMargin;
var vMargin = p.TopMargin + p.BottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
MakeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
CalculateItemDecorationsForChild(child, TmpRect);
var hDecoration = GetRightDecorationWidth(child) + GetLeftDecorationWidth(child);
var vDecoration = GetTopDecorationHeight(child) + GetBottomDecorationHeight(child);
var childWidthSpec = GetChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.Width,
CanScrollHorizontally());
var childHeightSpec = GetChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.Height,
CanScrollVertically());
child.Measure(childWidthSpec, childHeightSpec);
dimensions[ChildWidth] = GetDecoratedMeasuredWidth(child) + p.LeftMargin + p.RightMargin;
dimensions[ChildHeight] = GetDecoratedMeasuredHeight(child) + p.BottomMargin + p.TopMargin;
// as view is recycled let's not keep old measured values
MakeInsetsDirty(p);
}
recycler.RecycleView(child);
}
private static void MakeInsetsDirty(RecyclerView.LayoutParams p)
{
if (!_canMakeInsetsDirty)
{
return;
}
try
{
if (InsetsDirtyField == null)
{
var klass = Java.Lang.Class.FromType (typeof (RecyclerView.LayoutParams));
InsetsDirtyField = klass.GetDeclaredField("mInsetsDirty");
InsetsDirtyField.Accessible = true;
}
InsetsDirtyField.Set(p, true);
}
catch (NoSuchFieldException e)
{
OnMakeInsertDirtyFailed();
}
catch (IllegalAccessException e)
{
OnMakeInsertDirtyFailed();
}
}
private static void OnMakeInsertDirtyFailed()
{
_canMakeInsetsDirty = false;
#if DEBUG
Log.Warn("LinearLayoutManager",
"Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
#endif
}
}
}
Save the current product id before entering your loop:
$current_product = $product->id;
Then in your loop for your sidebar, use $product->id again to compare:
<li><a <? if ($product->id == $current_product) { echo "class='on'"; }?> href="<?=get_permalink();?>"><?=the_title();?></a></li>
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)
namespace App\Traits;
trait AppTraits
{
/**
* Create pivot array from given values
*
* @param array $entities
* @param array $pivots
* @return array combined $pivots
*/
public function combinePivot($entities, $pivots = [])
{
// Set array
$pivotArray = [];
// Loop through all pivot attributes
foreach ($pivots as $pivot => $value) {
// Combine them to pivot array
$pivotArray += [$pivot => $value];
}
// Get the total of arrays we need to fill
$total = count($entities);
// Make filler array
$filler = array_fill(0, $total, $pivotArray);
// Combine and return filler pivot array with data
return array_combine($entities, $filler);
}
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
use Traits\AppTraits;
// ...
}
Usage:
// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
'price' => 634,
'name' => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);
Swift 4
I think, there are two ways.
1. NSRange(range, in: )
2. NSRange(location:, length: )
Sample code:
let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])
// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample") {
attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}
// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}
Assuming that create_time contains the time the order was created, and you want the 100 clients with the latest orders, you can:
create_time desc
ROWNUM
Query:
SELECT * FROM (
SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc
) WHERE rownum <= 100
UPDATE for Oracle 12c
With release 12.1, Oracle introduced "real" Top-N queries. Using the new FETCH FIRST...
syntax, you can also use:
SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn = 1
ORDER BY create_time desc
FETCH FIRST 100 ROWS ONLY)
(MacOS) I got this issue after getting some malware that was forcing me to use WeKnow as a search engine. To fix this on MacOs I followed these steps
Go to System Preferences, then check if there's an icon named Profiles.
Remove AdminPrefs profile
Change default search engine settings, Restart Chrome
The above partially helped (I still had WeKnow as my home page). After that I followed these steps:
Type chrome://policy/ to see the policies. You cannot change them there
Copy paste this into your terminal
defaults write com.google.Chrome HomepageIsNewTabPage -bool false
defaults write com.google.Chrome NewTabPageLocation -string "https://www.google.com/"
defaults write com.google.Chrome HomepageLocation -string "https://www.google.com/"
defaults delete com.google.Chrome DefaultSearchProviderSearchURL
defaults delete com.google.Chrome DefaultSearchProviderNewTabURL
defaults delete com.google.Chrome DefaultSearchProviderName
I've also ran a scan of my system with Avast antivirus that has detected some malware
db.getCollection('orders').aggregate([
{$group: {
_id: {name: "$name"},
uniqueIds: {$addToSet: "$_id"},
count: {$sum: 1}
}
},
{$match: {
count: {"$gt": 1}
}
}
])
First Group Query the group according to the fields.
Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.
You cannot use WHILE
like that; see: mysql DECLARE WHILE outside stored procedure how?
You have to put your code in a stored procedure. Example:
CREATE PROCEDURE myproc()
BEGIN
DECLARE i int DEFAULT 237692001;
WHILE i <= 237692004 DO
INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
SET i = i + 1;
END WHILE;
END
Fiddle: http://sqlfiddle.com/#!2/a4f92/1
Alternatively, generate a list of INSERT
statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:
for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done
By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.
import UIKit
@IBDesignable
class RoundedButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 8
@IBInspectable var borderColor: UIColor? = .lightGray
override func draw(_ rect: CGRect) {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = borderColor?.cgColor
}
}
Yes: You can use Inner Join
to join on multiple columns.
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
E.FileNum = V.FileNum AND
E.ActivityNum = V.ActivityNum
Create table
CREATE TABLE MyNewTab(CaseNum int, FileNum int,
ActivityNum int, Grade int, Score varchar(100))
Insert values
INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score)
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
E.FileNum = V.FileNum AND
E.ActivityNum = V.ActivityNum
Set table-layout
to auto
and define an extreme width on .absorbing-column
.
Here I have set the width
to 100%
because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.
This is one of the quirky benefits of how tables behave. The table-layout: auto
algorithm is mathematically forgiving.
You may even choose to define a min-width
on all td
elements to prevent them from becoming too narrow and the table will behave nicely.
table {_x000D_
table-layout: auto;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
table td {_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
table .absorbing-column {_x000D_
width: 100%;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column A</th>_x000D_
<th>Column B</th>_x000D_
<th>Column C</th>_x000D_
<th class="absorbing-column">Column D</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data A.1 lorem</td>_x000D_
<td>Data B.1 ip</td>_x000D_
<td>Data C.1 sum l</td>_x000D_
<td>Data D.1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.2 ipsum</td>_x000D_
<td>Data B.2 lorem</td>_x000D_
<td>Data C.2 some data</td>_x000D_
<td>Data D.2 a long line of text that is long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.3</td>_x000D_
<td>Data B.3</td>_x000D_
<td>Data C.3</td>_x000D_
<td>Data D.3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
For Swift 5+
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let submodules = (
home: HomeRouter.createModule(),
search: SearchRouter.createModule(),
exoplanets: ExoplanetsRouter.createModule()
)
let tabBarController = TabBarModuleBuilder.build(usingSubmodules: submodules)
window.rootViewController = tabBarController
self.window = window
window.makeKeyAndVisible()
}
}
tl;dr (this tl;dr is from @sp00m's answer below)
$emit
dispatches an event upwards ...$broadcast
dispatches an event downwards
Detailed explanation
$rootScope.$emit
only lets other $rootScope
listeners catch it. This is good when you don't want every $scope
to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.
$rootScope.$broadcast
is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.
$scope.$emit
is when you want that $scope
and all its parents and $rootScope
to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).
$scope.$broadcast
is for the $scope
itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.
I want just emphasize that RecyclerView is a part of the compatibility package. It means that instead of using the feature and code from OS, every application carries own RecyclerView implementation. Potentially, a feature similar to RecyclerView can be a part of a future OS and using it from there can be beneficial. For example Harmony OS will be out soon.The compatibility package license can be changed in the future and it can be an implication. Summery of disadvantages:
But on a good note, an implementation of some functionality, as swiping items, is coming from RecyclerView.
All said above has to be taken in a consideration.
You don't seem to have the stopwords corpus on your computer.
You need to start the NLTK Downloader and download all the data you need.
Open a Python console and do the following:
>>> import nltk
>>> nltk.download()
showing info http://nltk.github.com/nltk_data/
In the GUI window that opens simply press the 'Download' button to download all corpora or go to the 'Corpora' tab and only download the ones you need/want.
I think the most correct way to get item position is
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override public void onClick(View v) {
View view = v;
View parent = (View) v.getParent();
while (!(parent instanceof RecyclerView)){
view=parent;
parent = (View) parent.getParent();
}
int position = recyclerView.getChildAdapterPosition(view);
}
Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);
Try to keep your files closer to the file system root. More details : for technical reasons, Git for Windows cannot create files or directories when the absolute path is longer than 260 characters.
instanceof
is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
Make sure that your div is set to runat="server", then simply reference it in the code-behind and set the "class" attribute.
<div runat="server" id="formSpinner">
...content...
</div>
Code-behind
formSpinner.Attributes["class"] = "class-name";
There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:
From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","[email protected]");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html
Like @g-eorge mention, you can make it like this:
module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);
You can also make as much as u need optional parameters.
Use either auto-fill
or auto-fit
as the first argument of the repeat()
notation.
<auto-repeat>
variant of the repeat()
notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When
auto-fill
is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.
auto-fit
The
auto-fit
keyword behaves the same asauto-fill
, except that after grid item placement any empty repeated tracks are collapsed.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0
.
A collapsed track is treated as having a fixed track sizing function of 0px
.
Unlike the auto-fill
image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.
auto-fill
vs auto-fit
The difference between the two is noticeable when the minmax()
function is used.
Use minmax(186px, 1fr)
to range the items from 186px
to a fraction of the leftover space in the grid container.
When using auto-fill
, the items will grow once there is no space to place empty tracks.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
When using auto-fit
, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px
.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
Playground:
Inspecting auto-fill tracks
Inspecting auto-fit tracks
I am using in the following case: In UI I got an action from a button, for eg. the user want to download an 500mb file. Thank I will initialize the background engine (AsyncTask class) and pass parameters to him. On the UI I will show a blocking progress dialog and disable the user to make any other clicks. The question is: when to remove the blocking from UI? the answer is: when the engine finished with success or fail, and that can be with callbacks or notifications.
What is the difference between notification and callbacks it is another question, but 1:1 is faster the callback.
Set a Tag on each button to whatever you want to work with, in this case probably an Integer. Then you need only one OnClickListener for all of your buttons:
Button one = (Button) findViewById(R.id.oneButton);
Button two = (Button) findViewById(R.id.twoButton);
one.setTag(new Integer(1));
two.setTag(new Integer(2));
OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView output = (TextView) findViewById(R.id.output);
output.append(v.getTag());
}
}
one.setOnClickListener(onClickListener);
two.setOnClickListener(onClickListener);
autoSize for column width set as bellow. It works for me.
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
…or a shorter try:
library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
On macOS, use subprocess.run
to pipe your text to pbcopy
:
import subprocess
data = "hello world"
subprocess.run("pbcopy", universal_newlines=True, input=data)
It will copy "hello world" to the clipboard.
adding on to t3chb0t's answer, not sure why the option to download is not visible, so created a patch for those who use GreaseMonkey/ TamperMonkey: you can find the gist code here
Or you can just paste the below lines in your browser console, and the link would magically appear:
let version = document.querySelector('.ux-table-metadata > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > div:nth-child(1)').innerText
, itemDetails = window.location.search.replace('?', '').split('&').filter(str => !str.indexOf('itemName')).map(str => str.split('=')[1])[0]
, [author, extension] = itemDetails.split('.')
, lAuthor = author.toLowerCase()
, href = `https://${lAuthor}.gallery.vsassets.io:443/_apis/public/gallery/publisher/${author}/extension/${extension}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage`
, element = document.createElement('a');
element.href = href;
element.className = 'vscode-moreinformation dark';
element.innerHTML = 'download .vsix file';
element.download = `${extension}.${version}.vsix`;
document.querySelector('.vscode-install-info-container').appendChild(element);
docker rm $(docker ps -a -q)
docker rmi $(docker images -q)
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
Below query will give accurate answer. Follow and give me comments:
select top 1 salary from (
select DISTINCT top 3 salary from Table(table name) order by salary ) as comp
order by personid salary
If you use Sass, there are Bootstrap variables are defined with !default
, among which you'll find font families. You can just set the variables in your own .scss
file before including the Bootstrap Sass file and !default
will not overwrite yours. Here's a good explanation of how !default
works: https://thoughtbot.com/blog/sass-default.
Here's an untested example using Bootstrap 4, npm, Gulp, gulp-sass and gulp-cssmin to give you an idea how you could hook this up together.
package.json
{
"devDependencies": {
"bootstrap": "4.0.0-alpha.6",
"gulp": "3.9.1",
"gulp-sass": "3.1.0",
"gulp-cssmin": "0.2.0"
}
}
mysite.scss
@import "./myvariables";
// Bootstrap
@import "bootstrap/scss/variables";
// ... need to include other bootstrap files here. Check node_modules\bootstrap\scss\bootstrap.scss for a list
_myvariables.scss
// For a list of Bootstrap variables you can override, look at node_modules\bootstrap\scss\_variables.scss
// These are the defaults, but you can override any values
$font-family-sans-serif: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !default;
$font-family-serif: Georgia, "Times New Roman", Times, serif !default;
$font-family-monospace: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
$font-family-base: $font-family-sans-serif !default;
gulpfile.js
var gulp = require("gulp"),
sass = require("gulp-sass"),
cssmin = require("gulp-cssmin");
gulp.task("transpile:sass", function() {
return gulp.src("./mysite.scss")
.pipe(sass({ includePaths: "./node_modules" }).on("error", sass.logError))
.pipe(cssmin())
.pipe(gulp.dest("./css/"));
});
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="mysite.css" />
</head>
<body>
...
</body>
</html>
you can also use awk
awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
To get rid of the outline when clicking, add outline:none
button {
background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
outline:none;
}
button {_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}
_x000D_
<button>button</button>
_x000D_
What I'm guessing is that you need to set those input elements to runat="server".
So you won't be able to access the control
<input type="text" name="email" id="myTextBox" />
But you'll be able to work with
<input type="text" name="email" id="myTextBox" runat="server" />
And read from it by using
string myStringFromTheInput = myTextBox.Value;
I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import
.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D
will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!
There are two obvious points, as well as the points in the other answer:
They are exactly equivalent when using sub queries:
SELECT * FROM table
WHERE column IN(subquery);
SELECT * FROM table
WHERE column = ANY(subquery);
On the other hand:
Only the IN
operator allows a simple list:
SELECT * FROM table
WHERE column IN(… , … , …);
Presuming they are exactly the same has caught me out several times when forgetting that ANY
doesn’t work with lists.
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:
apt-get install python-dev libxml2 libxml2-dev libxslt-dev
There is a VSCode extension called "Python Auto Venv" that automatically detects and uses your virtual environment if there is one.
This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.
FileStream fileStream = File.Open(<path>, FileMode.Open);
/*
* Set the length of filestream to 0 and flush it to the physical file.
*
* Flushing the stream is important because this ensures that
* the changes to the stream trickle down to the physical file.
*
*/
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.
Inserting data into a pandas dataframe and providing column name.
import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df) #printing dataframe.
This is our printed data:
For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.
Like this:
df['COUNTER'] =1 #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)
OUTPUT:
Try this code
HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");
Based on the answer of @Tyler McGinnis. I made a different approach using ES6 syntax and nested routes with wrapped components:
import React, { cloneElement, Children } from 'react'
import { Route, Redirect } from 'react-router-dom'
const PrivateRoute = ({ children, authed, ...rest }) =>
<Route
{...rest}
render={(props) => authed ?
<div>
{Children.map(children, child => cloneElement(child, { ...child.props }))}
</div>
:
<Redirect to={{ pathname: '/', state: { from: props.location } }} />}
/>
export default PrivateRoute
And using it:
<BrowserRouter>
<div>
<PrivateRoute path='/home' authed={auth}>
<Navigation>
<Route component={Home} path="/home" />
</Navigation>
</PrivateRoute>
<Route exact path='/' component={PublicHomePage} />
</div>
</BrowserRouter>
Here some possibilities of single and double quotes with variable
$world = "world";
"Hello '.$world.' ";
'hello ".$world."';
I have encountered such a problem when grouping object, i always resolved them by a simple way: perform a custom filter using a java.util.Set to remove duplicate object with whatever attribute of your choice as bellow
Set<String> uniqueNames = new HashSet<>();
Map<String, String> phoneBook = people
.stream()
.filter(person -> person != null && !uniqueNames.add(person.getName()))
.collect(toMap(Person::getName, Person::getAddress));
Hope this helps anyone having the same problem !
For those who don't care if it's "Google Chrome", I suggest using "Chromium" instead.
See: Download Chromium
- Look in http://googlechromereleases.blogspot.com/search/label/Stable%20updates for the last time "44." was mentioned.
- Loop up that version history ("44.0.2403.157") in the Position Lookup
- In this case it returns a base position of "330231". This is the commit of where the 44 release was branched, back in May 2015.*
- Open the continuous builds archive
- Click through on your platform (Linux/Mac/Win)
- Paste "330231" into the filter field at the top and wait for all the results to XHR in.
- Eventually I get a perfect hit: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Mac/330231/
- Sometimes you may have to decrement the commit number until you find one.
- Download and run!
Alternatively, if using javax.net.ssl.trustStore for specifying the location of your truststore does not work ( as it did in my case for two way authentication ), you can also use SSLContextBuilder as shown in the example below. This example also includes how to create a httpclient as well to show how the SSL builder would work.
SSLContextBuilder sslcontextbuilder = SSLContexts.custom();
sslcontextbuilder.loadTrustMaterial(
new File("C:\\path to\\truststore.jks"), //path to jks file
"password".toCharArray(), //enters in the truststore password for use
new TrustSelfSignedStrategy() //will trust own CA and all self-signed certs
);
SSLContext sslcontext = sslcontextbuilder.build(); //load trust store
SSLConnectionSocketFactory sslsockfac = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsockfac).build(); //sets up a httpclient for use with ssl socket factory
try {
HttpGet httpget = new HttpGet("https://localhost:8443"); //I had a tomcat server running on localhost which required the client to have their trust cert
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
Just my couple cents... sometimes it's good to be sure there are no any duplicates... so we have the next function in the utils library:
jQuery.loadCSS = function(url) {
if (!$('link[href="' + url + '"]').length)
$('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
}
How to use:
$.loadCSS('css/style2.css');
I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.
ExpectedConditions
is obsolete, so:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
Now I solved this issue in this way,
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the default
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
//No need to implement.
}
}
};
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e)
{
System.out.println(e);
}
Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool
e.g. local testing with temporary certifcates.
Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:
C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config
import the ViewChild
decorator from @angular/core
, like so:
HTML Code:
<form #f="ngForm">
...
...
</form>
TS Code:
import { ViewChild } from '@angular/core';
class TemplateFormComponent {
@ViewChild('f') myForm: any;
.
.
.
}
now you can use 'myForm' object to access any element within it in the class.
I had the problem a few weeks ago with a few discrete features which were formatted as 'object'. This solution seemed to work.
for col in discrete:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(pd.Int64Dtype())
Casting my hat into the ring a couple years later.
Will need to save the beginning center of the image view:
var panBegin: CGPoint.zero
Then update the new center using a transform:
if recognizer.state == .began {
panBegin = imageView!.center
} else if recognizer.state == .ended {
panBegin = CGPoint.zero
} else if recognizer.state == .changed {
let translation = recognizer.translation(in: view)
let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)
imageView!.center = panBegin.applying(panOffsetTransform)
}
The List class's constructor can convert an IQueryable for you:
public static List<TResult> ToList<TResult>(this IQueryable source)
{
return new List<TResult>(source);
}
or you can just convert it without the extension method, of course:
var list = new List<T>(queryable);
Step by step instructions:
The .ToLowerCase
version is not going to be faster - it involves an extra string allocation
(which must later be collected), etc.
Personally, I'd use
string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase)
this avoids all the issues of culture-sensitive strings, but as a consequence it avoids all the issues of culture-sensitive strings. Only you know whether that is OK in your context.
Using the string.Equals
static method avoids any issues with val
being null
.
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
To clean this up a little bit and maintain a single line of code (like you would with a toggle()
), you can use a ternary operator so your code winds up looking like this (also using jQuery):
$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');
The simplest solution I've found is:
var text = atob(byteArray);
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
Or more tersely:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
Define a custom non-enumerable sortBy
function using a Schwartzian transform on all arrays :
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Use it like so:
array.sortBy(function(o){ return o.date });
If your date is not directly comparable, make a comparable date out of it, e.g.
array.sortBy(function(o){ return new Date( o.date ) });
You can also use this to sort by multiple criteria if you return an array of values:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.
Using setBackgroundResource()
method:
myImgView.setBackgroundResource(R.drawable.monkey);
you are putting that monkey in the background.
I suggest the use of setImageResource()
method:
myImgView.setImageResource(R.drawable.monkey);
or with setImageDrawable()
method:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
getResources().getDrawable()
is now deprecated. This is an example how to use now:myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
and how to validate for old API versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}
Here's what I use. Note you have to use the @autoreleasepool
feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.
This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.
Here's the test string that I used: This is my 123+ test & test2. Got it?!
These are my Objective C++ class methods:
static NSString * urlDecode(NSString *stringToDecode) {
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
static NSString * urlEncode(NSString *stringToEncode) {
@autoreleasepool {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)stringToEncode,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8
));
result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
return result;
}
}
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
To view database roles assigned to users, you can use sys.database_role_members
The following query returns the members of the database roles.
SELECT DP1.name AS DatabaseRoleName,
isnull (DP2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DP1
ON DRM.role_principal_id = DP1.principal_id
LEFT OUTER JOIN sys.database_principals AS DP2
ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;
You need to enclose your class in {
and }
. A few extra pointers: According to the Java coding conventions, you should
{
on the same line as the method declaration:Here's how I would write it:
public class ModMyMod extends BaseMod {
public String version() {
return "1.2_02";
}
public void addRecipes(CraftingManager recipes) {
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt
});
}
}
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
<option value=''>- Please choose -</option>_x000D_
<option value='1'>1</option>_x000D_
<option value='2'>2</option>_x000D_
<option value='selectedvalue'>There we go!</option>_x000D_
<option value='3'>3</option>_x000D_
<option value='4'>4</option>_x000D_
<option value='5'>5</option>_x000D_
</select>
_x000D_
function showstuff(boxid){
document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />
This will help you, I think.
There are a number of obvious differences between Git and GitHub.
Git itself is really focused on the essential tasks of version control. It maintains a commit history, it allows you to reverse changes through reset and revert commands, and it allows you to share code with other developers through push and pull commands. I think those are the essential features every developer wants from a DVCS tool.
No Scope Creep with Git
But one thing about Git is that it is really just laser focused on source code control and nothing else. That's awesome, but it also means the tool lacks many features organizations want. For example, there is no built-in user management facilities to authenticate who is connecting and committing code. Integration with things like Jira or Jenkins are left up to developers to figure out through things like hooks. Basically, there are a load of places where features could be integrated. That's where organizations like GitHub and GitLab come in.
Additional GitHub Features
GitHub's primary 'value-add' is that it provides a cloud based platform for Git. That in itself is awesome. On top of that, GitHub also offers:
So GitHub really adds polish and refinement to an already popular DVCS tool.
Git and GitHub competitors
Sometimes when it comes to differentiating between Git and GitHub, I think it's good to look at who they compete against. Git competes on a plane with tools like Mercurial, Subversion and RTC, whereas GitHub is more in the SaaS space competing against cloud vendors such as GitLab and Atlassian's BitBucket.
No GitHub Required
One thing I always like to remind people of is that you don't need GitHub or GitLab or BitBucket to use Git. Git was released in what, 2005? GitHub didn't come on the scene until 2007 or 2008, so big organizations were doing distributed version control with Git long before the cloud hosting vendors came along. So Git is just fine on its own. It doesn't need a cloud hosting service to be effective. But at the same time, having a PaaS provider certainly doesn't hurt.
Working with GitHub Desktop
By the way, you mentioned the mismatch between the repositories in your GitHub account and the repos you have locally? That's understandable. Until you've connected and done a pull or a fetch, the local Git repo doesn't know about the remote GitHub repo. Having said that, GitHub provides a tool known as the GitHub desktop that allows you to connect to GitHub from a desktop client and easily load local Git repos to GitHub, or bring GitHub repos onto your local machine.
I'm not overly impressed by the tool, as once you know Git, these things aren't that hard to do in the Bash shell, but it's an option.
$("#availability option:selected").text();
This will give you the text value of your dropdown list. You can also use .val() instead of .text() depending on what you're looking to get. Follow the link to the jQuery documentation and examples.
how about just getting the length of char in your EditText and display it?
something along the line of
tv.setText(s.length() + " / " + String.valueOf(charCounts));
Here is a little snippet that allows you to change the type
of elements in documents.
jquery.type.js
(GitHub Gist):
var rtype = /^(?:button|input)$/i;
jQuery.attrHooks.type.set = function(elem, value) {
// We can't allow the type property to be changed (since it causes problems in IE)
if (rtype.test(elem.nodeName) && elem.parentNode) {
// jQuery.error( "type property can't be changed" );
// JB: Or ... can it!?
var $el = $(elem);
var insertionFn = 'after';
var $insertionPoint = $el.prev();
if (!$insertionPoint.length) {
insertionFn = 'prepend';
$insertionPoint = $el.parent();
}
$el.detach().attr('type', value);
$insertionPoint[insertionFn]($el);
return value;
} else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
It gets around the issue by removing the input
from the document, changing the type
and then putting it back where it was originally.
Note that this snippet was only tested for WebKit browsers – no guarantees on anything else!
Here are a couple of ways to do that:
I'd suggest, provide a popup asking the user if s/he wants to go full screen and then call this javascript accordingly.
random.sample()
also works on text
example:
> text = open("textfile.txt").read()
> random.sample(text, 5)
> ['f', 's', 'y', 'v', '\n']
\n is also seen as a character so that can also be returned
you could use random.sample()
to return random words from a text file if you first use the split method
example:
> words = text.split()
> random.sample(words, 5)
> ['the', 'and', 'a', 'her', 'of']
maybe SSL
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// ignore ssl error
if (handler != null){
handler.proceed();
} else {
super.onReceivedSslError(view, null, error);
}
}
This problem comes from a strange quirk within Office/Windows.
After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.
I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.
The redundant Ctrl+Break action probably resolves the lingering execution.
managed to fix this by copying the below folder from another Visual Studio setup (non-express)
from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc
to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc
c:out
also has an attribute for assigning a default value if the value of person.name
happens to be null.
I fixed this issue by adding a slash
at the beginning to my relative path
http://forums.iis.net/t/1187650.aspx has the answer. Setting the iis authentication to appliction pool identity will resolve this.
In IIS Authentication, Anonymous Authentication was set to "Specific User". When I changed it to Application Pool, I can access the site.
To set, click on your website in IIS and double-click "Authentication". Right-click on "Anonymous Authentication" and click "Edit..." option. Switch from "Specific User" to "Application pool identity". Now you should be able to set file and folder permissions using the IIS AppPool\{Your App Pool Name}.
If You are not using Express or simply want to use CORS. The following code will help resolve
const cors = require('cors')({ origin: true, });
exports.yourfunction = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
// *Your code*
});
});
You can use a list comprehension:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
The following works for me (Excel 2010)
Dim b1 As Button
Set b1 = ActiveSheet.Buttons("Button 1")
b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call aLongAction
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault
Be aware that
.enabled = False
does not gray out a button.
The font color has to be set explicitely to get it grayed.
Calling str(...)
is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,
:
print(','.join(str(x) for x in list_of_ints))
I found the solution, Problem started when I updated sdk, after that I used different buildToolsVersion ('22.0.1') and I was using different support library like compile 'com.android.support:appcompat-v7:23.0.0', showing you in image below
This was raising problem of "android.widget.Material..." Then I used same version for support library like compile 'com.android.support:appcompat-v7:22.0.1' and its DONE. (Showing you in below screenshot)
Simply
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
If you can't do what is told by @Martin Bean, then you can try another trick.
Create a new migration and on that file in up() method insert what's in down() method of the migration you want to rollback and in down() method insert what's in up() method.
e.g if your original migration is like this
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id')->unsigned();
$table->string('name');
});
}
public function down()
{
Schema::drop('users');
}
then in new migration file do this
public function up()
{
Schema::drop('users');
}
public function down()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id')->unsigned();
$table->string('name');
});
}
and then run the migrate, it will delete the table. and if you again want that back just rollback it.
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
Use the npm bin
command to get the node modules /bin directory of your project
$ $(npm bin)/<binary-name> [args]
e.g.
$ $(npm bin)/bower install
If you are using windows OS then in Gitbash terminal use the following command $source venv/Scripts/activate. This will help you to enter the virtual environment.
You can convert that time in Unix timestamp by using
select UNIX_TIMESTAMP('2013-11-26 01:24:34')
then convert it in the readable format in whatever format you need
select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");
For in detail you can visit link
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.
After importing the HOC you can then use it like this with the necessary methods:
/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
// start off with the existing state
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
/**
* Toggle all checkboxes for select table
*/
toggleAll() {
const selectAll = !this.state.selectAll;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.checkboxTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
}
/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
return this.state.selection.includes(key);
}
<CheckboxTable
ref={r => (this.checkboxTable = r)}
toggleSelection={this.toggleSelection}
selectAll={this.state.selectAll}
toggleAll={this.toggleAll}
selectType="checkbox"
isSelected={this.isSelected}
data={data}
columns={columns}
/>
See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable
Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw
Here is a useful git alias
that works for me.
git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-- \1/"'
Here is the output of git tree
jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
|-- main
| |-- java
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- AbstractFile.java
| | | | | |-- roman
| | | | | | |-- Main.java
| | | | | | |-- Numeral.java
| | | | | | |-- RomanNumberInputFile.java
| | | | | | |-- RomanNumeralToDecimalEvaluator.java
|-- test
| |-- java
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- roman
| | | | | | |-- InterpretSteps.java
| | | | | | |-- RunCukesTest.java
| |-- resources
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- roman
| | | | | | |-- Interpret.feature
| | |-- sample-input.txt
The comparable tree
command
jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
+-- pom.xml
+-- src
¦ +-- main
¦ ¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- AbstractFile.java
¦ ¦ +-- roman
¦ ¦ +-- Main.java
¦ ¦ +-- Numeral.java
¦ ¦ +-- RomanNumberInputFile.java
¦ ¦ +-- RomanNumeralToDecimalEvaluator.java
¦ +-- test
¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- roman
¦ ¦ +-- InterpretSteps.java
¦ ¦ +-- RunCukesTest.java
¦ +-- resources
¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- roman
¦ ¦ +-- Interpret.feature
¦ +-- sample-input.txt
+-- target
+-- classes
¦ +-- com
¦ +-- foxguardsolutions
¦ +-- jonavon
¦ +-- AbstractFile.class
¦ +-- roman
¦ +-- Main.class
¦ +-- Numeral.class
¦ +-- RomanNumberInputFile.class
¦ +-- RomanNumeralToDecimalEvaluator.class
+-- generated-sources
¦ +-- annotations
+-- maven-status
+-- maven-compiler-plugin
+-- compile
+-- default-compile
+-- createdFiles.lst
+-- inputFiles.lst
30 directories, 17 files
Clearly tree has better output, but I would like it to use my .gitignore file. So that my compiled content doesn't show
With Angular Universal, you can generate landing pages for the app that look like the complete app and then load your Angular app behind it.
Angular Universal generates pure HTML means no-javascript pages in server-side and serve them to users without delaying. So you can deal with any crawler, bot and user (who already have low cpu and network speed).Then you can redirect them by links/buttons to your actual angular app that already loaded behind it. This solution is recommended by official site. -More info about SEO and Angular Universal-
You can use them right inline:
var square = 9.4
var floored = floor(square)
var root = sqrt(floored)
println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")
Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:
$('#cat').hover(function()
{
// Mouse Over Callback
}, function()
{
// Mouse Leave callback
});
Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):
$('#cat').hover(function()
{
if($('#dog').is(':visible'))
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
}, function()
{
// Mouse Leave callback
});
This is the simplest way you can have your own javascript function be called when an onSubmit
occurs.
HTML
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
JavaScript
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(event) {
event.preventDefault();
}
I think the general consensus is that nlog is a bit easier to configure and use. Both are quite capable, though.
do it like this, without too the extra slashes
root="/home"
os.path.join(root,"build","test","sandboxes",todaystr,"new_sandbox")
You can replace your old dictionary with a defaultdict
:
>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1
The "trick" here is that a defaultdict
can be initialized with another dict
. This means
that you preserve the existing values in your normal dict
:
>>> d['foo']
123
For anyone who is looking a way to watch a specific file to exist in VBS:
Function bIsFileDownloaded(strPath, timeout)
Dim FSO, fileIsDownloaded
set FSO = CreateObject("Scripting.FileSystemObject")
fileIsDownloaded = false
limit = DateAdd("s", timeout, Now)
Do While Now < limit
If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
WScript.Sleep 1000
Loop
Set FSO = Nothing
bIsFileDownloaded = fileIsDownloaded
End Function
Usage:
FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
If fileIsDownloaded Then
WScript.Echo Now & " File is Downloaded: " & FileName
Else
WScript.Echo Now & " Timeout, file not found: " & FileName
End If
Both styles, with a touch of tweaking, would work.
The first method uses a Javascript Constructor, which like most things has pros and cons.
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
Clear all State
dbContextGlobalERP.ChangeTracker.Entries().Where(e => e.Entity != null).ToList().ForEach(e => e.State = EntityState.Detached);
In order to get the desired result, you must set "box-sizing: border-box" vs. the default which is "box-sizing: content-box". This is precisely the issue you are referring to (From MDN):
This is the initial and default value as specified by the CSS standard. The width and height properties are measured including only the content, but not the padding, border or margin.
The width and height properties include the content, the padding and border, but not the margin."
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
Compatibility for this CSS is good.
std::move
itself does nothing rather than a static_cast
. According to cppreference.com
It is exactly equivalent to a static_cast to an rvalue reference type.
Thus, it depends on the type of the variable you assign to after the move
, if the type has constructors
or assign operators
that takes a rvalue parameter, it may or may not steal the content of the original variable, so, it may leave the original variable to be in an unspecified state
:
Unless otherwise specified, all standard library objects that have been moved from being placed in a valid but unspecified state.
Because there is no special move constructor
or move assign operator
for built-in literal types such as integers and raw pointers, so, it will be just a simple copy for these types.
I have used DTS (now known as SQL server Import and Export Wizard). I used the this tutorial which worked great for me even in Sql 2008 and excel 2010 (14.0)
I hope this helps
-D
You always have to set the width and height of an Image
. It is not going to automatically size things for you. The React Native docs says so.
You should measure the total height of the ScrollView
using onLayout
and set the height of the Image
s based on it. If you use resizeMode
of cover
it will keep the aspect ratio of your Image
s but it will obviously crop them if it's bigger than the container.
I was having the same problem but only with a few machines. I found that using Invoke-Command to run the same command on the remote server worked.
So instead of:
Get-WmiObject win32_SystemEnclosure -ComputerName $hostname -Authentication Negotiate
Use this:
Invoke-Command -ComputerName $hostname -Authentication Negotiate -ScriptBlock {Get-WmiObject win32_SystemEnclosure}
I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.
The Date functions posted by others are the most correct way to handle this.
However, it's funny you mention the term "floor", because there's a little hack that will run somewhat faster:
CAST(FLOOR(CAST(@dateParam AS float)) AS DateTime)
HTML Code
<input id="is_verified" class="check" name="is_verified" type="radio" value="1"/>
<input id="is_verified" class="check" name="is_verified" type="radio" checked="checked" value="0"/>
<input id="submit" name="submit" type="submit" value="Save" />
Javascript Code
$("input[type='radio'].check").click(function() {
if($(this).is(':checked')) {
if ($(this).val() == 1) {
$("#submit").val("Verified & Save");
}else{
$("#submit").val("Save");
}
}
});
Use the Chr or ChrW function, Chr(charNumber)
.
Relying on compiler optimizations is fragile. The benchmarks linked in the accepted answer and numbers given by Antoine-tran are not to be trusted. Andrew Hare makes the mistake of including a call to repr
in his methods. That slows all the methods equally but obscures the real penalty in constructing the string.
Use join
. It's very fast and more robust.
$ ipython3
Python 3.5.1 (default, Mar 2 2016, 03:38:02)
IPython 4.1.2 -- An enhanced Interactive Python.
In [1]: values = [str(num) for num in range(int(1e3))]
In [2]: %%timeit
...: ''.join(values)
...:
100000 loops, best of 3: 7.37 µs per loop
In [3]: %%timeit
...: result = ''
...: for value in values:
...: result += value
...:
10000 loops, best of 3: 82.8 µs per loop
In [4]: import io
In [5]: %%timeit
...: writer = io.StringIO()
...: for value in values:
...: writer.write(value)
...: writer.getvalue()
...:
10000 loops, best of 3: 81.8 µs per loop
1 - Change Your tables search engine from 'My ISAM' to 'Inno DB' by Operations tab 2 - you must do this for all tables that you want make relationship between 3 - localhost/phpmyadmin/tbl_relation.php?db=your_database_name&table=your_table_name then replace this url in browser, then you will be able to see the relationship page
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
using html5 data attribute...
try this
Html
Product price: $<span id="product_price">500</span>
<br>Total price: $500
<br>
<input type="button" data-quantity="2" value="2
Qty">
<input type="button" data-quantity="4" class="mnozstvi_sleva" value="4
Qty">
<br>Total
<input type="text" id="count" value="1">
JS
$(function(){
$('input:button').click(function () {
$('#count').val($(this).data('quantity') * $('#product_price').text());
});
});
If you're an Android developer you can use android.util.Base64
class for this purpose.
This works for me
td::after {
content: '';
display: block;
width: 30px;
}
You can just use the error function that's built in to the math library, as stated on their website.
This page shows how to add an UIAlertController if you are using Swift.
I was wondering, would this be on any use to you?
declare @val int,@len=800
select replace(str(@val,@len),' ','0')
Quick 'n dirty, regex-free, low-robustness chop-chop technique
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
in
is definitely more pythonic.
In fact has_key()
was removed in Python 3.x.
Probably your simple json.jar file isn't in your classpath.
You can use alternative "delimiters" like ";" or "|" but simplest might just be quoting which is supported by most (decent) CSV libraries and most decent spreadsheets.
Documentation here, and I'll use the Frankfurt region as an example.
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
You either need to create an object of type Beta in the Alpha class or its method
Like you do here in the Main Beta cBeta = new Beta();
If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like
public class Alpha
{
Beta localInstance;
public Alpha(Beta _beta)
{
localInstance = _beta;
}
public void DoSomethingAlpha()
{
localInstance.DoSomethingAlpha();
}
}
There is no sure shot trick. You need to explore the reasons why your mails are classified as spam. SpamAssassin hase a page describing Some Tips for Legitimate Senders to Avoid False Positives. See also Coding Horror: So You'd Like to Send Some Email (Through Code)
Otherwise you can try this also-
ViewGroup vg = (ViewGroup) findViewById (R.id.videoTitleTxtView);
vg.removeAllViews();
vg.refreshDrawableState();
if ($select.find('option[value=' + val + ']').length) {...}
I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)
You have to set the height
of the .modal-body
in and give it overflow-y: auto
. Also reset .modal-dialog
overflow value to initial
.
See the working sample:
http://www.bootply.com/T0yF2ZNTUd
.modal{
display: block !important; /* I added this to see the modal, you don't need this */
}
/* Important part */
.modal-dialog{
overflow-y: initial !important
}
.modal-body{
height: 80vh;
overflow-y: auto;
}
In Management Studio, open the Object Explorer.
Views
Script view as > Create To > New query window
and you're done!
If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:
SELECT
m.definition
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
You should look at Computed Properties
In your code sample, perimeter
is a property not backed up by a class variable, instead its value is computed using the get
method and stored via the set
method - usually referred to as getter and setter.
When you use that property like this:
var cp = myClass.perimeter
you are invoking the code contained in the get
code block, and when you use it like this:
myClass.perimeter = 5.0
you are invoking the code contained in the set
code block, where newValue
is automatically filled with the value provided at the right of the assignment operator.
Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.
In spring servlet .xml :
<context:component-scan base-package="net.controller" />
(I assumed that the service impl is in the same package as the service interface "net.service")
I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.
You have to create __init__.py
on the Models
subfolder. The file may be empty. It defines a package.
Then you can do:
from Models.user import User
Read all about it in python tutorial, here.
There is also a good article about file organization of python projects here.
You probablly have 2 different versions of hibernate-jpa-api on the classpath. To check that run:
mvn dependency:tree >dep.txt
Then search if there are hibernate-jpa-2.0-api and hibernate-jpa-2.1-api. And exclude the excess one.
Ideone supports Python 2.6 and Python 3
One option is to write a C/C++ wrapper that executes the python script on a regular basis. Your end-user would run the C/C++ executable, which would remain running in the background, and periodically execute the python script. This may not be the best solution, and may not work if you don't know C/C++ or want to keep this 100% python. But it does seem like the most user-friendly approach, since people are used to clicking on executables. All of this assumes that python is installed on your end user's computer.
Another option is to use cron job/Task Scheduler but to put it in the installer as a script so your end user doesn't have to do it.
If you have Tortoise SVN, like I do, take the google link, and ONLY copy the URL.
Regular- (svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only)
Modified to URL- (http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter)
Create a folder, right click the empty space. You can Browse Repo or just download it all via checkout.
I don't know whether you have to be a Google member or not, but I signed up just in case. Have fun with the code.
Misanthropy
This helper class manages parameters for GET and POST requests:
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
private Map<String, String> mParams;
private Listener<JSONObject> mListener;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.mMethod = method;
this.mUrl = url;
this.mParams = params;
this.mListener = reponseListener;
}
@Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
if(mParams != null) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
}
}
return mUrl;
}
@Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
mListener.onResponse(response);
}
}
You are using the same Cast object for every entry. On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
Assuming you're using Python's logging
module, you can pass the string formatting arguments as arguments to the .debug()
method rather than doing the formatting yourself:
log.debug("some debug info: %s", some_info)
which avoids doing the formatting unless the logger actually logs something.
In order to remove all subviews from superviews:
NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount < [oSubView count]; iCount++)
{
id object = [oSubView objectAtIndex:iCount];
[object removeFromSuperview];
iCount--;
}
"blue_box"
is null -- are you positive whatever it is with "id='blue'"
exists when this is being run?
try console.log(document.getElementById("blue"))
in chrome or FF with firebug. Your script might be running before the 'blue'
element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload
).
You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.
str = "aaaaabbbb"
newstr = str[-4:]
Redirecting the stream is asynchronous and will potentially continue after the process has terminated. It is mentioned by Umar to cancel after process termination process.CancelOutputRead()
. However that has data loss potential.
This is working reliably for me:
process.WaitForExit(...);
...
while (process.StandardOutput.EndOfStream == false)
{
Thread.Sleep(100);
}
I didn't try this approach but I like the suggestion from Sly:
if (process.WaitForExit(timeout))
{
process.WaitForExit();
}
Please follow below step to do some processing after Application Context get loaded i.e application is ready to serve.
Create below annotation i.e
@Retention(RetentionPolicy.RUNTIME) @Target(value= {ElementType.METHOD, ElementType.TYPE}) public @interface AfterApplicationReady {}
2.Create Below Class which is a listener which get call on application ready state.
@Component
public class PostApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(PostApplicationReadyListener.class);
public static final String MODULE = PostApplicationReadyListener.class.getSimpleName();
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
ApplicationContext context = event.getApplicationContext();
String[] beans = context.getBeanNamesForAnnotation(AfterAppStarted.class);
LOGGER.info("bean found with AfterAppStarted annotation are : {}", Arrays.toString(beans));
for (String beanName : beans) {
Object bean = context.getBean(beanName);
Class<?> targetClass = AopUtils.getTargetClass(bean);
Method[] methods = targetClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(AfterAppStartedComplete.class)) {
LOGGER.info("Method:[{} of Bean:{}] found with AfterAppStartedComplete Annotation.", method.getName(), beanName);
Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
LOGGER.info("Going to invoke method:{} of bean:{}", method.getName(), beanName);
currentMethod.invoke(bean);
LOGGER.info("Invocation compeleted method:{} of bean:{}", method.getName(), beanName);
}
}
}
} catch (Exception e) {
LOGGER.warn("Exception occured : ", e);
}
}
}
Finally when you start your Spring application just before log stating application started your listener will be called.
On Linux there is unshield
, which worked well for me (even if the GUI includes custom deterrents like license key prompts). It is included in the repositories of all major distributions (arch, suse, debian- and fedora-based) and its source is available at https://github.com/twogood/unshield
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
[self.locationManager setDistanceFilter:99999];
which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:
- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}
All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device
You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()
).
If so, just use unset()
:
unset($arr[1]);
If the input is inside the div than you can try this:
$('#div_id input').attr("placeholder", "placeholder text");
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
do this in two steps:
and use preg_replace
:
$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);
Include path of jar (jdbc driver) in classpath.
For the permission error using git repository on AWS instance, I successfully solved it by creating a group, and assigning it to the repository folder recursively(-R), and give the written right to this group, and then assign the default aws instance user(ec2-user or ubuntu) to this group.
sudo groupadd share_group
sudo chgrp -R share_group /path/to/your/repository
sudo chmod -R g+w /path/to/your/repository
sudo usermod -a -G share_group ubuntu
By the way, to see the ownership of the folder or file just type:
ls -l /path/to/your/repository
'
drwxr-x--x 2 root shared_group
(explanation please see:https://wiki.archlinux.org/index.php/File_permissions_and_attributes).
After step 3, you will see
drwx--x--x 2 root root
drwxr-x--x 2 root share_group
chmod -Rf u+w /path/to/git/repo/objects
It did not work for me, I think it should be the reason that my repository folder belong to the root user, not to Ubuntu user, and 'git' by default use the default user(ec2-user or Ubuntu user. You can try to change the user and test it.
sudo chmod -R 777 /path/to/your/repo
$ npm install cors
After installing cors from npm add the code below to your node app file. It solved my problem.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Install request module, using npm install request
In code:
var request = require('request');
var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
var json_obj = JSON.parse(data);
request.post({
headers: {'content-type': 'application/json'},
url: 'http://localhost/PhpPage.php',
form: json_obj
}, function(error, response, body){
console.log(body)
});
In Laravel 5.x you can use laravelcollective/html and the syntax:
{!! Html::image('img/logo.png') !!}
Depending on your timezone, you may lose a few minutes (1650-01-01 00:00:00 becomes 1649-12-31 23:52:58)
Use the following code to avoid that
new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional);
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
There are many way to get application context in Spring application. Those are given bellow:
Via ApplicationContextAware:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here setApplicationContext(ApplicationContext applicationContext)
method you will get the applicationContext
Via Autowired:
@Autowired
private ApplicationContext applicationContext;
Here @Autowired
keyword will provide the applicationContext.
For more info visit this thread
Thanks :)
Here's another one :D
class Program
{
static void Main(string[] args)
{
Console.Write("Working... ");
int spinIndex = 0;
while (true)
{
// obfuscate FTW! Let's hope overflow is disabled or testers are impatient
Console.Write("\b" + @"/-\|"[(spinIndex++) & 3]);
}
}
}
You can use a subselect in your from query (untested and not sure which is faster):
SELECT Grade, COUNT(*) / TotalRows
FROM (SELECT Grade, COUNT(*) As TotalRows
FROM myTable) Grades
GROUP BY Grade, TotalRows
Or
SELECT Grade, SUM(PartialCount)
FROM (SELECT Grade, 1/COUNT(*) AS PartialCount
FROM myTable) Grades
GROUP BY Grade
Or
SELECT Grade, GradeCount / SUM(GradeCount)
FROM (SELECT Grade, COUNT(*) As GradeCount
FROM myTable
GROUP BY Grade) Grades
You can also use a stored procedure (apologies for the Firebird syntax):
SELECT COUNT(*)
FROM myTable
INTO :TotalCount;
FOR SELECT Grade, COUNT(*)
FROM myTable
GROUP BY Grade
INTO :Grade, :GradeCount
DO
BEGIN
Percent = :GradeCount / :TotalCount;
SUSPEND;
END
You can also use a bean (request scoped is suggested) and directly access the context by way of the FacesContext.
You can get the HttpServletRequest and HttpServletResposne objects by using the following code:
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
After this, you can access individual parameters via getParameter(paramName)
or access the full map via getParameterMap()
req
object
The reason I suggest a request scoped bean is that you can use these during initialization (worst case scenario being the constructor. Most frameworks give you some place to do code at bean initialization time) and they will be done as your request comes in.
It is, however, a bit of a hack. ;) You may want to look into seeing if there is a JSF Acegi module that will allow you to get access to the variables you need.
Why not try to add a ScrollView to wrap whatever it is you want to scroll. Here is how I have done it, where I actually leave a header on top which does not scroll, while the dialog widgets (in particular the EditTexts) scroll when you open soft keypad.
<LinearLayout android:id="@+id/HeaderLayout" >
<!-- Here add a header or whatever will not be scrolled. -->
</LinearLayout>
<ScrollView android:id="@+id/MainForm" >
<!-- Here add your edittexts or whatever will scroll. -->
</ScrollView>
I would typically have a LinearLayout inside the ScrollView, but that is up to you. Also, setting Scrollbar style to outsideInset helps, at least on my devices.
In a function, use as
render: function (args) {
if (args.value != 0)
return (parseFloat(args.value).toFixed(2));
},
If you don't mind a bit more markup, this would work:
<div class="centered">
<button class="btn btn-large btn-primary" type="button">Submit</button>
</div>
With the corresponding CSS rule:
.centered
{
text-align:center;
}
I have to look at the CSS rules for the btn
class, but I don't think it specifies a width, so auto
left & right margins wouldn't work. If you added one of the span
or input-
rules to the button, auto margins would work, though.
Edit:
Confirmed my initial thought; the btn
classes do not have a width defined, so you can't use auto side margins. Also, as @AndrewM notes, you could simply use the text-center
class instead of creating a new ruleset.
bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
Try This
$( "#email,#confirmEmail " ).on( "copy cut paste drop", function() {
return false;
});
If the SSL certificates are not properly installed in your system, you may get this error:
cURL error 60: SSL certificate problem: unable to get local issuer certificate.
You can solve this issue as follows:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem
file to some safe location in your system
Update your php.ini
file and configure the path to that file:
@SolutionYogi's answer works like a charm, but it seems that using $.each is less straightforward and efficient than directly appending listitems :
var mylist = $('#list');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
mylist.empty().append(listitems);
It exits the function and returns nothing.
Something like return 1;
would be incorrect since it returns integer 1.
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
I was facing the same problem when I was trying to connect Mysql to a Remote Server. I had found out that I had to change the bind-address to the current private IP address of the DB server.
But when I was trying to add the bind-address =0.0.0.0
line in my.cnf
file, it was not understanding the line when I tried to create a DB.
Upon searching, I found out the original place where bind-address was declared.
The actual declaration is in : /etc/mysql/mariadb.conf.d/50-server.cnf
Therefore I changed the bind-address directly there and then all seems working.
I got this answer from here. and its works for me
Require local
Change to
Require all granted
Order Deny,Allow
Allow from all
The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
You can accomplish this via method overloading.
public int doSomething(int arg1, int arg2)
{
return 0;
}
public int doSomething()
{
return doSomething(defaultValue0, defaultValue1);
}
By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.
To return the whole table at once you could change the SELECT to:
SELECT ...
BULK COLLECT INTO T
FROM ...
This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.
You can make this connection in interface builder.
In your storyboard, click the assistant editor at the top of the screen (two circles in the middle).
Ctrl + Click on the textfield in interface builder.
Drag from EditingChanged to inside your view controller class in the assistant view.
Name your function ("textDidChange" for example) and click connect.
This will do it for you:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle)
return true;
}
return false;
}
I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().
I'm sending files(array) using formData in vuejs
for me below code is working
if(this.requiredDocumentForUploads.length > 0) {
this.requiredDocumentForUploads.forEach(file => {
var name = file.attachment_type // attachment_type is using for naming
if(document.querySelector("[name=" + name + "]").files.length > 0) {
formData.append("requiredDocumentForUploadsNew[" + name + "]", document.querySelector("[name=" + name + "]").files[0])
}
})
}
In your Package Manager Console run the command
PM> cd NameofApp
then you can try to run the command there.For instance
PM > ng generate component Home
I also get this error, but I was solved the problem. If you using php artisan serve
add this code {{ csrf_field() }}
under {!! Form::open() !!}
I hope this is solve your problem.
You can just use exec
to replace your current shell with a new shell:
Switch to bash
:
exec bash
Switch to zsh
:
exec zsh
This won't affect new terminal windows or anything, but it's convenient.
@people = qw( bob john linda );
$n = @people; # the number 3
Print " le number in the list is $n \n";
Expressions in Perl always return the appropriate value for their context. For example, how about the “name” * of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements in the array:
Try -
Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)
As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.
Since you are using webpack you should be able to just import
or require
moment and then use it:
import moment from 'moment'
...
render() {
return (
<div>
{
this.props.data.map((post,key) =>
<div key={key} className="post-detail">
<h1>{post.title}</h1>
<p>{moment(post.date).format()}</p>
<p dangerouslySetInnerHTML={{__html: post.content}}></p>
<hr />
</div>
)}
</div>
);
}
...
Use typeset:
typeset -l new # Always lowercase
find $topPoint | # Not using xargs to make this more readable
while read old
do new="$old" # $new is a lowercase version of $old
mv "$old" "$new" # Quotes for those annoying embedded spaces
done
On Windows, emulations, like Git Bash, may fail because Windows isn't case-sensitive under the hood. For those, add a step that mv
's the file to another name first, like "$old.tmp", and then to $new
.
My solution with jQuery. It may not be 100% reliable, but it works for me. The idea is described in code annotations.
/**_x000D_
* Prevent fields autofill for fields._x000D_
* When focusing on a text field with autocomplete (with values: "off", "none", "false") we replace the value with a new and unique one (here it is - "off-forced-[TIMESTAMP]"),_x000D_
* the browser does not find this type of autocomplete in the saved values and does not offer options._x000D_
* Then, to prevent the entered text from being saved in the browser for a our new unique autocomplete, we replace it with the one set earlier when the field loses focus or when user press Enter key._x000D_
* @type {{init: *}}_x000D_
*/_x000D_
var PreventFieldsAutofill = (function () {_x000D_
function init () {_x000D_
events.onPageStart();_x000D_
}_x000D_
_x000D_
var events = {_x000D_
onPageStart: function () {_x000D_
$(document).on('focus', 'input[autocomplete="off"], input[autocomplete="none"], input[autocomplete="false"]', function () {_x000D_
methods.replaceAttrs($(this));_x000D_
});_x000D_
$(document).on('blur', 'input[data-prev-autocomplete]', function () {_x000D_
methods.returnAttrs($(this));_x000D_
});_x000D_
$(document).on('keydown', 'input[data-prev-autocomplete]', function (event) {_x000D_
if (event.keyCode == 13 || event.which == 13) {_x000D_
methods.returnAttrs($(this));_x000D_
}_x000D_
});_x000D_
$(document).on('submit', 'form', function () {_x000D_
$(this).find('input[data-prev-autocomplete]').each(function () {_x000D_
methods.returnAttrs($(this));_x000D_
});_x000D_
});_x000D_
}_x000D_
};_x000D_
_x000D_
var methods = {_x000D_
/**_x000D_
* Replace value of autocomplete and name attribute for unique and save the original value to new data attributes_x000D_
* @param $input_x000D_
*/_x000D_
replaceAttrs: function ($input) {_x000D_
var randomString = 'off-forced-' + Date.now();_x000D_
$input.attr('data-prev-autocomplete', $input.attr('autocomplete'));_x000D_
$input.attr('autocomplete', randomString);_x000D_
if ($input.attr('name')) {_x000D_
$input.attr('data-prev-name', $input.attr('name'));_x000D_
$input.attr('name', randomString);_x000D_
}_x000D_
},_x000D_
/**_x000D_
* Restore original autocomplete and name value for prevent saving text in browser for unique value_x000D_
* @param $input_x000D_
*/_x000D_
returnAttrs: function ($input) {_x000D_
$input.attr('autocomplete', $input.attr('data-prev-autocomplete'));_x000D_
$input.removeAttr('data-prev-autocomplete');_x000D_
if ($input.attr('data-prev-name')) {_x000D_
$input.attr('name', $input.attr('data-prev-name'));_x000D_
$input.removeAttr('data-prev-name');_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
return {_x000D_
init: init_x000D_
}_x000D_
})();_x000D_
PreventFieldsAutofill.init();
_x000D_
.input {_x000D_
display: block;_x000D_
width: 90%;_x000D_
padding: 6px 12px;_x000D_
font-size: 14px;_x000D_
line-height: 1.42857143;_x000D_
color: #555555;_x000D_
background-color: #fff;_x000D_
background-image: none;_x000D_
border: 1px solid #ccc;_x000D_
border-radius: 4px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
<p>_x000D_
<label for="input-1">Firts name without autocomplete</label><br />_x000D_
<input id="input-1" class="input" type="text" name="first-name" autocomplete="off" placeholder="Firts name without autocomplete" />_x000D_
</p>_x000D_
<p>_x000D_
<label for="input-2">Firts name with autocomplete</label><br />_x000D_
<input id="input-2" class="input" type="text" name="first-name" autocomplete="given-name" placeholder="Firts name with autocomplete" />_x000D_
</p>_x000D_
<p>_x000D_
<button type="submit">Submit form</button>_x000D_
</p>_x000D_
</form>
_x000D_
One thing I've used with good results is the following (I don't know if its mentioned already because I can't remember its name).
You precompute a table T with a random number for each character in your key's alphabet [0,255]. You hash your key 'k0 k1 k2 ... kN' by taking T[k0] xor T[k1] xor ... xor T[kN]. You can easily show that this is as random as your random number generator and its computationally very feasible and if you really run into a very bad instance with lots of collisions you can just repeat the whole thing using a fresh batch of random numbers.
Running programs to parse the results seems a bit iffy. Here's what I use.
require('dns').lookup(require('os').hostname(), function (err, add, fam) {
console.log('addr: ' + add);
})
This should return your first network interface local IP address.
Unless I have misunderstood:
$("e").prepend("<yourelem>Text</yourelem>");
Or
$("<yourelem>Text</yourelem>").prependTo("e");
Although it sounds like from your description that there is some condition attached, so
if (SomeCondition){
$("e").prepend("<yourelem>Text</yourelem>");
}
else{
$("e").append("<yourelem>Text</yourelem>");
}
select t1.*, sq.*
from table1 t1,
(select a,b,c from table2 ...) sq
where ...
If not HTML
, then UTF-8
is not recommended. koi8-r
and windows-1251
only without problems. So use html mail.
$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';
$mail_object=& Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail_object->send($recipents, $headers, $body);
}
Most people will tell you to check your proxy settings or delete and re-add artifacts, but I will stay away from that and give another suggestion in case that doesn't turn out to be your problem. It could be your mirror settings.
If you use maven at the office then there's a good chance maven is configured to look for your company's internal maven repository. If you're doing some work from home and you are not connected to the network this could be the problem. An obvious solution might be VPN to the office to get visibility to this repo. Another way around this is to add another mirror site to your /User/.m2/settings.xml file so if it fails to find it on your office network it will try public repo.
<mirror>
<id>Central</id>
<url>http://repo1.maven.org/maven2</url>
<mirrorOf>central</mirrorOf>
<!-- United States, St. Louis-->
</mirror>
For other maven repositories take a look here: http://docs.codehaus.org/display/MAVENUSER/Mirrors+Repositories
To debug any XHR request:
for a GET request:
for a POST request:
$('a').click(function(){
$('#content-container').html('My content here :-)');
});
Support for the extended ternary operator was added in Twig 1.12.0.
If foo
echo yes
else echo no
:
{{ foo ? 'yes' : 'no' }}
If foo
echo it, else echo no
:
{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
If foo
echo yes
else echo nothing:
{{ foo ? 'yes' }}
or
{{ foo ? 'yes' : '' }}
Returns the value of foo
if it is defined and not null, no
otherwise:
{{ foo ?? 'no' }}
Returns the value of foo
if it is defined (empty values also count), no
otherwise:
{{ foo|default('no') }}