If your are using IntelliJ, go to setting => compiler and change the version to your current java version.
To resolve this issue I've changed File->Project Structure->Modules ->> Language level to 10.
And check File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler ->> Project bytecode and Per-module bytecode versions. I have 11 there.
Now I don't get these notifications and the error.
It could be useful for someone like me, having the most recent Idea and getting the same error.
Placing your list view in a Flexible widget may also help,
Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)
I was able to solve the issue by using an edited sdkmanager.bat file by forcing to use the Java embedded inside the Android Studio Itself, which i presume uses the OpenJDK 8. Here is the edited sdkmanager I Used :
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem sdkmanager startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%..
@rem Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."
@rem find Java from Android Studio
@rem Find java.exe
if defined ANDROID_STUDIO_JAVA_HOME goto findJavaFromAndroidStudioJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
goto findJavaNormally
:findJavaFromAndroidStudioJavaHome
set JAVA_HOME=%ANDROID_STUDIO_JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
goto findJavaNormally
@rem java from java home
@rem Find java.exe
:findJavaNormally
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
goto javaError
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
goto javaDirectoryError
:javaError
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:javaDirectoryError
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\lib\dvlib-26.0.0-dev.jar;%APP_HOME%\lib\jimfs-1.1.jar;%APP_HOME%\lib\jsr305-1.3.9.jar;%APP_HOME%\lib\repository-26.0.0-dev.jar;%APP_HOME%\lib\j2objc-annotations-1.1.jar;%APP_HOME%\lib\layoutlib-api-26.0.0-dev.jar;%APP_HOME%\lib\gson-2.3.jar;%APP_HOME%\lib\httpcore-4.2.5.jar;%APP_HOME%\lib\commons-logging-1.1.1.jar;%APP_HOME%\lib\commons-compress-1.12.jar;%APP_HOME%\lib\annotations-26.0.0-dev.jar;%APP_HOME%\lib\error_prone_annotations-2.0.18.jar;%APP_HOME%\lib\animal-sniffer-annotations-1.14.jar;%APP_HOME%\lib\httpclient-4.2.6.jar;%APP_HOME%\lib\commons-codec-1.6.jar;%APP_HOME%\lib\common-26.0.0-dev.jar;%APP_HOME%\lib\kxml2-2.3.0.jar;%APP_HOME%\lib\httpmime-4.1.jar;%APP_HOME%\lib\annotations-12.0.jar;%APP_HOME%\lib\sdklib-26.0.0-dev.jar;%APP_HOME%\lib\guava-22.0.jar
@rem Execute sdkmanager
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %SDKMANAGER_OPTS% -classpath "%CLASSPATH%" com.android.sdklib.tool.sdkmanager.SdkManagerCli %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable SDKMANAGER_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%SDKMANAGER_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Here i used an environmental variable ANDROID_STUDIO_JAVA_HOME which actually points to the JRE embedded in the android studio eg: ../android_studio/jre
This also has a fallback to JAVA_HOME if ANDROID_STUDIO_JAVA_HOME is not set.
When your Android stuio/jre uses a differ version of java, you will receive this error. to solve it, just set Android studio/jre to your JAVA_HOME. and uninstall your own java.
This worked for me (on Windows 10):
Add the following lines into your scripts in the package.json file:
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
Make your devDependencies looks something like this:
"devDependencies": {
"axios": "^0.18",
"bootstrap": "^4.0.0",
"popper.js": "^1.12",
"cross-env": "^5.1",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.4",
"vue": "^2.5.7"
}
Remove node_modules
folder
npm install
npm run dev
For me the solution was to correct the order:
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
Build your webpack.mix.js configuration.
mix.setResourceRoot("../");
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
Install the latest free version of Font Awesome via a package manager like npm.
npm install @fortawesome/fontawesome-free
This dependency entry should now be in your package.json.
// Font Awesome
"dependencies": {
"@fortawesome/fontawesome-free": "^5.15.2",
In your main SCSS file /resources/assets/sass/app.scss, import one or more styles.
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';
Compile your assets and produce a minified, production-ready build.
npm run production
Finally, reference your generated CSS file in your Blade template/layout.
<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">
https://gist.github.com/karlhillx/89368bfa6a447307cbffc59f4e10b621
Just copy the version that is less than the current version and add it explicitly with same version number as current version.
Example
Found versions 27.1.1, 27.1.0. Examples include com.android.support:animated-vector-drawable:27.1.1 and com.android.support:exifinterface:27.1.0
Just copy the version com.android.support:exifinterface:27.1.0
and change it to com.android.support:exifinterface:27.1.1
so that it becomes equal to the current version you are using and add it to your gradle dependencies as following.
implementation 'com.android.support:exifinterface:27.1.1'
Note: Once you are done don't forget to click Sync now at the top of the editor.
In my case, I was using a default import:
import VueAutosuggest from 'vue-autosuggest';
Using a named import fixed it:
import {VueAutosuggest} from 'vue-autosuggest';
Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.
The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.
(The below code is 32-bit, but can be easily converted to 64-bit)
For example, the sequence function can be optimized to only 5 instructions:
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
The whole code looks like:
include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"
start:
InitializeAll
mov ecx, 999999
xor edi, edi ; max
xor ebx, ebx ; max i
.main_loop:
xor esi, esi
mov eax, ecx
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
cmp edi, esi
cmovb edi, esi
cmovb ebx, ecx
dec ecx
jnz .main_loop
OutputValue "Max sequence: ", edi, 10, -1
OutputValue "Max index: ", ebx, 10, -1
FinalizeAll
stdcall TerminateAll, 0
In order to compile this code, FreshLib is needed.
In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0
: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3
.
The output of both programs is the same: max sequence = 525 on i = 837799.
Issue: 'id1' is missing in props validation, eslintreact/prop-types
<div id={props.id1} >
...
</div>
Below solution worked, in a function component:
let { id1 } = props;
<div id={id1} >
...
</div>
Hope that helps.
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
_x000D_
private router = ActivatedRoute;_x000D_
_x000D_
constructor(r: ActivatedRoute) {_x000D_
this.router =r;_x000D_
}_x000D_
_x000D_
onSuccess() {_x000D_
this.router.navigate(['/user_invitation'],_x000D_
{queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
this.route_x000D_
.queryParams_x000D_
.subscribe(params => {_x000D_
let code = params['code'];_x000D_
let userEmail = params['email'];_x000D_
});_x000D_
}
_x000D_
Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html
accuracy_score is a classification metric, you cannot use it for a regression problem.
this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.
that syntax is now deprecated, you will get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
parallel firstTask: {
^
WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
parallel secondTask: {
^
2 errors
You should do something like:
stage("Parallel") {
steps {
parallel (
"firstTask" : {
//do some stuff
},
"secondTask" : {
// Do some other stuff in parallel
}
)
}
}
Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:
pipeline {
stages {
stage("Work 1"){
steps{
parallel ( "Build common Library":
{
node('<Label>'){
/// your stuff
}
},
"Build Utilities" : {
node('<Label>'){
/// your stuff
}
}
)
}
}
All VMs should be labelled as to use as a pool.
in the end of your Index.js need to add this Code:
import React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import { BrowserRouter } from 'react-router-dom';_x000D_
_x000D_
import './index.css';_x000D_
import App from './App';_x000D_
_x000D_
import { Provider } from 'react-redux';_x000D_
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';_x000D_
import thunk from 'redux-thunk';_x000D_
_x000D_
///its your redux ex_x000D_
import productReducer from './redux/reducer/admin/product/produt.reducer.js'_x000D_
_x000D_
const rootReducer = combineReducers({_x000D_
adminProduct: productReducer_x000D_
_x000D_
})_x000D_
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;_x000D_
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));_x000D_
_x000D_
_x000D_
const app = (_x000D_
<Provider store={store}>_x000D_
<BrowserRouter basename='/'>_x000D_
<App />_x000D_
</BrowserRouter >_x000D_
</Provider>_x000D_
);_x000D_
ReactDOM.render(app, document.getElementById('root'));
_x000D_
Got the same issue outside of Android Studio, when trying to build for Cordova using the sdk from command line (cordova build android).
The solution provided by Rudy works in this case too. You just don't downgrade the version of Build Tools from Android Studio but you do it using the android sdk manager ui.
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}
For any users having the same issue in 2017, I solved it the following way:
NavBar.contextTypes = {
router: React.PropTypes.object,
location: React.PropTypes.object
}
and use it like this:
componentDidMount () {
console.log(this.context.location.pathname);
}
I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.
sudo apt-get install openjfx
I just had to delete and reinstall my google-services.json
and then restart Android Studio.
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Nothing worked for me but:
componentDidMount(){
$( document ).ready(function() {
window.scrollTo(0,0);
});
}
Per Spring Data REST docs, if using application.properties, use this property to set your base path:
spring.data.rest.basePath=/api
But note that Spring uses relaxed binding, so this variation can be used:
spring.data.rest.base-path=/api
... or this one if you prefer:
spring.data.rest.base_path=/api
If using application.yml, you would use colons for key separators:
spring:
data:
rest:
basePath: /api
(For reference, a related ticket was created in March 2018 to clarify the docs.)
You want to use Test-Path
:
Test-Path <path to file> -PathType Leaf
According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.
For ES6 + React components, the following solution worked for me.
I followed Felippe skinner, but added an end to end solution to help beginners like me.
Below are the versions I used:
"react-router": "^2.7.0"
"react": "^15.3.1"
Below is my react component where I used programmatic navigation using react-router:
import React from 'react';
class loginComp extends React.Component {
constructor( context) {
super(context);
this.state = {
uname: '',
pwd: ''
};
}
redirectToMainPage(){
this.context.router.replace('/home');
}
render(){
return <div>
// skipping html code
<button onClick={this.redirectToMainPage.bind(this)}>Redirect</button>
</div>;
}
};
loginComp.contextTypes = {
router: React.PropTypes.object.isRequired
}
module.exports = loginComp;
Below is the configuration for my router:
import { Router, Route, IndexRedirect, browserHistory } from 'react-router'
render(<Router history={browserHistory}>
<Route path='/' component={ParentComp}>
<IndexRedirect to = "/login"/>
<Route path='/login' component={LoginComp}/>
<Route path='/home' component={HomeComp}/>
<Route path='/repair' component={RepairJobComp} />
<Route path='/service' component={ServiceJobComp} />
</Route>
</Router>, document.getElementById('root'));
Check out my working example using React 16.0 with React-router v4 Live Example. check out the code Github
Use withRouter
and history.goBack()
This is the idea I am implementing...
History.js
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import './App.css'
class History extends Component {
handleBack = () => {
this.props.history.goBack()
}
handleForward = () => {
console.log(this.props.history)
this.props.history.go(+1)
}
render() {
return <div className="container">
<div className="row d-flex justify-content-between">
<span onClick={this.handleBack} className="d-flex justify-content-start button">
<i className="fas fa-arrow-alt-circle-left fa-5x"></i>
</span>
<span onClick={this.handleForward} className="d-flex justify-content-end button">
<i className="fas fa-arrow-alt-circle-right fa-5x"></i>
</span>
</div>
</div>
}
}
export default withRouter(History)
PageOne.js
import React, { Fragment, Component } from 'react'
class PageOne extends Component {
componentDidMount(){
if(this.props.location.state && this.props.location.state.from != '/pageone')
this.props.history.push({
pathname: '/pageone',
state: {
from: this.props.location.pathname
}
});
}
render() {
return (
<Fragment>
<div className="container-fluid">
<div className="row d-flex justify-content-center">
<h2>Page One</h2>
</div>
</div>
</Fragment>
)
}
}
export default PageOne
p.s. sorry the code is to big to post it all here
Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.
devtool: '#inline-source-map',
debug: true,
and in loaders I kept babel-loader as first option
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")]
},
{ test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
{ test: /\.html$/, loader: 'raw' },
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{test: /\.less$/, loader: "style!css!less"},
{ test: /\.styl$/, loader: 'style!css!stylus' },
{ test: /\.css$/, loader: 'style!css' }
]
You can do the following to install java 8 on your machine. First get the link of tar
that you want to install. You can do this by:
- go to java downloads page and find the appropriate download.
- Accept the license agreement and download it.
- In the download page in your browser right click and
copy link address
.
Then in your terminal:
$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java
First you should have Java 7. If you don't have, install it first (I don't know what you are using, Linux, Mac, yum, apt, homebrew, you should find out yourself.)
If you already have Java 7, run:
echo $JAVA_HOME
Output should be something like this:/usr/lib/jvm/java-8-oracle
. Near this directory, you should see java-7
directory. After you found it, run
export JAVA_HOME=${java-7-dir}
Change {java-7-dir}
with your directory path. Then you can run your command.
This is only a temporary solution. To change it permanently, put the above command to your ~/.bashrc
file.
EDIT: If you are using Windows, change environment variable of JAVA_HOME
to your Java 7 installation directory path.
Here is another way:
df['rnd'] = np.random.rand(len(df))
df = df.sort_values(by='rnd', inplace=True).drop('rnd', axis=1)
The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
In my case my JDK installation is jdk1.8.0_40, make sure you type yours.
Then you can use maven commands.
Regards!
Check this has everything you need
http://www.html5rocks.com/en/mobile/fullscreen/
The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.
<meta name="mobile-web-app-capable" content="yes">
You can also use findIndex and pick to achieve the same result:
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
var data = {id: 2, name: 'Person 2 (updated)'};
var index = _.findIndex(arr, _.pick(data, 'id'));
if( index !== -1) {
arr.splice(index, 1, data);
} else {
arr.push(data);
}
Another programmatic Kotlin Alternative:
mButton.transformationMethod = null
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.
<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:background">#FF0000</item>
<item name="android:textColorPrimary">#0000FF</item>
</style>
You can then apply your theme to the toolbar:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:theme="@style/MyToolbar"
android:minHeight="?attr/actionBarSize"/>
> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
a b
"numeric" "numeric"
string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"
With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.
On a Mac, you need to use this command:
STATIC_DEPS=true sudo pip install lxml
I know this is an old question. But I figure out an alternative way to use the library in Swift project, which might be helpful for those who don't want to import framework introduced in these answers.
In Swift project, create a Objective-C bridging header, create NSData category (or custom class that to use the library) in Objective-C. The only drawback would be that you have to write all implementation code in Objective-C. For example:
#import "NSData+NSDataEncryptionExtension.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation NSData (NSDataEncryptionExtension)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
//do something
}
- (NSData *)AES256DecryptWithKey:(NSString *)key {
//do something
}
And then in your objective-c bridging header, add this
#import "NSData+NSDataEncryptionExtension.h"
And then in Swift class do similar thing:
public extension String {
func encryp(withKey key:String) -> String? {
if let data = self.data(using: .utf8), let encrypedData = NSData(data: data).aes256Encrypt(withKey: key) {
return encrypedData.base64EncodedString()
}
return nil
}
func decryp(withKey key:String) -> String? {
if let data = NSData(base64Encoded: self, options: []), let decrypedData = data.aes256Decrypt(withKey: key) {
return decrypedData.UTF8String
}
return nil
}
}
It works as expected.
Have you tried passing -funroll-loops -fprefetch-loop-arrays
to GCC?
I get the following results with these additional optimizations:
[1829] /tmp/so_25078285 $ cat /proc/cpuinfo |grep CPU|head -n1
model name : Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz
[1829] /tmp/so_25078285 $ g++ --version|head -n1
g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
[1829] /tmp/so_25078285 $ g++ -O3 -march=native -std=c++11 test.cpp -o test_o3
[1829] /tmp/so_25078285 $ g++ -O3 -march=native -funroll-loops -fprefetch-loop-arrays -std=c++11 test.cpp -o test_o3_unroll_loops__and__prefetch_loop_arrays
[1829] /tmp/so_25078285 $ ./test_o3 1
unsigned 41959360000 0.595 sec 17.6231 GB/s
uint64_t 41959360000 0.898626 sec 11.6687 GB/s
[1829] /tmp/so_25078285 $ ./test_o3_unroll_loops__and__prefetch_loop_arrays 1
unsigned 41959360000 0.618222 sec 16.9612 GB/s
uint64_t 41959360000 0.407304 sec 25.7443 GB/s
As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el))
method will produce the following warning:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
Converting your columns to numpy arrays should do the job (I prefer StandardScaler):
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())
-- Edit Nov 2018 (Tested for pandas 0.23.4)--
As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix()
returns FutureWarning
. Therefore, it should be replaced by .values
:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit_transform(dfTest[['A','B']].values)
-- Edit May 2019 (Tested for pandas 0.24.2)--
As joelostblom mentions in the comments, "Since 0.24.0
, it is recommended to use .to_numpy()
instead of .values
."
Updated example:
import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
A B C
0 -1.995290 -1.571117 big
1 0.436356 -0.603995 small
2 0.460289 0.100818 big
3 0.630058 0.985826 small
4 0.468586 1.088469 small
None of the other answers were "sticking" for me in RHEL 7, even setting JAVA_HOME
and PATH
directly in /etc/profile
or ~/.bash_profile
would not work. Each time I tried to check if JAVA_HOME
was set, it would come up blank:
$ echo $JAVA_HOME
(<-- no output)
What I had to do was set up a script in /etc/profile.d/jdk_home.sh
:
#!/bin/sh
export JAVA_HOME=/opt/ibm/java-x86_64-60/
export PATH=$JAVA_HOME/bin:$PATH
I initially neglected the first line (the #!/bin/sh
), and it won't work without it.
Now it's working:
$ echo $JAVA_HOME
/opt/ibm/java-x86_64-60/
Here's how to fix this error when launching Eclipse:
Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.
Go and install latest JDK
Make sure you have installed 64 bit Eclipse
Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.
Sometimes, when all else fails, you just want to tell pandas to shut up about it:
# Ignore DtypeWarnings from pandas' read_csv
warnings.filterwarnings('ignore', message="^Columns.*")
I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.
Hope this helps someone.
If you are getting this problem when converting wsdl to jave with the cxf-codegen-plugin, then you can solve it by configuring the plugin to fork and provide the additional "-Djavax.xml.accessExternalSchema=all" JVM option.
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<fork>always</fork>
<additionalJvmArgs>
-Djavax.xml.accessExternalSchema=all
</additionalJvmArgs>
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
Using CSS Grid
HTML
<div class="container">
<i class="fab fa-5x fa-file"></i>
<span>text</span>
</div>
CSS
.container {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
}
Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
For me an explicit set on the arguments section of the external tools configuration in Eclipse was the problem.
This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level
You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property
You can do that by following steps:
Here is what I had and what caused my "incomplete type error":
#include "X.h" // another already declared class
class Big {...} // full declaration of class A
class Small : Big {
Small() {}
Small(X); // line 6
}
//.... all other stuff
What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..
Small::Big(X my_x) { // line 9 <--- LOOK at this !
}
I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..
Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
BLOB
primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB
intended to retain character-based data.
you can use this
import pandas as pd
dataset=pd.read_csv("filepath.txt",delimiter="\t")
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer
, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)
Same caution to run as the user you need to access permissions with applies.
Simple run your project online i.e mvn clean install
. It fetches all the latest dependencies that you mention in your pom.xml and built the project
Don't include bin folder while coping the path for Java_home.
I could solve the issue simply by replacing the JPA api jar file which is located jboss7/modules/javax/persistence/api/main with 'hibernate-jpa-2.1-api'. also with updating module.xml in the directory.
You don't have a field named user_email
in the members table
... as for why, I'm not sure as the code "looks" like it should try to join on different fields
Does the Auth::attempt method perform a join of the schema?
Run grep -Rl 'class Auth' /path/to/framework
and find where the attempt
method is and what it does.
Eureka ! Finally I found a solution on this.
This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.
Start >> All Programs >> Accessories >> System Tools >> System Restore.
And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)
Only for .NET Core Web API project, add following changes:
services.AddMvc()
line in the ConfigureServices()
method of the Startup.cs file:services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
app.UseMvc()
line in the Configure()
method of the Startup.cs file:app.UseCors(options => options.AllowAnyOrigin());
[EnableCors("AllowOrigin")]
This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.
Check Mike's answer to his own question here: stackoverflow question 24705877
This solved the issue for me both command line AND within eclipse.
Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
I had a similar issue with mongoose :
fields:
[ '[object Object]',
'[object Object]',
'[object Object]',
'[object Object]' ] }
In fact, I was using "type" as a property name in my schema :
fields: [
{
name: String,
type: {
type: String
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
To avoid that behavior, you have to change the parameter to :
fields: [
{
name: String,
type: {
type: { type: String }
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
or use display property with table-cell;
css
.table-layout {
display:table;
width:100%;
}
.table-layout .table-cell {
display:table-cell;
border:solid 1px #ccc;
}
.fixed-width-200 {
width:200px;
}
html
<div class="table-layout">
<div class="table-cell fixed-width-200">
<p>fixed width div</p>
</div>
<div class="table-cell">
<p>fluid width div</p>
</div>
</div>
For Eclipse Users. If you have a Run Configuration that does clean package for example.
In the Run Configuration panel there is a JRE tab where you can specify against which runtime it should run. Note that this configuration overrides whatever is in the pom.xml.
In Windows open the Run window (Win + R):
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --allow-running-insecure-content
In OS-X Terminal.app
run the following command ⌘+space:
open /Applications/Google\ Chrome.app --args --allow-running-insecure-content
Note:
You seem to be able to add the argument --allow-running-insecure-content
to bypass this for development. But its not a recommended solution.
If you are consuming an internal service via AJAX, make sure the url points to https, this cleared up the error for me.
Initial AJAX URL: "http://XXXXXX.com/Core.svc/" + ApiName
Corrected AJAX URL: "https://XXXXXX.com/Core.svc/" + ApiName,
Create /res/drawable/button.xml
with the following content :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
<solid android:color="#90EE90"/>
<corners
android:bottomRightRadius="3dp"
android:bottomLeftRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp"/>
</shape>
And then you can use the following :
<Button
android:id="@+id/button_save_prefs"
android:text="@string/save"
android:background="@drawable/button"/>
In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))
In [17]: df
Out[17]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [18]: df.dtypes
Out[18]:
A int64
B int64
dtype: object
Convert a series
In [19]: df['A'].apply(str)
Out[19]:
0 0
1 2
2 4
3 6
4 8
Name: A, dtype: object
In [20]: df['A'].apply(str)[0]
Out[20]: '0'
Don't forget to assign the result back:
df['A'] = df['A'].apply(str)
Convert the whole frame
In [21]: df.applymap(str)
Out[21]:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'
df = df.applymap(str)
Python 3.6+ provides built-in convenience methods to find and decode the plain text body as in @Todor Minakov
's answer. You can use the EMailMessage.get_body()
and get_content()
methods:
msg = email.message_from_string(s, policy=email.policy.default)
body = msg.get_body(('plain',))
if body:
body = body.get_content()
print(body)
Note this will give None
if there is no (obvious) plain text body part.
If you are reading from e.g. an mbox file, you can give the mailbox constructor an EmailMessage
factory:
mbox = mailbox.mbox(mboxfile, factory=lambda f: email.message_from_binary_file(f, policy=email.policy.default), create=False)
for msg in mbox:
...
Note you must pass email.policy.default
as the policy, since it's not the default...
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
To avoid 'Unclosed block: CssSyntaxError' errors being thrown from sass compilers add a ';' to the end of @content.
@mixin placeholder {
::-webkit-input-placeholder { @content;}
:-moz-placeholder { @content;}
::-moz-placeholder { @content;}
:-ms-input-placeholder { @content;}
}
$whereis java
java: /usr/bin/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz
$cd /usr/bin
$ls -l java
lrwxrwxrwx 1 root root 22 Apr 15 2014 java -> /etc/alternatives/java
$ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 39 Apr 15 2014 /etc/alternatives/java -> /usr/lib/jvm/java-7-oracle/jre/bin/java
So,JDK's real location is /usr/lib/jvm/java-7-oracle/
Since the methods used in other answers seems quite complicated for such easy task, here is a new answer:
Instead of a ListedColormap
, which produces a discrete colormap, you may use a LinearSegmentedColormap
. This can easily be created from a list using the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
norm=plt.Normalize(-2,2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
More generally, if you have a list of values (e.g. [-2., -1, 2]
) and corresponding colors, (e.g. ["red","violet","blue"]
), such that the n
th value should correspond to the n
th color, you can normalize the values and supply them as tuples to the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
cvals = [-2., -1, 2]
colors = ["red","violet","blue"]
norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package
in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
Starting with the following sample data :
df <- data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],stringsAsFactors=FALSE)
v1 v2 v3
1 a 1 j
2 b 2 k
3 c 3 l
4 d 4 m
5 e 5 n
You can use :
data.frame(lapply(df, function(v) {
if (is.character(v)) return(toupper(v))
else return(v)
}))
Which gives :
v1 v2 v3
1 A 1 J
2 B 2 K
3 C 3 L
4 D 4 M
5 E 5 N
In addition to flup's answer you might also want to run the following to set JAVA_HOME and PATH:
sudo apt-get install oracle-java7-set-default
More information at: http://www.ubuntuupdates.org/package/webupd8_java/precise/main/base/oracle-java7-set-default
The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:
tcp:name.cloudapp.net,1433
theMaxx answer works in nuxt/vue, smooth scrolling is default behavior
<button @click=scrollToTop()>Jump to top of page
methods: {
scrollToTop() {
window.scrollTo({ top: 0 });
}
}
In typical usage (responses<2GB) it is not necessary to Dispose the HttpResponseMessages.
The return types of the HttpClient methods should be Disposed if their Stream Content is not fully Read. Otherwise there is no way for the CLR to know those Streams can be closed until they are garbage collected.
If you set the HttpCompletionOption to ResponseHeadersRead or the response is larger than 2GB, you should clean up. This can be done by calling Dispose on the HttpResponseMessage or by calling Dispose/Close on the Stream obtained from the HttpResonseMessage Content or by reading the content completely.
Whether you call Dispose on the HttpClient depends on whether you want to cancel pending requests or not.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Node.js is built upon libuv, a cross-platform library that abstracts apis/syscalls for asynchronous (non-blocking) input/output provided by the supported OSes (Unix, OS X and Windows at least).
In this programming model open/read/write operation on devices and resources (sockets, filesystem, etc.) managed by the file-system don't block the calling thread (as in the typical synchronous c-like model) and just mark the process (in kernel/OS level data structure) to be notified when new data or events are available. In case of a web-server-like app, the process is then responsible to figure out which request/context the notified event belongs to and proceed processing the request from there. Note that this will necessarily mean you'll be on a different stack frame from the one that originated the request to the OS as the latter had to yield to a process' dispatcher in order for a single threaded process to handle new events.
The problem with the model I described is that it's not familiar and hard to reason about for the programmer as it's non-sequential in nature. "You need to make request in function A and handle the result in a different function where your locals from A are usually not available."
Node tackles the problem leveraging javascript's language features to make this model a little more synchronous-looking by inducing the programmer to employ a certain programming style. Every function that requests IO has a signature like function (... parameters ..., callback)
and needs to be given a callback that will be invoked when the requested operation is completed (keep in mind that most of the time is spent waiting for the OS to signal the completion - time that can be spent doing other work). Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently. See also Continuation Passing Style.
Moreover, after invoking a function spawning an IO operation the calling function will usually return
control to node's event loop. This loop will invoke the next callback or function that was scheduled for execution (most likely because the corresponding event was notified by the OS) - this allows the concurrent processing of multiple requests.
You can think of node's event loop as somewhat similar to the kernel's dispatcher: the kernel would schedule for execution a blocked thread once its pending IO is completed while node will schedule a callback when the corresponding event has occured.
As a final remark, the phrase "everything runs in parallel except your code" does a decent job of capturing the point that node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution (even though saying "everything runs in parallel" is probably not correct here - see Concurrency vs Parallelism - What is the difference?). This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.
Update:
// use it like this
obj?.a?.lot?.of?.properties
Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:
A quick workaround is using a try/catch helper function with ES6 arrow function:
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
_x000D_
To decode json, you have to pass the json string. Currently you're trying to pass an object:
>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>
You can fetch the data with response.read()
.
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
I think the answers above are missing a simple approach that I've found very useful.
When I have a file that is too large to load in memory, I break up the file into multiple smaller files (either by row or cols)
Example: In case of 30 days worth of trading data of ~30GB size, I break it into a file per day of ~1GB size. I subsequently process each file separately and aggregate results at the end
One of the biggest advantages is that it allows parallel processing of the files (either multiple threads or processes)
The other advantage is that file manipulation (like adding/removing dates in the example) can be accomplished by regular shell commands, which is not be possible in more advanced/complicated file formats
This approach doesn't cover all scenarios, but is very useful in a lot of them
if re.search(r'pattern', string):
Simple if-test:
if re.search(r'ing\b', "seeking a great perhaps"): # any words end with ing?
print("yes")
Pattern check, extract a substring, case insensitive:
match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
assert "to" == match_object.group(1) # what's between ought and be?
Notes:
Use re.search()
not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A
instead, re.search(r'^...', ...)
Use raw string syntax r'pattern'
for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)
In this example, \b
is a special sequence meaning word-boundary in regex. Not to be confused with backspace.
re.search()
returns None
if it doesn't find anything, which is always falsy.
re.search()
returns a Match object if it finds anything, which is always truthy.
a group is what matched inside parentheses
group numbering starts at 1
The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie
results in another call to poruszanie
, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.
Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.
Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.
The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843
A simple 4on4 pasting function that works-
def paste(background,foreground,pos=(0,0)):
#get position and crop pasting area if needed
x = pos[0]
y = pos[1]
bgWidth = background.shape[0]
bgHeight = background.shape[1]
frWidth = foreground.shape[0]
frHeight = foreground.shape[1]
width = bgWidth-x
height = bgHeight-y
if frWidth<width:
width = frWidth
if frHeight<height:
height = frHeight
# normalize alpha channels from 0-255 to 0-1
alpha_background = background[x:x+width,y:y+height,3] / 255.0
alpha_foreground = foreground[:width,:height,3] / 255.0
# set adjusted colors
for color in range(0, 3):
fr = alpha_foreground * foreground[:width,:height,color]
bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
background[x:x+width,y:y+height,color] = fr+bg
# set adjusted alpha and denormalize back to 0-255
background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
return background
Not sure what the OS is in use here, but you can eliminate a lot of java version futzing un debian/ubuntu with update-java-alternatives to set the default jvm system wide.
#> update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-6-sun 63 /usr/lib/jvm/java-6-sun
java-7-oracle 1073 /usr/lib/jvm/java-7-oracle
To set a new one, use:
#> update-java-alternatives -s java-7-oracle
No need to set JAVA_HOME for most apps.
If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME
environment variable value for each build. Instead execute Maven like:
JAVA_HOME=/path/to/your/jdk mvn clean install
It will build using the specified JDK, but it won't change your environment variable.
Demo:
$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.
var node = require("deasync");
node.loop = node.runLoopOnce;
var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
done = 1;
});
while (!done)
node.loop();
// Now, here you go
-Wdeclaration-after-statement
minimal reproducible example
main.c
#!/usr/bin/env bash
set -eux
cat << EOF > main.c
#include <stdio.h>
int main(void) {
puts("hello");
int a = 1;
printf("%d\n", a);
return 0;
}
EOF
Give warning:
gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c
Don't give warning:
gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c
The warning:
main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
int a = 1;
^~~
Tested on Ubuntu 16.04, GCC 6.4.0.
In Eclipse, go to Build Path, click "Add Library", select JRE System Library, click "Next", select option "Workspace default JRE(i)", and click "Finish".
This worked for me.
In my case, the issue was that Oracle was installing it to a different location than I was used to.
Download from Oracle: http://java.com/en/download/mac_download.jsp?locale=en
Verify that it's installed properly by looking in System Prefs:
Verify that the version is as you expect (sub in your path as needed):
/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -version
Create link from /usr/bin/java to your new install
sudo ln -fs /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
Sanity check your version:
java -version
From Laravel 5.7 with Illuminate\Database\Query\Builder
you can use insertUsing method.
$query = [];
foreach($oXML->results->item->item as $oEntry){
$date = date("Y-m-d H:i:s")
$query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}
Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));
This answer covers:
There are a number of ways to retrieve data from multiple tables in a database. In this answer, I will be using ANSI-92 join syntax. This may be different to a number of other tutorials out there which use the older ANSI-89 syntax (and if you are used to 89, may seem much less intuitive - but all I can say is to try it) as it is much easier to understand when the queries start getting more complex. Why use it? Is there a performance gain? The short answer is no, but it is easier to read once you get used to it. It is easier to read queries written by other folks using this syntax.
I am also going to use the concept of a small caryard which has a database to keep track of what cars it has available. The owner has hired you as his IT Computer guy and expects you to be able to drop him the data that he asks for at the drop of a hat.
I have made a number of lookup tables that will be used by the final table. This will give us a reasonable model to work from. To start off, I will be running my queries against an example database that has the following structure. I will try to think of common mistakes that are made when starting out and explain what goes wrong with them - as well as of course showing how to correct them.
The first table is simply a color listing so that we know what colors we have in the car yard.
mysql> create table colors(id int(3) not null auto_increment primary key,
-> color varchar(15), paint varchar(10));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | varchar(15) | YES | | NULL | |
| paint | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
mysql> insert into colors (color, paint) values ('Red', 'Metallic'),
-> ('Green', 'Gloss'), ('Blue', 'Metallic'),
-> ('White' 'Gloss'), ('Black' 'Gloss');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from colors;
+----+-------+----------+
| id | color | paint |
+----+-------+----------+
| 1 | Red | Metallic |
| 2 | Green | Gloss |
| 3 | Blue | Metallic |
| 4 | White | Gloss |
| 5 | Black | Gloss |
+----+-------+----------+
5 rows in set (0.00 sec)
The brands table identifies the different brands of the cars out caryard could possibly sell.
mysql> create table brands (id int(3) not null auto_increment primary key,
-> brand varchar(15));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from brands;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| brand | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
mysql> insert into brands (brand) values ('Ford'), ('Toyota'),
-> ('Nissan'), ('Smart'), ('BMW');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from brands;
+----+--------+
| id | brand |
+----+--------+
| 1 | Ford |
| 2 | Toyota |
| 3 | Nissan |
| 4 | Smart |
| 5 | BMW |
+----+--------+
5 rows in set (0.00 sec)
The model table will cover off different types of cars, it is going to be simpler for this to use different car types rather than actual car models.
mysql> create table models (id int(3) not null auto_increment primary key,
-> model varchar(15));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from models;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| model | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> insert into models (model) values ('Sports'), ('Sedan'), ('4WD'), ('Luxury');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from models;
+----+--------+
| id | model |
+----+--------+
| 1 | Sports |
| 2 | Sedan |
| 3 | 4WD |
| 4 | Luxury |
+----+--------+
4 rows in set (0.00 sec)
And finally, to tie up all these other tables, the table that ties everything together. The ID field is actually the unique lot number used to identify cars.
mysql> create table cars (id int(3) not null auto_increment primary key,
-> color int(3), brand int(3), model int(3));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from cars;
+-------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | int(3) | YES | | NULL | |
| brand | int(3) | YES | | NULL | |
| model | int(3) | YES | | NULL | |
+-------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> insert into cars (color, brand, model) values (1,2,1), (3,1,2), (5,3,1),
-> (4,4,2), (2,2,3), (3,5,4), (4,1,3), (2,2,1), (5,2,3), (4,5,1);
Query OK, 10 rows affected (0.00 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from cars;
+----+-------+-------+-------+
| id | color | brand | model |
+----+-------+-------+-------+
| 1 | 1 | 2 | 1 |
| 2 | 3 | 1 | 2 |
| 3 | 5 | 3 | 1 |
| 4 | 4 | 4 | 2 |
| 5 | 2 | 2 | 3 |
| 6 | 3 | 5 | 4 |
| 7 | 4 | 1 | 3 |
| 8 | 2 | 2 | 1 |
| 9 | 5 | 2 | 3 |
| 10 | 4 | 5 | 1 |
+----+-------+-------+-------+
10 rows in set (0.00 sec)
This will give us enough data (I hope) to cover off the examples below of different types of joins and also give enough data to make them worthwhile.
So getting into the grit of it, the boss wants to know The IDs of all the sports cars he has.
This is a simple two table join. We have a table that identifies the model and the table with the available stock in it. As you can see, the data in the model
column of the cars
table relates to the models
column of the cars
table we have. Now, we know that the models table has an ID of 1
for Sports
so lets write the join.
select
ID,
model
from
cars
join models
on model=ID
So this query looks good right? We have identified the two tables and contain the information we need and use a join that correctly identifies what columns to join on.
ERROR 1052 (23000): Column 'ID' in field list is ambiguous
Oh noes! An error in our first query! Yes, and it is a plum. You see, the query has indeed got the right columns, but some of them exist in both tables, so the database gets confused about what actual column we mean and where. There are two solutions to solve this. The first is nice and simple, we can use tableName.columnName
to tell the database exactly what we mean, like this:
select
cars.ID,
models.model
from
cars
join models
on cars.model=models.ID
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
| 2 | Sedan |
| 4 | Sedan |
| 5 | 4WD |
| 7 | 4WD |
| 9 | 4WD |
| 6 | Luxury |
+----+--------+
10 rows in set (0.00 sec)
The other is probably more often used and is called table aliasing. The tables in this example have nice and short simple names, but typing out something like KPI_DAILY_SALES_BY_DEPARTMENT
would probably get old quickly, so a simple way is to nickname the table like this:
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
Now, back to the request. As you can see we have the information we need, but we also have information that wasn't asked for, so we need to include a where clause in the statement to only get the Sports cars as was asked. As I prefer the table alias method rather than using the table names over and over, I will stick to it from this point onwards.
Clearly, we need to add a where clause to our query. We can identify Sports cars either by ID=1
or model='Sports'
. As the ID is indexed and the primary key (and it happens to be less typing), lets use that in our query.
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
where
b.ID=1
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)
Bingo! The boss is happy. Of course, being a boss and never being happy with what he asked for, he looks at the information, then says I want the colors as well.
Okay, so we have a good part of our query already written, but we need to use a third table which is colors. Now, our main information table cars
stores the car color ID and this links back to the colors ID column. So, in a similar manner to the original, we can join a third table:
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
where
b.ID=1
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)
Damn, although the table was correctly joined and the related columns were linked, we forgot to pull in the actual information from the new table that we just linked.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
where
b.ID=1
+----+--------+-------+
| ID | model | color |
+----+--------+-------+
| 1 | Sports | Red |
| 8 | Sports | Green |
| 10 | Sports | White |
| 3 | Sports | Black |
+----+--------+-------+
4 rows in set (0.00 sec)
Right, that's the boss off our back for a moment. Now, to explain some of this in a little more detail. As you can see, the from
clause in our statement links our main table (I often use a table that contains information rather than a lookup or dimension table. The query would work just as well with the tables all switched around, but make less sense when we come back to this query to read it in a few months time, so it is often best to try to write a query that will be nice and easy to understand - lay it out intuitively, use nice indenting so that everything is as clear as it can be. If you go on to teach others, try to instill these characteristics in their queries - especially if you will be troubleshooting them.
It is entirely possible to keep linking more and more tables in this manner.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
While I forgot to include a table where we might want to join more than one column in the join
statement, here is an example. If the models
table had brand-specific models and therefore also had a column called brand
which linked back to the brands
table on the ID
field, it could be done as this:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
and b.brand=d.ID
where
b.ID=1
You can see, the query above not only links the joined tables to the main cars
table, but also specifies joins between the already joined tables. If this wasn't done, the result is called a cartesian join - which is dba speak for bad. A cartesian join is one where rows are returned because the information doesn't tell the database how to limit the results, so the query returns all the rows that fit the criteria.
So, to give an example of a cartesian join, lets run the following query:
select
a.ID,
b.model
from
cars a
join models b
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 1 | Sedan |
| 1 | 4WD |
| 1 | Luxury |
| 2 | Sports |
| 2 | Sedan |
| 2 | 4WD |
| 2 | Luxury |
| 3 | Sports |
| 3 | Sedan |
| 3 | 4WD |
| 3 | Luxury |
| 4 | Sports |
| 4 | Sedan |
| 4 | 4WD |
| 4 | Luxury |
| 5 | Sports |
| 5 | Sedan |
| 5 | 4WD |
| 5 | Luxury |
| 6 | Sports |
| 6 | Sedan |
| 6 | 4WD |
| 6 | Luxury |
| 7 | Sports |
| 7 | Sedan |
| 7 | 4WD |
| 7 | Luxury |
| 8 | Sports |
| 8 | Sedan |
| 8 | 4WD |
| 8 | Luxury |
| 9 | Sports |
| 9 | Sedan |
| 9 | 4WD |
| 9 | Luxury |
| 10 | Sports |
| 10 | Sedan |
| 10 | 4WD |
| 10 | Luxury |
+----+--------+
40 rows in set (0.00 sec)
Good god, that's ugly. However, as far as the database is concerned, it is exactly what was asked for. In the query, we asked for for the ID
from cars
and the model
from models
. However, because we didn't specify how to join the tables, the database has matched every row from the first table with every row from the second table.
Okay, so the boss is back, and he wants more information again. I want the same list, but also include 4WDs in it.
This however, gives us a great excuse to look at two different ways to accomplish this. We could add another condition to the where clause like this:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
or b.ID=3
While the above will work perfectly well, lets look at it differently, this is a great excuse to show how a union
query will work.
We know that the following will return all the Sports cars:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
And the following would return all the 4WDs:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=3
So by adding a union all
clause between them, the results of the second query will be appended to the results of the first query.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
union all
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=3
+----+--------+-------+
| ID | model | color |
+----+--------+-------+
| 1 | Sports | Red |
| 8 | Sports | Green |
| 10 | Sports | White |
| 3 | Sports | Black |
| 5 | 4WD | Green |
| 7 | 4WD | White |
| 9 | 4WD | Black |
+----+--------+-------+
7 rows in set (0.00 sec)
As you can see, the results of the first query are returned first, followed by the results of the second query.
In this example, it would of course have been much easier to simply use the first query, but union
queries can be great for specific cases. They are a great way to return specific results from tables from tables that aren't easily joined together - or for that matter completely unrelated tables. There are a few rules to follow however.
Now, you might be wondering what the difference is between using union
and union all
. A union
query will remove duplicates, while a union all
will not. This does mean that there is a small performance hit when using union
over union all
but the results may be worth it - I won't speculate on that sort of thing in this though.
On this note, it might be worth noting some additional notes here.
order by
but you can't use the alias anymore. In the query above, appending an order by a.ID
would result in an error - as far as the results are concerned, the column is called ID
rather than a.ID
- even though the same alias has been used in both queries.order by
statement, and it must be as the last statement.For the next examples, I am adding a few extra rows to our tables.
I have added Holden
to the brands table.
I have also added a row into cars
that has the color
value of 12
- which has no reference in the colors table.
Okay, the boss is back again, barking requests out - *I want a count of each brand we carry and the number of cars in it!` - Typical, we just get to an interesting section of our discussion and the boss wants more work.
Rightyo, so the first thing we need to do is get a complete listing of possible brands.
select
a.brand
from
brands a
+--------+
| brand |
+--------+
| Ford |
| Toyota |
| Nissan |
| Smart |
| BMW |
| Holden |
+--------+
6 rows in set (0.00 sec)
Now, when we join this to our cars table we get the following result:
select
a.brand
from
brands a
join cars b
on a.ID=b.brand
group by
a.brand
+--------+
| brand |
+--------+
| BMW |
| Ford |
| Nissan |
| Smart |
| Toyota |
+--------+
5 rows in set (0.00 sec)
Which is of course a problem - we aren't seeing any mention of the lovely Holden
brand I added.
This is because a join looks for matching rows in both tables. As there is no data in cars that is of type Holden
it isn't returned. This is where we can use an outer
join. This will return all the results from one table whether they are matched in the other table or not:
select
a.brand
from
brands a
left outer join cars b
on a.ID=b.brand
group by
a.brand
+--------+
| brand |
+--------+
| BMW |
| Ford |
| Holden |
| Nissan |
| Smart |
| Toyota |
+--------+
6 rows in set (0.00 sec)
Now that we have that, we can add a lovely aggregate function to get a count and get the boss off our backs for a moment.
select
a.brand,
count(b.id) as countOfBrand
from
brands a
left outer join cars b
on a.ID=b.brand
group by
a.brand
+--------+--------------+
| brand | countOfBrand |
+--------+--------------+
| BMW | 2 |
| Ford | 2 |
| Holden | 0 |
| Nissan | 1 |
| Smart | 1 |
| Toyota | 5 |
+--------+--------------+
6 rows in set (0.00 sec)
And with that, away the boss skulks.
Now, to explain this in some more detail, outer joins can be of the left
or right
type. The Left or Right defines which table is fully included. A left outer join
will include all the rows from the table on the left, while (you guessed it) a right outer join
brings all the results from the table on the right into the results.
Some databases will allow a full outer join
which will bring back results (whether matched or not) from both tables, but this isn't supported in all databases.
Now, I probably figure at this point in time, you are wondering whether or not you can merge join types in a query - and the answer is yes, you absolutely can.
select
b.brand,
c.color,
count(a.id) as countOfBrand
from
cars a
right outer join brands b
on b.ID=a.brand
join colors c
on a.color=c.ID
group by
a.brand,
c.color
+--------+-------+--------------+
| brand | color | countOfBrand |
+--------+-------+--------------+
| Ford | Blue | 1 |
| Ford | White | 1 |
| Toyota | Black | 1 |
| Toyota | Green | 2 |
| Toyota | Red | 1 |
| Nissan | Black | 1 |
| Smart | White | 1 |
| BMW | Blue | 1 |
| BMW | White | 1 |
+--------+-------+--------------+
9 rows in set (0.00 sec)
So, why is that not the results that were expected? It is because although we have selected the outer join from cars to brands, it wasn't specified in the join to colors - so that particular join will only bring back results that match in both tables.
Here is the query that would work to get the results that we expected:
select
a.brand,
c.color,
count(b.id) as countOfBrand
from
brands a
left outer join cars b
on a.ID=b.brand
left outer join colors c
on b.color=c.ID
group by
a.brand,
c.color
+--------+-------+--------------+
| brand | color | countOfBrand |
+--------+-------+--------------+
| BMW | Blue | 1 |
| BMW | White | 1 |
| Ford | Blue | 1 |
| Ford | White | 1 |
| Holden | NULL | 0 |
| Nissan | Black | 1 |
| Smart | White | 1 |
| Toyota | NULL | 1 |
| Toyota | Black | 1 |
| Toyota | Green | 2 |
| Toyota | Red | 1 |
+--------+-------+--------------+
11 rows in set (0.00 sec)
As we can see, we have two outer joins in the query and the results are coming through as expected.
Now, how about those other types of joins you ask? What about Intersections?
Well, not all databases support the intersection
but pretty much all databases will allow you to create an intersection through a join (or a well structured where statement at the least).
An Intersection is a type of join somewhat similar to a union
as described above - but the difference is that it only returns rows of data that are identical (and I do mean identical) between the various individual queries joined by the union. Only rows that are identical in every regard will be returned.
A simple example would be as such:
select
*
from
colors
where
ID>2
intersect
select
*
from
colors
where
id<4
While a normal union
query would return all the rows of the table (the first query returning anything over ID>2
and the second anything having ID<4
) which would result in a full set, an intersect query would only return the row matching id=3
as it meets both criteria.
Now, if your database doesn't support an intersect
query, the above can be easily accomlished with the following query:
select
a.ID,
a.color,
a.paint
from
colors a
join colors b
on a.ID=b.ID
where
a.ID>2
and b.ID<4
+----+-------+----------+
| ID | color | paint |
+----+-------+----------+
| 3 | Blue | Metallic |
+----+-------+----------+
1 row in set (0.00 sec)
If you wish to perform an intersection across two different tables using a database that doesn't inherently support an intersection query, you will need to create a join on every column of the tables.
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
BadImageFormatException
, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?
Instead of using AnyCPU/Mixed
as the platform. Try to manually set it to x86
and see if it will run after that.
Hope this helps.
You can nest your queries:
select * from (
select bla
from bla
where bla
order by finaldate desc
)
where rownum < 2
If you are using an old version of FFMPEG and you cant upgrade you can do the following:
ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4
Notice that I used -vcodec
Answer is adding to @Sebas' answer - setting the collation of my local environment. Do not try this on production.
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Source of this solution
Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.
since 1.5.0 u can use the 'inline' keyword.
Example: @import (inline) "not-less-compatible.css";
You will use this when a CSS file may not be Less compatible; this is because although Less supports most known standards CSS, it does not support comments in some places and does not support all known CSS hacks without modifying the CSS. So you can use this to include the file in the output so that all CSS will be in one file.
(source: http://lesscss.org/features/#import-directives-feature)
I tried above samples but not working for me. The simplest solution is working for me awesome:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/Area"/>
</RelativeLayout>
Unfortunately, detecting pinch gestures across browsers is a not as simple as one would hope, but HammerJS makes it a lot easier!
Check out the Pinch Zoom and Pan with HammerJS demo. This example has been tested on Android, iOS and Windows Phone.
You can find the source code at Pinch Zoom and Pan with HammerJS.
For your convenience, here is the source code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport"_x000D_
content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">_x000D_
<title>Pinch Zoom</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div>_x000D_
_x000D_
<div style="height:150px;background-color:#eeeeee">_x000D_
Ignore this area. Space is needed to test on the iPhone simulator as pinch simulation on the_x000D_
iPhone simulator requires the target to be near the middle of the screen and we only respect_x000D_
touch events in the image area. This space is not needed in production._x000D_
</div>_x000D_
_x000D_
<style>_x000D_
_x000D_
.pinch-zoom-container {_x000D_
overflow: hidden;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.pinch-zoom-image {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
</style>_x000D_
_x000D_
<script src="https://hammerjs.github.io/dist/hammer.js"></script>_x000D_
_x000D_
<script>_x000D_
_x000D_
var MIN_SCALE = 1; // 1=scaling when first loaded_x000D_
var MAX_SCALE = 64;_x000D_
_x000D_
// HammerJS fires "pinch" and "pan" events that are cumulative in nature and not_x000D_
// deltas. Therefore, we need to store the "last" values of scale, x and y so that we can_x000D_
// adjust the UI accordingly. It isn't until the "pinchend" and "panend" events are received_x000D_
// that we can set the "last" values._x000D_
_x000D_
// Our "raw" coordinates are not scaled. This allows us to only have to modify our stored_x000D_
// coordinates when the UI is updated. It also simplifies our calculations as these_x000D_
// coordinates are without respect to the current scale._x000D_
_x000D_
var imgWidth = null;_x000D_
var imgHeight = null;_x000D_
var viewportWidth = null;_x000D_
var viewportHeight = null;_x000D_
var scale = null;_x000D_
var lastScale = null;_x000D_
var container = null;_x000D_
var img = null;_x000D_
var x = 0;_x000D_
var lastX = 0;_x000D_
var y = 0;_x000D_
var lastY = 0;_x000D_
var pinchCenter = null;_x000D_
_x000D_
// We need to disable the following event handlers so that the browser doesn't try to_x000D_
// automatically handle our image drag gestures._x000D_
var disableImgEventHandlers = function () {_x000D_
var events = ['onclick', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',_x000D_
'onmouseup', 'ondblclick', 'onfocus', 'onblur'];_x000D_
_x000D_
events.forEach(function (event) {_x000D_
img[event] = function () {_x000D_
return false;_x000D_
};_x000D_
});_x000D_
};_x000D_
_x000D_
// Traverse the DOM to calculate the absolute position of an element_x000D_
var absolutePosition = function (el) {_x000D_
var x = 0,_x000D_
y = 0;_x000D_
_x000D_
while (el !== null) {_x000D_
x += el.offsetLeft;_x000D_
y += el.offsetTop;_x000D_
el = el.offsetParent;_x000D_
}_x000D_
_x000D_
return { x: x, y: y };_x000D_
};_x000D_
_x000D_
var restrictScale = function (scale) {_x000D_
if (scale < MIN_SCALE) {_x000D_
scale = MIN_SCALE;_x000D_
} else if (scale > MAX_SCALE) {_x000D_
scale = MAX_SCALE;_x000D_
}_x000D_
return scale;_x000D_
};_x000D_
_x000D_
var restrictRawPos = function (pos, viewportDim, imgDim) {_x000D_
if (pos < viewportDim/scale - imgDim) { // too far left/up?_x000D_
pos = viewportDim/scale - imgDim;_x000D_
} else if (pos > 0) { // too far right/down?_x000D_
pos = 0;_x000D_
}_x000D_
return pos;_x000D_
};_x000D_
_x000D_
var updateLastPos = function (deltaX, deltaY) {_x000D_
lastX = x;_x000D_
lastY = y;_x000D_
};_x000D_
_x000D_
var translate = function (deltaX, deltaY) {_x000D_
// We restrict to the min of the viewport width/height or current width/height as the_x000D_
// current width/height may be smaller than the viewport width/height_x000D_
_x000D_
var newX = restrictRawPos(lastX + deltaX/scale,_x000D_
Math.min(viewportWidth, curWidth), imgWidth);_x000D_
x = newX;_x000D_
img.style.marginLeft = Math.ceil(newX*scale) + 'px';_x000D_
_x000D_
var newY = restrictRawPos(lastY + deltaY/scale,_x000D_
Math.min(viewportHeight, curHeight), imgHeight);_x000D_
y = newY;_x000D_
img.style.marginTop = Math.ceil(newY*scale) + 'px';_x000D_
};_x000D_
_x000D_
var zoom = function (scaleBy) {_x000D_
scale = restrictScale(lastScale*scaleBy);_x000D_
_x000D_
curWidth = imgWidth*scale;_x000D_
curHeight = imgHeight*scale;_x000D_
_x000D_
img.style.width = Math.ceil(curWidth) + 'px';_x000D_
img.style.height = Math.ceil(curHeight) + 'px';_x000D_
_x000D_
// Adjust margins to make sure that we aren't out of bounds_x000D_
translate(0, 0);_x000D_
};_x000D_
_x000D_
var rawCenter = function (e) {_x000D_
var pos = absolutePosition(container);_x000D_
_x000D_
// We need to account for the scroll position_x000D_
var scrollLeft = window.pageXOffset ? window.pageXOffset : document.body.scrollLeft;_x000D_
var scrollTop = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
_x000D_
var zoomX = -x + (e.center.x - pos.x + scrollLeft)/scale;_x000D_
var zoomY = -y + (e.center.y - pos.y + scrollTop)/scale;_x000D_
_x000D_
return { x: zoomX, y: zoomY };_x000D_
};_x000D_
_x000D_
var updateLastScale = function () {_x000D_
lastScale = scale;_x000D_
};_x000D_
_x000D_
var zoomAround = function (scaleBy, rawZoomX, rawZoomY, doNotUpdateLast) {_x000D_
// Zoom_x000D_
zoom(scaleBy);_x000D_
_x000D_
// New raw center of viewport_x000D_
var rawCenterX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
var rawCenterY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
// Delta_x000D_
var deltaX = (rawCenterX - rawZoomX)*scale;_x000D_
var deltaY = (rawCenterY - rawZoomY)*scale;_x000D_
_x000D_
// Translate back to zoom center_x000D_
translate(deltaX, deltaY);_x000D_
_x000D_
if (!doNotUpdateLast) {_x000D_
updateLastScale();_x000D_
updateLastPos();_x000D_
}_x000D_
};_x000D_
_x000D_
var zoomCenter = function (scaleBy) {_x000D_
// Center of viewport_x000D_
var zoomX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
var zoomY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
zoomAround(scaleBy, zoomX, zoomY);_x000D_
};_x000D_
_x000D_
var zoomIn = function () {_x000D_
zoomCenter(2);_x000D_
};_x000D_
_x000D_
var zoomOut = function () {_x000D_
zoomCenter(1/2);_x000D_
};_x000D_
_x000D_
var onLoad = function () {_x000D_
_x000D_
img = document.getElementById('pinch-zoom-image-id');_x000D_
container = img.parentElement;_x000D_
_x000D_
disableImgEventHandlers();_x000D_
_x000D_
imgWidth = img.width;_x000D_
imgHeight = img.height;_x000D_
viewportWidth = img.offsetWidth;_x000D_
scale = viewportWidth/imgWidth;_x000D_
lastScale = scale;_x000D_
viewportHeight = img.parentElement.offsetHeight;_x000D_
curWidth = imgWidth*scale;_x000D_
curHeight = imgHeight*scale;_x000D_
_x000D_
var hammer = new Hammer(container, {_x000D_
domEvents: true_x000D_
});_x000D_
_x000D_
hammer.get('pinch').set({_x000D_
enable: true_x000D_
});_x000D_
_x000D_
hammer.on('pan', function (e) {_x000D_
translate(e.deltaX, e.deltaY);_x000D_
});_x000D_
_x000D_
hammer.on('panend', function (e) {_x000D_
updateLastPos();_x000D_
});_x000D_
_x000D_
hammer.on('pinch', function (e) {_x000D_
_x000D_
// We only calculate the pinch center on the first pinch event as we want the center to_x000D_
// stay consistent during the entire pinch_x000D_
if (pinchCenter === null) {_x000D_
pinchCenter = rawCenter(e);_x000D_
var offsetX = pinchCenter.x*scale - (-x*scale + Math.min(viewportWidth, curWidth)/2);_x000D_
var offsetY = pinchCenter.y*scale - (-y*scale + Math.min(viewportHeight, curHeight)/2);_x000D_
pinchCenterOffset = { x: offsetX, y: offsetY };_x000D_
}_x000D_
_x000D_
// When the user pinch zooms, she/he expects the pinch center to remain in the same_x000D_
// relative location of the screen. To achieve this, the raw zoom center is calculated by_x000D_
// first storing the pinch center and the scaled offset to the current center of the_x000D_
// image. The new scale is then used to calculate the zoom center. This has the effect of_x000D_
// actually translating the zoom center on each pinch zoom event._x000D_
var newScale = restrictScale(scale*e.scale);_x000D_
var zoomX = pinchCenter.x*newScale - pinchCenterOffset.x;_x000D_
var zoomY = pinchCenter.y*newScale - pinchCenterOffset.y;_x000D_
var zoomCenter = { x: zoomX/newScale, y: zoomY/newScale };_x000D_
_x000D_
zoomAround(e.scale, zoomCenter.x, zoomCenter.y, true);_x000D_
});_x000D_
_x000D_
hammer.on('pinchend', function (e) {_x000D_
updateLastScale();_x000D_
updateLastPos();_x000D_
pinchCenter = null;_x000D_
});_x000D_
_x000D_
hammer.on('doubletap', function (e) {_x000D_
var c = rawCenter(e);_x000D_
zoomAround(2, c.x, c.y);_x000D_
});_x000D_
_x000D_
};_x000D_
_x000D_
</script>_x000D_
_x000D_
<button onclick="zoomIn()">Zoom In</button>_x000D_
<button onclick="zoomOut()">Zoom Out</button>_x000D_
_x000D_
<div class="pinch-zoom-container">_x000D_
<img id="pinch-zoom-image-id" class="pinch-zoom-image" onload="onLoad()"_x000D_
src="https://hammerjs.github.io/assets/img/pano-1.jpg">_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I find this issue in my centOS is caused by "Oracle Java is replace by gcj", after change default java to "Oracle Java", the issue is resolved.
alternatives --config java
There are 2 programs which provide 'java'.
Selection Command
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.5.0-gcj/bin/java
+ 2 /usr/java/jdk1.7.0_67/bin/java
If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.
There is a builtin mixin: transparentize($color, $amount);
background-color: transparentize(#F05353, .3);
The amount should be between 0 to 1;
Official Sass Documentation (Module: Sass::Script::Functions)
Taking the answer from @Petr Stastny a step further by adding a password variable. I'd prefer if it actually took it in like a regular password rather than as an argument, but it's working for what I needed.
#!/bin/bash
# mycollate.sh <database> <password> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
PW="$2"
CHARSET="$3"
COLL="$4"
[ -n "$DB" ] || exit 1
[ -n "$PW" ]
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_bin"
PW="--password=""$PW"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql -u root "$PW"
echo "USE $DB; SHOW TABLES;" | mysql -s "$PW" | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql "$PW" $DB
done
)
PW="pleaseEmptyMeNow"
Why cant you use the finally block?
Like
try {
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
EDIT after question amended:
You can do:
int? returnFromFunction2 = null;
try {
returnFromFunction2 = function2();
return returnFromFunction2.value;
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
if (returnFromFunction2.HasValue) { // do something with value }
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
Store it in multi valued column with a comma separator in an RDBMs table.
Try this simple solution to convert file to base64 string
String base64String = imageFileToByte(file);
public String imageFileToByte(File file){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.
Fortunately our friends from askUbuntu had something similar:
tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install
to close bootstrap modal you can pass 'hide' as option to modal method as follow
$('#modal').modal('hide');
Please take a look at working fiddle here
bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation
If non of the above method work, give a id to your close button and trigger click on close button.
This can happen if you are out of disk space on the volume.
See also boost::format:
#include <boost/format.hpp>
std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();
As others have said, std::max_element()
and std::min_element()
return iterators, which need to be dereferenced to obtain the value.
The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C++11 for brevity):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
This yields:
Max element is 5 at position 4
min element is 1 at position 0
Using std::minmax_element()
as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9
since...
If several elements are equivalent to the largest element, the iterator to the last such element is returned.
A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
I actually managed to work out what I was doing wrong (and it was my fault).
I'm used to using pre-jQuery Rails, so when I included the Bootstrap JS files I didn't think that including the version of jQuery bundled with them would cause any issues, however when I removed that one JS file everything started working perfectly.
Lesson learnt, triple check which JS files are loaded, see if there's any conflicts.
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'
In answer to the further question -
"is there anyway to apply this within the Visual Studio project? In a multi-developer environment, if someone else check's out the code on their machine, then their local IIS Express wouldn't be configured with the virtual directory and cause runtime errors wouldn't it?"
I never found a consistant answer to this anywhere but then figured out you could do it with a post build event using the XmlPoke task in the project file for the website -
<Target Name="AfterBuild">
<!-- Get the local directory root (and strip off the website name) -->
<PropertyGroup>
<LocalTarget>$(ProjectDir.Replace('MyWebSite\', ''))</LocalTarget>
</PropertyGroup>
<!-- Now change the virtual directories as you need to -->
<XmlPoke XmlInputPath="..\..\Source\Assemblies\MyWebSite\.vs\MyWebSite\config\applicationhost.config"
Value="$(LocalTarget)AnotherVirtual"
Query="/configuration/system.applicationHost/sites/site[@name='MyWebSite']/application[@path='/']/virtualDirectory[@path='/AnotherVirtual']/@physicalPath"/>
</Target>
You can use this technique to repoint anything in the file before IISExpress starts up. This would allow you to initially force an applicationHost.config file into GIT (assuming it is ignored by gitignore) then subsequently repoint all the paths at build time. GIT will ignore any changes to the file so it's now easy to share them around.
In answer to the futher question about adding other applications under one site:
You can create the site in your application hosts file just like the one on your server. For example:
<site name="MyWebSite" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\MyWebSite\Main" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<application path="/AppSubSite" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\GIT\AppSubSite\" />
<virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
<virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:4076:localhost" />
</bindings>
</site>
Then use the above technique to change the folder locations at build time.
This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.
I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:
void find_squares(Mat& image, vector<vector<Point> >& squares)
{
// blur will enhance edge detection
Mat blurred(image);
medianBlur(image, blurred, 9);
Mat gray0(blurred.size(), CV_8U), gray;
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; c++)
{
int ch[] = {c, 0};
mixChannels(&blurred, 1, &gray0, 1, ch, 1);
// try several threshold levels
const int threshold_level = 2;
for (int l = 0; l < threshold_level; l++)
{
// Use Canny instead of zero threshold level!
// Canny helps to catch squares with gradient shading
if (l == 0)
{
Canny(gray0, gray, 10, 20, 3); //
// Dilate helps to remove potential holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
{
gray = gray0 >= (l+1) * 255 / threshold_level;
}
// Find contours and store them in a list
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
// Test contours
vector<Point> approx;
for (size_t i = 0; i < contours.size(); i++)
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
}
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
}
After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >
:
I'm letting you write the function to find the largest square. ;)
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows
The whole idea is doing some simple check into the SELECT and sorting with the result.
For what it's worth, to be a single-line solution, the below is a working solution for me.
$currFolderName = (Get-Location).Path.Substring((Get-Location).Path.LastIndexOf("\")+1)
The 1 at the end is to ignore the /
.
Thanks to the posts above using the Get-Location cmdlet.
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
I'd suggest using grep -i version
to make sure you get the right line containing the version string. If you have the environment variable JAVA_OPTIONS set, openjdk will print the java options before printing the version information. This version returns 1.6, 1.7 etc.
java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2
For is()
import static org.hamcrest.CoreMatchers.*;
For assertThat()
import static org.junit.Assert.*;
For when() and verify()
import static org.mockito.Mockito.*;
At first I would use http://ruby.railstutorial.org/.
And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.
Write one table per join, like this:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
Note that while my query contains actual left join, your query apparently doesn't.
Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).
The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.
In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.
So look what happens when you move conditions to the where clause:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx
left join table4 tab4 on tab4.xya = tab3.xya
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
tab3.desc = "XYZ" and
tab4.ss = tab3.ss
Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss
is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.
PS: left join
and left outer join
are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join
to make not the left, but the right table the leading table. And there is and even full [outer] join
to return a row if there is data in either table.
There's a style tag, so you could do something like this:
<style type="text/css">
.title
{
color: blue;
text-decoration: bold;
text-size: 1em;
}
</style>
If you are using visual studio dataset designer to get the data table, and it is throwing an error 'Failed to Enable constraints'. I've faced the same problem, try to preview the data from the dataset designer itself and match it with table inside your database.
The best way to solve this issue is to delete the table adapter and create a new one instead.
The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}
Demo:
input {_x000D_
font: small-caption;_x000D_
font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
It's a time zone change on December 31st in Shanghai.
See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possible instant for that local date/time - hence the difference.
Just another episode in the often weird and wonderful world of time zones.
EDIT: Stop press! History changes...
The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of TZDB. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.
I only noticed this because I'm collecting questions like this in Noda Time, in the form of unit tests... The test has now been changed, but it just goes to show - not even historical data is safe.
EDIT: History has changed again...
In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between t
and t+1
is 344 seconds, if you see what I mean).
EDIT: To answer a question around a transition at 1900... it looks like the Java timezone implementation treats all time zones as simply being in their standard time for any instant before the start of 1900 UTC:
import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws Exception {
long startOf1900Utc = -2208988800000L;
for (String id : TimeZone.getAvailableIDs()) {
TimeZone zone = TimeZone.getTimeZone(id);
if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
System.out.println(id);
}
}
}
}
The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a "fixed" standard time (which is what getRawOffset
assumes to be a valid concept) so other libraries needn't introduce this artificial transition.
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.
You can use CSS3 RGBA in this way:
rgba(255, 0, 0, 0.7);
0.7
means 70% opacity.
DI is a subset of IoC
add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..
add new tomcat for each new workspace.
Enabling the legacy from app.config didn't work for me. For unknown reasons, my application wasn't activating V2 runtime policy. I found a work around here.
Enabling the legacy from app.config is a recommended approach but in some cases it doesn't work as expected. Use the following code with in your main application to force Legacy V2 policy:
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}
so as things have changed with GIT since alot of these answers were posted here is the correct instructions to get symlinks working correctly in windows as of
AUGUST 2018
1. Make sure git is installed with symlink support
2. Tell Bash to create hardlinks instead of symlinks
EDIT -- (git folder)/etc/bash.bashrc
ADD TO BOTTOM - MSYS=winsymlinks:nativestrict
3. Set git config to use symlinks
git config core.symlinks true
or
git clone -c core.symlinks=true <URL>
NOTE: I have tried adding this to the global git config and at the moment it is not working for me so I recommend adding this to each repo...
4. pull the repo
NOTE: Unless you have enabled developer mode in the latest version of Windows 10, you need to run bash as administrator to create symlinks
5. Reset all Symlinks (optional) If you have an existing repo, or are using submodules you may find that the symlinks are not being created correctly so to refresh all the symlinks in the repo you can run these commands.
find -type l -delete
git reset --hard
NOTE: this will reset any changes since last commit so make sure you have committed first
The good news is that if you need to make a case-sensitive query, it is very easy to do:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
Use <text>
:
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
<text>
data.push([ @r.UnixTime * 1000, @r.Value ]);
</text>
}
</script>
Default text size vary from device to devices
Type Dimension Micro 12 sp Small 14 sp Medium 18 sp Large 22 sp
First of all: Yes you can mix jQuery with common JS :)
Best way to build up an intervall call of a function is to use setTimeout methode:
For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:
function test(){
console.log('test called');
setTimeout(test, 5000);
}
Finally you have to trigger the function once:
$(document).ready(function(){
test();
});
This document ready function is called automatically, after all html is loaded.
The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";
print $bucket;
yields:
$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']
I too had OpenJDK on my Ubuntu machine:
$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)
Replacing OpenJDK with the HotSpot VM works fine:
sudo apt-get autoremove openjdk-7-jre-headless
For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java
In general, you either have to specify $(OBJDIR)
on the left hand side of all the rules that place files in $(OBJDIR)
, or you can run make from $(OBJDIR)
.
VPATH
is for sources, not for objects.
Take a look at these two links for more explanation, and a "clever" workaround.
If one want to match 0-9
tesseract myimage.png stdout -c tessedit_char_whitelist=0123456789
Or if one almost wants to match 0-9, but with one or more different characters
tesseract myimage.png stdout -c tessedit_char_whitelist=01234ABCDE
It should be
document.getElementById("hidden").style.display = "block";
not
document.getElementById["hidden"].style.display = "block";
EDIT due to author edit:
Why are you using a <div>
here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">
Use xlsread, it works just as well on .csv files as it does on .xls files. Specify that you want three outputs:
[num char raw] = xlsread('your_filename.csv')
and it will give you an array containing only the numeric data (num), an array containing only the character data (char) and an array that contains all data types in the same format as the .csv layout (raw).
Go to this JVM online test and run it.
Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.
Case 1 should have worked. I don't see anything wrong. There may be some other problems. I would suggest a clean build.
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
If you want to skip every other row and every other column, then you can do it with basic slicing:
In [49]: x=np.arange(16).reshape((4,4))
In [50]: x[1:4:2,1:4:2]
Out[50]:
array([[ 5, 7],
[13, 15]])
This returns a view, not a copy of your array.
In [51]: y=x[1:4:2,1:4:2]
In [52]: y[0,0]=100
In [53]: x # <---- Notice x[1,1] has changed
Out[53]:
array([[ 0, 1, 2, 3],
[ 4, 100, 6, 7],
[ 8, 9, 10, 11],
[ 12, 13, 14, 15]])
while z=x[(1,3),:][:,(1,3)]
uses advanced indexing and thus returns a copy:
In [58]: x=np.arange(16).reshape((4,4))
In [59]: z=x[(1,3),:][:,(1,3)]
In [60]: z
Out[60]:
array([[ 5, 7],
[13, 15]])
In [61]: z[0,0]=0
Note that x
is unchanged:
In [62]: x
Out[62]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
If you wish to select arbitrary rows and columns, then you can't use basic slicing. You'll have to use advanced indexing, using something like x[rows,:][:,columns]
, where rows
and columns
are sequences. This of course is going to give you a copy, not a view, of your original array. This is as one should expect, since a numpy array uses contiguous memory (with constant strides), and there would be no way to generate a view with arbitrary rows and columns (since that would require non-constant strides).
Make's substitutions feature is nice and helped me to write
%.i: src/%.c $(INCLUDE)
gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@
You might find this useful, because it asks make
to check for changes in include folders too
I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,
String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);
fo.write(asset.getBytes());
fo.close();
parts.add("file", new FileSystemResource(tempFileName));
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);
//clean-up
File f = new File(tempFileName);
f.delete();
I am still looking for a more elegant solution to this problem.
In Visual Studio 2015 (this still holds in 2019 for the same value), check the setting:
Tools > Options > Environment > Documents > Check for consistent line endings on load
VS2015 will now prompt you to convert line endings when you open a file where they are inconsistent, so all you need to do is open the files, select the desired option from the prompt and save them again.
This works fine for me using MySQL 5.1.35:
DELIMITER $$
DROP PROCEDURE IF EXISTS `example`.`test` $$
CREATE PROCEDURE `example`.`test` ()
BEGIN
DECLARE FOO varchar(7);
DECLARE oldFOO varchar(7);
SET FOO = '138';
SET oldFOO = CONCAT('0', FOO);
update mypermits
set person = FOO
where person = oldFOO;
END $$
DELIMITER ;
Table:
DROP TABLE IF EXISTS `example`.`mypermits`;
CREATE TABLE `example`.`mypermits` (
`person` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO mypermits VALUES ('0138');
CALL test()
I found a "neat" reflection tweak on "the interwebs" that I like to share. (origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)
It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.
I tested succesfully:
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
private static void makeJSONObjLinear(JSONObject jsonObject) {
try {
Field changeMap = jsonObject.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonObject, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);
requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)
Here is the best: Multipart/mixed mime message with attachments and inline images
And image: https://www.qcode.co.uk/images/mime-nesting-structure.png
From: [email protected]
To: to@@qcode.co.uk
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"
--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"
--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"
--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
This is the plain text part of the email.
--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable
<html>
<body>=0D
<img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
=5C>=0D
<p>This is the html part of the email.</p>=0D
<img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
>=0D
</body>=0D
</html>=0D
--AlternativeBoundaryString--
--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <[email protected]>
amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
...
...
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=
--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <[email protected]>
aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
...
...
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=
--RelatedBoundaryString--
--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"
aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
...
...
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
dWg4NTA0
--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"
aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
...
...
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=
--MixedBoundaryString--
.
Schema multipart/related/alternative
Header
|From: email
|To: email
|MIME-Version: 1.0
|Content-Type: multipart/mixed; boundary="boundary1";
Message body
|multipart/mixed --boundary1
|--boundary1
| multipart/related --boundary2
| |--boundary2
| | multipart/alternative --boundary3
| | |--boundary3
| | |text/plain
| | |--boundary3
| | |text/html
| | |--boundary3--
| |--boundary2
| |Inline image
| |--boundary2
| |Inline image
| |--boundary2--
|--boundary1
|Attachment1
|--boundary1
|Attachment2
|--boundary1
|Attachment3
|--boundary1--
|
.
extern "C"
doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).
What extern "C"
does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.
Code inside an extern "C"
is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.
extern "C"
blocks nest nicely. There's also extern "C++"
if you find yourself hopelessly trapped inside of extern "C"
regions, but it isn't such a good idea from a cleanliness perspective.
Now, specifically regarding your numbered questions:
Regarding #1: __cplusplus will stay defined inside of extern "C"
blocks. This doesn't matter, though, since the blocks should nest neatly.
Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C"
when being interpreted as C++, and they should not have extern "C"
when being interpreted as C -- hence the #ifdef __cplusplus
checking.
To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C"
block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.
For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C"
the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic
when you were looking for void h(int, char)
5: This sort of mixing is a common reason to use extern "C"
, and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.
I assume you calculated the "depth of 1024" by the recurring lines in the stack trace?
Obviously, the stack trace array length in Throwable seems to be limited to 1024. Try the following program:
public class Test {
public static void main(String[] args) {
try {
System.out.println(fact(1 << 15));
}
catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was " +
e.getStackTrace().length);
}
}
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
}
You can use the this customization to change the default mapping to java.util.Date
<xsd:annotation>
<xsd:appinfo>
<jaxb:globalBindings>
<jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
</jaxb:globalBindings>
</xsd:appinfo>
Or no JavaScript load function at all...
<html>
<head></head>
<body>
<canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
var draw = function() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
draw();
//or self executing...
(function(){
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (50, 50, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (70, 70, 55, 50);
}
})();
</script>
</html>
If you're in Python 3, there's a fork of JPype called JPype1-py3
pip install JPype1-py3
This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version
)
from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()
You don't have to force yourself to remember differences between them. Think of how you actually made a commit.
Make some changes.
git add .
git commit -m "I did Something"
Soft, Mixed and Hard is the way enabling you to give up the operations you did from 3 to 1.
git commit
.git add .
@mixin box-shadow($left: 0, $top: 0, $blur: 6px, $color: hsla(0,0%,0%,0.25), $inset: false) {
@if $inset {
-webkit-box-shadow: inset $left $top $blur $color;
-moz-box-shadow: inset $left $top $blur $color;
box-shadow: inset $left $top $blur $color;
} @else {
-webkit-box-shadow: $left $top $blur $color;
-moz-box-shadow: $left $top $blur $color;
box-shadow: $left $top $blur $color;
}
}
You can use pandas library and reference the rows and columns like this:
import pandas as pd
input = pd.read_csv("path_to_file");
#for accessing ith row:
input.iloc[i]
#for accessing column named X
input.X
#for accessing ith row and column named X
input.iloc[i].X
How can I make as "perfect" a subclass of dict as possible?
The end goal is to have a simple dict in which the keys are lowercase.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?Am I preventing pickling from working, and do I need to implement
__setstate__
etc?Do I need repr, update and
__init__
?Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
The accepted answer would be my first approach, but since it has some issues,
and since no one has addressed the alternative, actually subclassing a dict
, I'm going to do that here.
This seems like a rather simple request to me:
How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.
The accepted answer doesn't actually subclass dict
, and a test for this fails:
>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False
Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict
- and we can't "fix" those functions, this code will fail.
Other quibbles one might make:
fromkeys
. The accepted answer also has a redundant __dict__
- therefore taking up more space in memory:
>>> s.foo = 'bar'
>>> s.__dict__
{'foo': 'bar', 'store': {'test': 'test'}}
dict
We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?
Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping
(see the accepted answer), but it's really not that much more work.
First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError
) to make sure we know if we actually get an argument to dict.pop
, and create a function to ensure our string keys are lowercase:
from itertools import chain
try: # Python 2
str_base = basestring
items = 'iteritems'
except NameError: # Python 3
str_base = str, bytes, bytearray
items = 'items'
_RaiseKeyError = object() # singleton for no-default behavior
def ensure_lower(maybe_str):
"""dict keys can be any hashable object - only call lower if str"""
return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str
Now we implement - I'm using super
with the full arguments so that this code works for Python 2 and 3:
class LowerDict(dict): # dicts take a mapping or iterable as their optional first argument
__slots__ = () # no __dict__ - that would be redundant
@staticmethod # because this doesn't make sense as a global function.
def _process_args(mapping=(), **kwargs):
if hasattr(mapping, items):
mapping = getattr(mapping, items)()
return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
def __init__(self, mapping=(), **kwargs):
super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
def __getitem__(self, k):
return super(LowerDict, self).__getitem__(ensure_lower(k))
def __setitem__(self, k, v):
return super(LowerDict, self).__setitem__(ensure_lower(k), v)
def __delitem__(self, k):
return super(LowerDict, self).__delitem__(ensure_lower(k))
def get(self, k, default=None):
return super(LowerDict, self).get(ensure_lower(k), default)
def setdefault(self, k, default=None):
return super(LowerDict, self).setdefault(ensure_lower(k), default)
def pop(self, k, v=_RaiseKeyError):
if v is _RaiseKeyError:
return super(LowerDict, self).pop(ensure_lower(k))
return super(LowerDict, self).pop(ensure_lower(k), v)
def update(self, mapping=(), **kwargs):
super(LowerDict, self).update(self._process_args(mapping, **kwargs))
def __contains__(self, k):
return super(LowerDict, self).__contains__(ensure_lower(k))
def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
return type(self)(self)
@classmethod
def fromkeys(cls, keys, v=None):
return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())
We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len
, clear
, items
, keys
, popitem
, and values
for free. While this required some careful thought to get right, it is trivial to see that this works.
(Note that haskey
was deprecated in Python 2, removed in Python 3.)
Here's some usage:
>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)
Am I preventing pickling from working, and do I need to implement
__setstate__
etc?
And the dict subclass pickles just fine:
>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>
__repr__
Do I need repr, update and
__init__
?
We defined update
and __init__
, but you have a beautiful __repr__
by default:
>>> ld # without __repr__ defined for the class, we get this
{'foo': None}
However, it's good to write a __repr__
to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj
. If it's easy to do for your code, I strongly recommend it:
>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True
You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:
>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})
Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.
Premature optimization is going for greater complexity in search of performance.
MutableMapping
is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.
I should add that there was a push to put a similar dictionary into the collections
module, but it was rejected. You should probably just do this instead:
my_dict[transform(key)]
It should be far more easily debugable.
There are 6 interface functions implemented with the MutableMapping
(which is missing fromkeys
) and 11 with the dict
subclass. I don't need to implement __iter__
or __len__
, but instead I have to implement get
, setdefault
, pop
, update
, copy
, __contains__
, and fromkeys
- but these are fairly trivial, since I can use inheritance for most of those implementations.
The MutableMapping
implements some things in Python that dict
implements in C - so I would expect a dict
subclass to be more performant in some cases.
We get a free __eq__
in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict
subclass will compare more quickly.
MutableMapping
is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
dict
is faster, uses less memory, and passes isinstance(x, dict)
, but it has greater complexity to implement.Which is more perfect? That depends on your definition of perfect.
In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date
. It is basically backed by the Epoch time in flavor of a long
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.
In SQL side, there are several standard date and time types, DATE
, TIME
and TIMESTAMP
(at some DB's also called DATETIME
), which are represented in JDBC as java.sql.Date
, java.sql.Time
and java.sql.Timestamp
, all subclasses of java.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.
In contrary to java.util.Date
, the java.sql.Date
contains only information about the date part (year, month, day). The Time
contains only information about the time part (hours, minutes, seconds) and the Timestamp
contains information about the both parts, like as java.util.Date
does.
The normal practice to store a timestamp in the DB (thus, java.util.Date
in Java side and java.sql.Timestamp
in JDBC side) is to use PreparedStatement#setTimestamp()
.
java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp()
.
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "
core.eol
" config variable' commit that's currently inpu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact thatautocrlf
is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.Introduce a new configuration variable, "
core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf
" overridescore.eol
.
This means that:[core] autocrlf = true
puts CRLFs in the working directory even if
core.eol
is set to "lf
".core.eol:
Sets the line ending type to use in the working directory for files that have the
text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value isnative
.
Other evolutions are being considered:
For 1.8, I would consider making
core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactorcrlf_action
Refactor the determination and usage of
crlf_action
.
Today, when no "crlf
" attribute are set on a file,crlf_action
is set toCRLF_GUESS
. UseCRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.Replace the old
CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from
eol=
orautocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., duringgit add
rather than atgit commit
time.
(Note thatgit commit -a
or--only
or--include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
Those are two different things, as others have mentioned.
When you specify # -*- coding: utf-8 -*-
, you're telling Python the source file you've saved is utf-8
. The default for Python 2 is ASCII (for Python 3 it's utf-8
). This just affects how the interpreter reads the characters in the file.
In general, it's probably not the best idea to embed high unicode characters into your file no matter what the encoding is; you can use string unicode escapes, which work in either encoding.
When you declare a string with a u
in front, like u'This is a string'
, it tells the Python compiler that the string is Unicode, not bytes. This is handled mostly transparently by the interpreter; the most obvious difference is that you can now embed unicode characters in the string (that is, u'\u2665'
is now legal). You can use from __future__ import unicode_literals
to make it the default.
This only applies to Python 2; in Python 3 the default is Unicode, and you need to specify a b
in front (like b'These are bytes'
, to declare a sequence of bytes).
Below conf works for me:
JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME
JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"
/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"
Sometimes it can be dangerous to convert charsets, specially on databases with huge amounts of data. I think the best option is to use the "binary" operator:
e.g : WHERE binary table1.column1 = binary table2.column1
This works for me. If I haven't misconstrued your question, you might give it a try.
div#centerDiv {_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
border: 1px solid red;_x000D_
}_x000D_
ul.centerUL {_x000D_
margin: 2px auto;_x000D_
line-height: 1.4;_x000D_
padding-left: 0;_x000D_
}_x000D_
.centerUL li {_x000D_
display: inline;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="centerDiv">_x000D_
<ul class="centerUL">_x000D_
<li><a href="http://www.amazon.com">Amazon 1</a> </li>_x000D_
<li><a href="http://www.amazon.com">Amazon 2</a> </li>_x000D_
<li><a href="http://www.amazon.com">Amazon 3</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
I had to specify different generateDirectory
(without this, the plugin was considering that files were up to date and wasn't generating anything during the second execution). And I recommend to follow the target/generated-sources/<tool>
convention for generated sources so that they will be imported in your favorite IDE automatically. I also recommend to declare several execution
instead of declaring the plugin twice (and to move the configuration
inside each execution
element):
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.7.1</version>
<executions>
<execution>
<id>schema1-generate</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<schemaDirectory>src/main/resources/dir1</schemaDirectory>
<schemaIncludes>
<include>shiporder.xsd</include>
</schemaIncludes>
<generatePackage>com.stackoverflow.package1</generatePackage>
<generateDirectory>${project.build.directory}/generated-sources/xjc1</generateDirectory>
</configuration>
</execution>
<execution>
<id>schema2-generate</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<schemaDirectory>src/main/resources/dir2</schemaDirectory>
<schemaIncludes>
<include>books.xsd</include>
</schemaIncludes>
<generatePackage>com.stackoverflow.package2</generatePackage>
<generateDirectory>${project.build.directory}/generated-sources/xjc2</generateDirectory>
</configuration>
</execution>
</executions>
</plugin>
With this setup, I get the following result after a mvn clean compile
$ tree target/ target/ +-- classes ¦ +-- com ¦ ¦ +-- stackoverflow ¦ ¦ +-- App.class ¦ ¦ +-- package1 ¦ ¦ ¦ +-- ObjectFactory.class ¦ ¦ ¦ +-- Shiporder.class ¦ ¦ ¦ +-- Shiporder$Item.class ¦ ¦ ¦ +-- Shiporder$Shipto.class ¦ ¦ +-- package2 ¦ ¦ +-- BookForm.class ¦ ¦ +-- BooksForm.class ¦ ¦ +-- ObjectFactory.class ¦ ¦ +-- package-info.class ¦ +-- dir1 ¦ ¦ +-- shiporder.xsd ¦ +-- dir2 ¦ +-- books.xsd +-- generated-sources +-- xjc ¦ +-- META-INF ¦ +-- sun-jaxb.episode +-- xjc1 ¦ +-- com ¦ +-- stackoverflow ¦ +-- package1 ¦ +-- ObjectFactory.java ¦ +-- Shiporder.java +-- xjc2 +-- com +-- stackoverflow +-- package2 +-- BookForm.java +-- BooksForm.java +-- ObjectFactory.java +-- package-info.java
Which seems to be the expected result.
update_attribute
This method update single attribute of object without invoking model based validation.
obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”
update_attributes
This method update multiple attribute of single object and also pass model based validation.
attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)
Hope this answer will clear out when to use what method of active record.
I met this problem today, however it was a bit different. I had a CUDA DLL project in my solution. Compiling in a clean solution was OK, but otherwise it failed and the compiler always treated the CUDA DLL project as not up to date.
I tried the solution from this post.
But there is no missing header file in my solution. Then I found out the reason in my case.
I have changed the project's Intermediate Directory before, although it didn't cause trouble. And now when I changed the CUDA DLL Project's Intermediate Directory back to $(Configuration)\, everything works right again.
I guess there is some minor problem between CUDA Build Customization and non-default Intermediate Directory.
By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush
:
while((c=getchar())!= EOF)
{
putchar(c);
fflush(stdout);
}
I found that piping the array to the Out-String
cmdlet works well too.
For example:
PS C:\> $a | out-string
This
Is
a
cat
It depends on your end goal as to which method is the best to use.
I had a similar proxy related problem. In my case it was enough to add:
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
protected void UpdateButton_Click(object sender, EventArgs e)
{
var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
var bytes = Encoding.ASCII.GetBytes(values);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
UpdateResponseLabel.Text = "Update completed";
else
UpdateResponseLabel.Text = "Error in update";
}
It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So
someCommand | tee someFile
gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use
someCommand 2>&1 | tee someFile
(source: In the shell, what is " 2>&1 "? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:
someCommand 2>&1 | tee -a someFile
for Xcode 8:
What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.
Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.
I once saved over 50GB doing this since I did so much testing on older iOS versions.
I would like to add yourkit java and .net profiler, I love it for Java, haven't tried .NET version though.
With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++);
is actually well defined and does what you're asking for, e.g.:
#include <stdio.h>
int main() {
int a = 100;
int *p = &a;
printf("%p\n",(void*)p);
++(*p++);
printf("%p\n",(void*)p);
printf("%d\n",a);
return 0;
}
It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.
The case-insensitive marker, (?i)
can be incorporated directly into the regex pattern:
>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']
You should be able to use reduce
.
var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
And with arrow functions introduced in ES6, it's even simpler:
sum = array.reduce((pv, cv) => pv + cv, 0);
Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:
//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());
while (li.hasPrevious()) {
String curr = li.previous()
}
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like +
, -
, *
and /
to special functions, such that e.g. a + b
is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only /
which maps to __div__
and the result is dependent on the input types (e.g. int
, float
).
Python 2.2 introduced the __future__
feature division
, which changed the division semantics the following way (TL;DR of PEP 238):
/
maps to __truediv__
which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)//
maps to __floordiv__
, which should return the floored result of /
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__
in Python's object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of /
and //
.
git rm --cached file
should do what you want.
You can read more details at git help rm
You could also use viewport percentages if you don't care about old school IE.
height: 100vh;
This is hard to answer without more detail about the network architecture. Some things to investigate are:
When I upgraded Visual Studio to version 15.5.1, .Net Core SDK was upgraded to 2.X, so this error went away. When I run dotnet --info
, I see the following now:
Including this worked for me.
Please include the line mentioned below in the section.
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js'>
For Swift 4:
import UIKit
extension UIImageView {
func makeRounded() {
let radius = self.frame.width/2.0
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
If you're a homebrew user instead of macports, homebrew has an ant recipe.
brew install ant
You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.
.ui-corner-all
{
border-radius: 0px !important;
}
To add to some of the other answers, note that:
keyup
and keydown
differ from keypress
String.fromCharCode()
to get the actual digit from keyup
, you'll need to first normalize the keyCode
.Below is a self-documenting example that determines if the key is numeric, along with which number it is (example uses the range
function from lodash
).
const isKeypad = range(96, 106).includes(keyCode);
const normalizedKeyCode = isKeypad ? keyCode - 48 : keyCode;
const isDigit = range(48, 58).includes(normalizedKeyCode);
const digit = String.fromCharCode(normalizedKeyCode);
You can use the createRef to change the state of the child component from the parent component. Here are all the steps.
Create a method to change the state in the child component.
2 - Create a reference for the child component in parent component using React.createRef().
3 - Attach reference with the child component using ref={}.
4 - Call the child component method using this.yor-reference.current.method.
Parent component
class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
render() {
return (
<div>
<button onClick={this.changeChild.current.toggleMenu()}>
Toggle Menu from Parent
</button>
<ChildComponent ref={this.changeChild} />
</div>
);
}
}
Child Component
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}
toggleMenu=() => {
this.setState({
open: !this.state.open
});
}
render() {
return (
<Drawer open={this.state.open}/>
);
}
}
By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.
To stop this from occurring you can set the h1 to have inline flow behaviour:
#header > h1 { display: inline; }
As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:
#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }
If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.
UPDATE:
Here is a complete example that works on Firefox 3:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Example of vertical positioning inside a div</title>
<style type="text/css">
#header > h1 { display: inline; }
#header { border: solid 1px red;
position: relative; }
#img-for-abs-positioning { position: absolute;
bottom: -1em; right: 2em; }
</style>
</head>
<body>
<div id="header">
<img src="#" alt="Image 1" width="40" height="40" />
<h1>Header</h1>
<img src="#" alt="Image 2" width="40" height="40"
id="img-for-abs-positioning" />
</div>
</body>
</html>
Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0
each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)
Private Function FileExists(fullFileName As String) As Boolean
FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
the main method should be declared in the your class like this :
public class derivativeQuiz_source{
// bunch of methods .....
public static void main(String args[])
{
// code
}
}
I get enum values in this way:
SELECT COLUMN_TYPE
FROM information_schema.`COLUMNS`
WHERE TABLE_NAME = 'tableName'
AND COLUMN_NAME = 'columnName';
Running this sql I have get : enum('BDBL','AB Bank')
then I have filtered just value using following code :
preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
$enum = explode("','", $matches[1]);
var_dump($enum) ;
Out put :
array(2) { [0]=> string(4) "BDBL" [1]=> string(7) "AB Bank" }
For me, as I was using pretty standard React fetch calls, this could have been fixed using some of the AWS Console and Lambda fixes above, but my Lambda returned the right headers (I was also using Proxy mode) and I needed to package my application up into a SAM Template, so I could not spend my time clicking around the console.
I noticed that all of the CORS stuff worked fine UNTIL I put Cognito Auth onto my application. I just basically went very slow doing a SAM package / SAM deploy with more and more configurations until it broke and it broke as soon as I added Auth to my API Gateway. I spent a whole day clicking around wonderful discussions like this one, looking for an easy fix, but then ended up having to actually read about what CORS was doing. I'll save you the reading and give you another easy fix (at least for me).
Here is an example of an API Gateway template that finally worked (YAML):
Resources:
MySearchApi:
Type: AWS::Serverless::Api
Properties:
StageName: 'Dev'
Cors:
AllowMethods: "'OPTIONS, GET'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
AllowOrigin: "'*'"
Auth:
DefaultAuthorizer: MyCognitoSearchAuth
Authorizers:
MyCognitoSearchAuth:
UserPoolArn: "<my hardcoded user pool ARN>"
AuthType: "COGNITO_USER_POOLS"
AddDefaultAuthorizerToCorsPreflight: False
Note the AddDefaultAuthorizerToCorsPreflight at the bottom. This defaults to True if you DON'T have it in your template, as as far as I can tell from my reading. And, when True, it sort of blocks the normal OPTIONS behavior to announce what the Resource supports in terms of Allowed Origins. Once I explicitly added it and set it to False, all of my issues were resolved.
The implication is that if you are having this issue and want to diagnose it more completely, you should visit your Resources in API Gateway and check to see if your OPTIONS method contains some form of Authentication. Your GET or POST needs Auth, but if your OPTIONS has Auth enabled on it, then you might find yourself in this situation. If you are clicking around the AWS console, then try removing from OPTIONS, re-deploy, then test. If you are using SAM CLI, then try my fix above.
Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:
L1 = [1,2,2,3]
L2 = [1,2,3,3]
You are likely better off sorting the two lists and comparing them:
def checkEqual(L1, L2):
if sorted(L1) == sorted(L2):
print "the two lists are the same"
return True
else:
print "the two lists are not the same"
return False
Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists
You can create a temp table matching your proc output and insert into it.
CREATE TABLE #Temp (
Col1 INT
)
INSERT INTO #Temp
EXEC MyProc
Please note, I wrote this answer based on Python 3.x
. No worries you can assign print()
statement to the variable like this.
>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>
According to the documentation,
All non-keyword arguments are converted to strings like
str()
does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also beNone
, which means to use the default values. If no objects are given, print() will just write end.The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.
That's why we cannot assign print()
statement values to the variable. In this question you have ask (or any function)
. So print()
also a function with the return value with None
. So the return value of python function is None
. But you can call the function(with parenthesis ()) and save the return value in this way.
>>> var = some_function()
So the var
variable has the return value of some_function()
or the default value None
. According to the documentation about print()
, All non-keyword arguments are converted to strings like str() does and written to the stream
. Lets look what happen inside the str()
.
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of
str()
depends on whether encoding or errors is given, as follows.
So we get a string object, then you can modify the below code line as follows,
>>> var = str(some_function())
or you can use str.join()
if you really have a string
object.
Return a string which is the concatenation of the strings in iterable. A
TypeError
will be raised if there are any non-string values in iterable, includingbytes
objects. The separator between elements is the string providing this method.
change can be as follows,
>>> var = ''.join(some_function()) # you can use this if some_function() really returns a string value
For larger data sets where sorting may not be desirable, you can also use the following perl script:
./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'
This basically just remembers every line output so that it doesn't output it again.
It has the advantage over the "sort | uniq
" solution in that there's no sorting required up front.
What about?
/.*\S.*/
This means
/
= delimiter
.*
= zero or more of anything but newline
\S
= anything except a whitespace (newline, tab, space)
so you get
match anything but newline + something not whitespace + anything but newline
Assume that you need to launch ps script from shared folder
copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1
P.S. Reduce googling)
I know this is old, but I was just working on a project that required me to filter HTML and this worked fine:
noHTMLString.replaceAll("\\&.*?\\;", "");
instead of this:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
PECL XHPROF looks interensting too. It has clickable HTML interface for viewing reports and pretty straightforward documentation. I have yet to test it though.
are you just trying to install it, or are you looking to build from source?
If you just need to install, the easiest way is to use the MSI installers provided here:
http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)
make sure you get the correct version (matches Python version, 32bit/64bit, etc)
The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?
1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)
2) Unzip the ZIP file (eg c:\oracle\instantclient).
3) Include the above path in the PATH.
4) Create the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]
5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]
6) Now create at least three string values ??in the above key:
NLS_LANG = BRAZILIAN PORTUGUESE_BRAZIL.WE8MSWIN1252
(complete list here: http://docs.oracle.com/cd/B19306_01/install.102/b14317/gblsupp.htm)ORACLE_HOME = c:\oracle\instantclient
(the same folder in PATH)ORACLE_HOME_NAME = MY_INSTANTCLIENT
(choose any name)For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":
The registry keys are now displayed for selecting the oracle client:
I had a similar issue when deploying from OSx on my local to my Linux live site.
It ran fine on OSx, but on Linux I was getting:
An Error Was Encountered
Unable to load the requested class: Ckeditor
The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".
I also changed my load call to match the capitalization:
$this->load->library('CKEditor');
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
With CSS properties, we can only control the thickness of border; not length.
However we can mimic border effect and control its width
and height
as we want with some other ways.
We can use linear-gradient()
to create a background image(s) and control its size and position with CSS so that it looks like a border. As we can apply multiple background images to an element, we can use this feature to create multiple border like images and apply on different sides of element. We can also cover the remaining available area with some solid color, gradient or background image.
Required HTML:
All we need is one element only (possibly having some class).
<div class="box"></div>
Steps:
linear-gradient()
.background-size
to adjust the width
/ height
of above created image(s) so that it looks like a border.background-position
to adjust position (like left
, right
, left bottom
etc.) of the above created border(s).Necessary CSS:
.box {
background-image: linear-gradient(purple, purple),
// Above css will create background image that looks like a border.
linear-gradient(steelblue, steelblue);
// This will create background image for the container.
background-repeat: no-repeat;
/* First sizing pair (4px 50%) will define the size of the border i.e border
will be of having 4px width and 50% height. */
/* 2nd pair will define the size of stretched background image. */
background-size: 4px 50%, calc(100% - 4px) 100%;
/* Similar to size, first pair will define the position of the border
and 2nd one for the container background */
background-position: left bottom, 4px 0;
}
Examples:
With linear-gradient()
we can create borders of solid color as well as having gradients. Below are some examples of border created with this method.
Example with border applied on one side only:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, calc(100% - 4px) 100%;_x000D_
background-position: left bottom, 4px 0;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Example with border applied on two sides:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, 4px 50%, calc(100% - 8px) 100%;_x000D_
background-position: left bottom, right top, 4px 0;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(purple, red),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Example with border applied on all sides:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, 50% 4px, 4px 50%, 50% 4px, calc(100% - 8px) calc(100% - 8px);_x000D_
background-position: left bottom, left bottom, right top, right top, 4px 4px;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(to right, purple, red),_x000D_
linear-gradient(to bottom, purple, red),_x000D_
linear-gradient(to left, purple, red),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Screenshot:
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
This is because:
You executed an SQL statement that tried to convert a string to a number, but it was unsuccessful.
As explained in:
To resolve this error:
Only numeric fields or character fields that contain numeric values can be used in arithmetic operations. Make sure that all expressions evaluate to numbers.
Here are few suggestions:
Check your network connections. For example by the following shell commands:
</dev/tcp/registry-1.docker.io/443 && echo Works || echo Problem
curl https://registry-1.docker.io/v2/ && echo Works || echo Problem
Check your proxy settings (e.g. in /etc/default/docker
).
If above won't help, this could be a temporary issue with the Docker services (as per Service Unavailable).
Related: GH-842 - 503 Service Unavailable at http://hub.docker.com.
I had this problem for past days, it just worked after that.
You can consider raising the issue at docker/hub-feedback
repo, check at, Docker Community Forums, or contact Docker Support directly.
even this will work:
<div class="container">
<div class="row">
<div class="col-4 col-sm-4 col-md-6 order-1">
1
</div>
<div class="col-4 col-sm-4 col-md-6 order-3">
2
</div>
<div class="col-4 col-sm-4 col-md-12 order-2">
3
</div>
</div>
</div>
Embedded option:
Wrap python code in a bash function.
#!/bin/bash
function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}
# Call it
current_datetime
# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT
Use environment variables, to pass data into to your embedded python script.
#!/bin/bash
function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}
# Do it one way
line 80
# Do it another way
echo $(line 80)
http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html
Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)
I'm going to throw my hat into the ring here:
I've used the __call hack with mixed degrees of success. The alternative I came up with was to use the Visitor pattern:
1: generate a stdClass or custom class (to enforce type)
2: prime that with the required method and arguments
3: ensure that your SUT has an acceptVisitor method which will execute the method with the arguments specified in the visiting class
4: inject it into the class you wish to test
5: SUT injects the result of operation into the visitor
6: apply your test conditions to the Visitor's result attribute
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string()
.
http://us3.php.net/mysql-real-escape-string
The reason your two queries are behaving differently is likely because you have magic_quotes_gpc
turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien"
).
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien"
. So, you will need to pass it through mysql_real_escape_string()
.
Removing ./
from source path should resolve your issue:
COPY test.json /home/test.json
COPY test.py /home/test.py
For 2019 ...
jQuery 3.4.0 is deprecating :first, :last, :eq, :even, :odd, :lt, :gt, and :nth. When we remove Sizzle, we’ll replace it with a small wrapper around querySelectorAll, and it would be almost impossible to reimplement these selectors without a larger selector engine.
We think this trade-off is worth it. Keep in mind we will still support the positional methods, such as .first, .last, and .eq. Anything you can do with positional selectors, you can do with positional methods instead. They perform better anyway.
https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/
So you should be now be using .first()
, .last()
instead (or no jQuery).
Another way is to use purrr package
# example data like what is said above
@A Handcart And Mohair
set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))
library(purrr)
means <- map_dbl(m, mean)
> means
# X1 X2 X3 X4
#47.0 64.4 44.8 67.8
You can set this in your manifest file..
android:name=".your launching activity name"
android:screenOrientation="portrait"
and you can also achive the same by writing the code in your class file like:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
You can use reset_index
to turn the index back into a column:
monthly_mean.reset_index().plot(x='index', y='A')
The following two cases relate to loading a properties file from an example class named TestLoadProperties
.
Case 1: Loading the properties file using ClassLoader
InputStream inputStream = TestLoadProperties.class.getClassLoader()
.getResourceAsStream("A.config");
properties.load(inputStream);
In this case the properties file must be in the root/src
directory for successful loading.
Case 2: Loading the properties file without using ClassLoader
InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);
In this case the properties file must be in the same directory as the TestLoadProperties.class
file for successful loading.
Note: TestLoadProperties.java
and TestLoadProperties.class
are two different files. The former, .java
file, is usually found in a project's src/
directory, while the latter, .class
file, is usually found in its bin/
directory.
According to the Java Language Specification (specifically §10.7 Array Members) it is a field:
- The
public
final
fieldlength
, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
Thanks a lot Codo.
I've just updated and completed what you have done to :
add, remove and update node (who knows)
Option Explicit
Private ScriptEngine As ScriptControl
Public Sub InitScriptEngine()
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
ScriptEngine.AddCode "function getType(jsonObj, propertyName) {return typeof(jsonObj[propertyName]);}"
ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
ScriptEngine.AddCode "function addKey(jsonObj, propertyName, value) { jsonObj[propertyName] = value; return jsonObj;}"
ScriptEngine.AddCode "function removeKey(jsonObj, propertyName) { var json = jsonObj; delete json[propertyName]; return json }"
End Sub
Public Function removeJSONProperty(ByVal JsonObject As Object, propertyName As String)
Set removeJSONProperty = ScriptEngine.Run("removeKey", JsonObject, propertyName)
End Function
Public Function updateJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set updateJSONPropertyValue = ScriptEngine.Run("removeKey", JsonObject, propertyName)
Set updateJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function addJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set addJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function DecodeJsonString(ByVal JsonString As String)
InitScriptEngine
Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function
Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function SerializeJSONObject(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
Dim tmpString As String
Dim tmpJSON As Object
Dim tmpJSONArray() As Variant
Dim tmpJSONObject() As Variant
Dim strJsonObject As String
Dim tmpNbElement As Long, i As Long
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
tmpString = ""
If ScriptEngine.Run("getType", JsonObject, Key) = "object" Then
'MsgBox "object " & SerializeJSONObject(GetObjectProperty(JsonObject, Key))(0)
Set tmpJSON = GetObjectProperty(JsonObject, Key)
strJsonObject = VBA.Replace(ScriptEngine.Run("getKeys", tmpJSON), " ", "")
tmpNbElement = Len(strJsonObject) - Len(VBA.Replace(strJsonObject, ",", ""))
If VBA.IsNumeric(Left(ScriptEngine.Run("getKeys", tmpJSON), 1)) = True Then
ReDim tmpJSONArray(tmpNbElement)
For i = 0 To tmpNbElement
tmpJSONArray(i) = GetProperty(tmpJSON, i)
Next
tmpString = "[" & Join(tmpJSONArray, ",") & "]"
Else
tmpString = "{" & Join(SerializeJSONObject(tmpJSON), ", ") & "}"
End If
Else
tmpString = GetProperty(JsonObject, Key)
End If
KeysArray(Index) = Key & ": " & tmpString
Index = Index + 1
Next
SerializeJSONObject = KeysArray
End Function
Public Function GetKeys(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
KeysArray(Index) = Key
Index = Index + 1
Next
GetKeys = KeysArray
End Function
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]
# 1. 'Actual' and 'Predicted' data
df <- data.frame(
y_actual = c(1:5),
y_predicted = c(0.8, 2.4, 2, 3, 4.8))
# 2. R2 Score components
# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)
# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)
# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total
This problem mainly happens when you are using connection pooling because when you close connection that connection go back to the connection pool and all cursor associated with that connection never get closed as the connection to database is still open. So one alternative is to decrease the idle connection time of connections in pool, so may whenever connection sits idle in connection for say 10 sec , connection to database will get closed and new connection created to put in pool.
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
Also you can do something like that:
document.addEventListener("DOMContentLoaded", function(event) {
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
})
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.
http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx
DECLARE @obj INT, @res INT, @match BIT;
DECLARE @pattern varchar(255) = '<your regex pattern goes here>';
DECLARE @matchstring varchar(8000) = '<string to search goes here>';
SET @match = 0;
-- Create a VB script component object
EXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;
-- Apply/set the pattern to the RegEx object
EXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;
-- Set any other settings/properties here
EXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;
-- Call the method 'Test' to find a match
EXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;
-- Don't forget to clean-up
EXEC @res = sp_OADestroy @obj;
If you get SQL Server blocked access to procedure 'sys.sp_OACreate'...
error, use sp_reconfigure
to enable Ole Automation Procedures
. (Yes, unfortunately that is a server level change!)
More information about the Test
method is available here
Happy coding
This is what worked for me with a Fedora 20 host. I ran a container using:
docker run -v /etc/localtime:/etc/localtime:ro -i -t mattdm/fedora /bin/bash
Initially /etc/localtime
was a soft link to /usr/share/zoneinfo/Asia/Kolkata
which Indian Standard Time. Executing date
inside the container showed me same time as that on the host. I exited from the shell and stopped the container using docker stop <container-id>
.
Next, I removed this file and made it link to /usr/share/zoneinfo/Singapore
for testing purpose. Host time was set to Singapore time zone. And then did docker start <container-id>
. Then accessed its shell again using nsenter
and found that time was now set to Singapore time zone.
docker start <container-id>
docker inspect -f {{.State.Pid}} <container-id>
nsenter -m -u -i -n -p -t <PID> /bin/bash
So the key here is to use -v /etc/localtime:/etc/localtime:ro
when you run the container first time. I found it on this link.
Hope it helps.
Use ISNULL(field, 0)
It can also be used with aggregates:
ISNULL(count(field), 0)
However, you might consider changing count(field) to count(*)
Edit:
try:
closedcases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is not null
group by assigned_to), 0),
opencases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is null
group by assigned_to), 0),
//$sql - sql statement
//$em - entity manager
$em->getConnection()->exec( $sql );
function validatePhone(inputtxt) {_x000D_
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
return phoneno.test(inputtxt)_x000D_
}
_x000D_
Try like this: server.bind(("0.0.0.0", 6677))
The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)
select *
from (
select PEAA.PresupuestoEtapaActividadId,
PEAH.PresupuestoEtapaActividadHistoricoId,
sum(PEAA.ValorTotalDesperdicioBase) as Base,
sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
from hgc.PresupuestoActividadAnalisis as PEAA
inner join hgc.PresupuestoEtapaActividad as PEA
on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId
group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId
) as t
where exists (
select 1
from (
select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId
from hgc.PresupuestoEtapaActividadHistorico as PEAH
group by PEAH.PresupuestoEtapaActividadId
) as ti
where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId
)
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
Select count(*) from table_name into @var1;
Select @var1;
Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.
It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)
Possible. You can get commercial sport also.
JavaFXPorts is the name of the open source project maintained by Gluon that develops the code necessary for Java and JavaFX to run well on mobile and embedded hardware. The goal of this project is to contribute as much back to the OpenJFX project wherever possible, and when not possible, to maintain the minimal number of changes necessary to enable the goals of JavaFXPorts. Gluon takes the JavaFXPorts source code and compiles it into binaries ready for deployment onto iOS, Android, and embedded hardware. The JavaFXPorts builds are freely available on this website for all developers.
Happened the same to me. It turns out that
var data = $("#myObject").data();
gives you a non-writable object. I solved it using:
var data = $.extend({}, $("#myObject").data());
And from then on, data
was a standard, writable JS object.
In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$");
for further information see the javadoc
Firefox and Chrome are different
Chrome ignores the TR's background-color
Example: http://jsfiddle.net/T4NK3R/9SE4p/
<tr style="background-color:#F00">
<td style="background-color:#FFF; border-radius:20px">
</tr>
In FF the TD gets red corners, in Chrome not
Hopefully, this will be of value to someone out there - I went through half a dozen stackoverflow posts trying to figure out relative imports similar to whats posted above here. I set up everything as suggested but I was still hitting ModuleNotFoundError: No module named 'my_module_name'
Since I was just developing locally and playing around, I hadn't created/run a setup.py
file. I also hadn't apparently set my PYTHONPATH
.
I realized that when I ran my code as I had been when the tests were in the same directory as the module, I couldn't find my module:
$ python3 test/my_module/module_test.py 2.4.0
Traceback (most recent call last):
File "test/my_module/module_test.py", line 6, in <module>
from my_module.module import *
ModuleNotFoundError: No module named 'my_module'
However, when I explicitly specified the path things started to work:
$ PYTHONPATH=. python3 test/my_module/module_test.py 2.4.0
...........
----------------------------------------------------------------------
Ran 11 tests in 0.001s
OK
So, in the event that anyone has tried a few suggestions, believes their code is structured correctly and still finds themselves in a similar situation as myself try either of the following if you don't export the current directory to your PYTHONPATH:
$ PYTHONPATH=. python3 test/my_module/module_test.py
PYTHONPATH=.
, create a setup.py
file with contents like the following and run python setup.py development
to add packages to the path:# setup.py from setuptools import setup, find_packages setup( name='sample', packages=find_packages() )
Read Eric Lippert 's answers to these questions
def quit(self):
self.root.destroy()
Add parentheses after destroy
to call the method.
When you use command=self.root.destroy
you pass the method to Tkinter.Button
without the parentheses because you want Tkinter.Button
to store the method for future calling, not to call it immediately when the button is created.
But when you define the quit
method, you need to call self.root.destroy()
in the body of the method because by then the method has been called.
For Numbers with leading zeroes and comma separated:
You can put 'A' to affect the entire column'.
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
Then you can write to the cell as you normally would.
This should work fine (using .text()
:
$("#toptitle").text("New word");
.clear() can be used to clear the text
(locator).clear();
using clear with the locator deletes all the value in that exact locator.
The Way I solved this problem is , Install TCPview go to TCP view and check what ports is Tomcat utilizing there will be few other ports other than 8005,8009,8080 now go to Servers tab in eclipse double click on Tomcatv9.0 server and change port numbers there. This will solve the problem.
When you mark your method as @Transactional
, occurrence of any exception inside your method will mark the surrounding TX as roll-back only (even if you catch them). You can use other attributes of @Transactional
annotation to prevent it of rolling back like:
@Transactional(rollbackFor=MyException.class, noRollbackFor=MyException2.class)
I would recommend using Wireshark, which has a "Follow TCP Stream" option that makes it very easy to see the full requests and responses for a particular TCP connection. If you would prefer to use the command line, you can try tcpflow, a tool dedicated to capturing and reconstructing the contents of TCP streams.
Other options would be using an HTTP debugging proxy, like Charles or Fiddler as EricLaw suggests. These have the advantage of having specific support for HTTP to make it easier to deal with various sorts of encodings, and other features like saving requests to replay them or editing requests.
You could also use a tool like Firebug (Firefox), Web Inspector (Safari, Chrome, and other WebKit-based browsers), or Opera Dragonfly, all of which provide some ability to view the request and response headers and bodies (though most of them don't allow you to see the exact byte stream, but instead how the browsers parsed the requests).
And finally, you can always construct requests by hand, using something like telnet, netcat, or socat to connect to port 80 and type the request in manually, or a tool like htty to help easily construct a request and inspect the response.
In c/c++ the source code(c program file) after the compilation using a compiler is directly converted to native machine code(which is understandable to particular machine on which u compiling the code). And hence the compiled code of c/c++ can not run on different OS.
But in case of Java : the source file of java(.java) will be compiled using JAVAC compiler(present in JDK) which provides the Byte code(.class file) which is understandable to any JVM installed on any OS(Physical System).
Here we need to have different JVM (which is platform dependent) for different operating Systems where we want to run the code, but the .class file(compiled code/Intermediate code)remains same, because it is understandable to any of the JVM installed on any OS.
In c/c++ : only source code is machine independent. In Java : both the source code and the compiled code is platform independent.
This makes Java Platform(machine) independent.
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
I thought I experienced issues with connecting my emulator to the internet but it turned out to be problems with the code I was using. I know its obvious but in the first instance try the browser on the emulator to confirm you have no internet access. I would have saved an hour if I had done that first.
Why do you need to state both
x
andy
before the:
?
Because it's a function definition and it needs to know what parameters the function accepts, and in what order. It can't just look at the expression and use the variables names in that, because some of those names you might want to use existing local or global variable values for, and even if it did that, it wouldn't know what order it should expect to get them.
Your error message means that Tk is calling your lambda with one argument, while your lambda is written to accept no arguments. If you don't need the argument, just accept one and don't use it. (Demosthenex has the code, I would have posted it but was beaten to it.)
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
If you want to define a 3D matrix containing all zeros, you write
A = zeros(8,4,20);
All ones uses ones
, all NaN's uses NaN
, all false uses false
instead of zeros
.
If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.
For example
B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
You can easily create a static object that represents a NULL return.
class Attr;
extern Attr AttrNull;
class Node {
....
Attr& getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return attributes[i];
//if not found
return AttrNull;
}
bool IsNull(const Attr& test) const {
return &test == &AttrNull;
}
private:
vector<Attr> attributes;
};
And somewhere in a source file:
static Attr AttrNull;
Use this String.valueOf(value);
from http://htmlhelp.com/reference/wilbur/misc/comment.html
Since HTML is officially an SGML application, the comment syntax used in HTML documents is actually the SGML comment syntax. Unfortunately this syntax is a bit unclear at first.
The definition of an SGML comment is basically as follows:
A comment declaration starts withThis means that the following are all legal SGML comments:<!
, followed by zero or more comments, followed by>
. A comment starts and ends with "--
", and does not contain any occurrence of "--
".Note that an "empty" comment tag, with just "
<!-- Hello -->
<!-- Hello -- -- Hello-->
<!---->
<!------ Hello -->
<!>
--
" characters, should always have a multiple of four "-
" characters to be legal. (And yes,<!>
is also a legal comment - it's the empty comment).Not all HTML parsers get this right. For example, "
<!------> hello-->
" is a legal comment, as you can verify with the rule above. It is a comment tag with two comments; the first is empty and the second one contains "> hello". If you try it in a browser, you will find that the text is displayed on screen.There are two possible reasons for this:
There is also the problem with the "
- The browser sees the ">" character and thinks the comment ends there.
- The browser sees the "
-->
" text and thinks the comment ends there.--
" sequence. Some people have a habit of using things like "<!-------------->
" as separators in their source. Unfortunately, in most cases, the number of "-
" characters is not a multiple of four. This means that a browser who tries to get it right will actually get it wrong here and actually hide the rest of the document.For this reason, use the following simple rule to compose valid and accepted comments:
An HTML comment begins with "<!--
", ends with "-->
" and does not contain "--
" or ">
" anywhere in the comment.
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
You haven't mentioned the DBMS. Assuming you are using MS SQL-Server, I've found a T-SQL Error message that is self-explanatory:
"An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference"
http://www.sql-server-performance.com/
And an example that it is possible in a subquery.
Show all customers and smallest order for those who have 5 or more orders (and NULL for others):
SELECT a.lastname
, a.firstname
, ( SELECT MIN( o.amount )
FROM orders o
WHERE a.customerid = o.customerid
AND COUNT( a.customerid ) >= 5
)
AS smallestOrderAmount
FROM account a
GROUP BY a.customerid
, a.lastname
, a.firstname ;
UPDATE.
The above runs in both SQL-Server and MySQL but it doesn't return the result I expected. The next one is more close. I guess it has to do with that the field customerid
, GROUPed BY and used in the query-subquery join is in the first case PRIMARY KEY of the outer table and in the second case it's not.
Show all customer ids and number of orders for those who have 5 or more orders (and NULL for others):
SELECT o.customerid
, ( SELECT COUNT( o.customerid )
FROM account a
WHERE a.customerid = o.customerid
AND COUNT( o.customerid ) >= 5
)
AS cnt
FROM orders o
GROUP BY o.customerid ;
you can add the selected values in an array
and set it as the value for default selection
eg:
var selectedItems =[];
selectedItems.push("your selected items");
..
$('#drp_Books_Ill_Illustrations').select2('val',selectedItems );
Try this, this should definitely work!
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
It seems in general you're just looking for a join:
> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
dat1 dat2
0 9 7
1 5 6
Use glutStrokeCharacter(GLUT_STROKE_ROMAN, myCharString)
.
An example: A STAR WARS SCROLLER.
#include <windows.h>
#include <string.h>
#include <GL\glut.h>
#include <iostream.h>
#include <fstream.h>
GLfloat UpwardsScrollVelocity = -10.0;
float view=20.0;
char quote[6][80];
int numberOfQuotes=0,i;
//*********************************************
//* glutIdleFunc(timeTick); *
//*********************************************
void timeTick(void)
{
if (UpwardsScrollVelocity< -600)
view-=0.000011;
if(view < 0) {view=20; UpwardsScrollVelocity = -10.0;}
// exit(0);
UpwardsScrollVelocity -= 0.015;
glutPostRedisplay();
}
//*********************************************
//* printToConsoleWindow() *
//*********************************************
void printToConsoleWindow()
{
int l,lenghOfQuote, i;
for( l=0;l<numberOfQuotes;l++)
{
lenghOfQuote = (int)strlen(quote[l]);
for (i = 0; i < lenghOfQuote; i++)
{
//cout<<quote[l][i];
}
//out<<endl;
}
}
//*********************************************
//* RenderToDisplay() *
//*********************************************
void RenderToDisplay()
{
int l,lenghOfQuote, i;
glTranslatef(0.0, -100, UpwardsScrollVelocity);
glRotatef(-20, 1.0, 0.0, 0.0);
glScalef(0.1, 0.1, 0.1);
for( l=0;l<numberOfQuotes;l++)
{
lenghOfQuote = (int)strlen(quote[l]);
glPushMatrix();
glTranslatef(-(lenghOfQuote*37), -(l*200), 0.0);
for (i = 0; i < lenghOfQuote; i++)
{
glColor3f((UpwardsScrollVelocity/10)+300+(l*10),(UpwardsScrollVelocity/10)+300+(l*10),0.0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, quote[l][i]);
}
glPopMatrix();
}
}
//*********************************************
//* glutDisplayFunc(myDisplayFunction); *
//*********************************************
void myDisplayFunction(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0.0, 30.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
RenderToDisplay();
glutSwapBuffers();
}
//*********************************************
//* glutReshapeFunc(reshape); *
//*********************************************
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 1.0, 1.0, 3200);
glMatrixMode(GL_MODELVIEW);
}
//*********************************************
//* int main() *
//*********************************************
int main()
{
strcpy(quote[0],"Luke, I am your father!.");
strcpy(quote[1],"Obi-Wan has taught you well. ");
strcpy(quote[2],"The force is strong with this one. ");
strcpy(quote[3],"Alert all commands. Calculate every possible destination along their last known trajectory. ");
strcpy(quote[4],"The force is with you, young Skywalker, but you are not a Jedi yet.");
numberOfQuotes=5;
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 400);
glutCreateWindow("StarWars scroller");
glClearColor(0.0, 0.0, 0.0, 1.0);
glLineWidth(3);
glutDisplayFunc(myDisplayFunction);
glutReshapeFunc(reshape);
glutIdleFunc(timeTick);
glutMainLoop();
return 0;
}
A few things I've noted:
For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.
<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">
I was trying to use this resource but kept getting an error, I found the code above worked perfectly.
Just replaced IMAGE URL HERE with the URL of your image - http://www.website.com/image.jpg
This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:
2019-03-12 09:35:43,659 INFO (null) - Application Started
I generally log both the Application_Start and Session_Start, so I see more detail in the next message
2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
log.Info("Application Started");
GlobalContext.Properties["page"] = new GetCurrentPage();
}
protected void Session_Start(object sender, EventArgs e)
{
Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
log.Info(string.Format("Session Started ({0})", Globals._Environment));
}
please try to install the dependencie with pip, run this command:
sudo pip install -U setuptools
Right code of two ppl before ^_^
/* return true if values of array are empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $value){
if(!empty($value)){
return false;
}
}
}
return true;
}
Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:
where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45
$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin
Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.
You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).
You can also link with .obj or other extensions if the object files have the correct format (such as COFF).
No. When your input type is submit, you should have an onsubmit
event declared in the markup and then do the changes you want. Meaning, have an onsubmit
defined in your form tag.
Otherwise change the input type to a button and then define an onclick
event for that button.
try out this....
using javascript
?document.getElementById('sel').value = 'car';??????????
using jQuery
$('#sel').val('car');
Html.Raw()
returns IHtmlString
, not the ordinary string
. So, you cannot write them in opposite sides of :
operator. Remove that .ToString()
calling
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))
// some code
@(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))
@(count++)
}
By the way, returning IHtmlString
is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString()
would destroy meaning of Html.Raw()
Possibly something along these lines:
SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT)
FROM dummy WHERE id = 1;
You can install some git aliases to make this process simpler. This edits the [alias]
node of your .gitconfig
file.
git config --global alias.ignore 'update-index --skip-worktree'
git config --global alias.unignore 'update-index --no-skip-worktree'
git config --global alias.ignored '!git ls-files -v | grep "^S"'
The shortcuts this installs for you are as follows:
git ignore config.xml
config.xml
— preventing you from accidentally committing those changes.git unignore config.xml
config.xml
— allowing you again to commit those changes.git ignored
I built these by referring to phatmann's answer — which presents an --assume-unchanged
version of the same.
The version I present uses --skip-worktree
for ignoring local changes. See Borealid's answer for a full explanation of the difference, but essentially --skip-worktree
's purpose is for developers to change files without the risk of committing their changes.
The git ignored
command presented here uses git ls-files -v
, and filters the list to show just those entries beginning with the S
tag. The S
tag denotes a file whose status is "skip worktree". For a full list of the file statuses shown by git ls-files
: see the documentation for the -t
option on git ls-files
.
setTimeout
may help out here
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
To scale an image, you need to create a new image and draw into it. One way is to use the filter()
method of an AffineTransferOp
, as suggested here. This allows you to choose the interpolation technique.
private static BufferedImage scale1(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
scaleOp.filter(before, after);
return after;
}
Another way is to simply draw the original image into the new image, using a scaling operation to do the scaling. This method is very similar, but it also illustrates how you can draw anything you want in the final image. (I put in a blank line where the two methods start to differ.)
private static BufferedImage scale2(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
Graphics2D g2 = (Graphics2D) after.getGraphics();
// Here, you may draw anything you want into the new image, but we're
// drawing a scaled version of the original image.
g2.drawImage(before, scaleOp, 0, 0);
g2.dispose();
return after;
}
Addendum: Results
To illustrate the differences, I compared the results of the five methods below. Here is what the results look like, scaled both up and down, along with performance data. (Performance varies from one run to the next, so take these numbers only as rough guidelines.) The top image is the original. I scale it double-size and half-size.
As you can see, AffineTransformOp.filter()
, used in scaleBilinear()
, is faster than the standard drawing method of Graphics2D.drawImage()
in scale2()
. Also BiCubic interpolation is the slowest, but gives the best results when expanding the image. (For performance, it should only be compared with scaleBilinear()
and scaleNearest().
) Bilinear seems to be better for shrinking the image, although it's a tough call. And NearestNeighbor is the fastest, with the worst results. Bilinear seems to be the best compromise between speed and quality. The Image.getScaledInstance()
, called in the questionable()
method, performed very poorly, and returned the same low quality as NearestNeighbor. (Performance numbers are only given for expanding the image.)
public static BufferedImage scaleBilinear(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_BILINEAR;
return scale(before, scale, interpolation);
}
public static BufferedImage scaleBicubic(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_BICUBIC;
return scale(before, scale, interpolation);
}
public static BufferedImage scaleNearest(BufferedImage before, double scale) {
final int interpolation = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
return scale(before, scale, interpolation);
}
@NotNull
private static
BufferedImage scale(final BufferedImage before, final double scale, final int type) {
int w = before.getWidth();
int h = before.getHeight();
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, before.getType());
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp = new AffineTransformOp(scaleInstance, type);
scaleOp.filter(before, after);
return after;
}
/**
* This is a more generic solution. It produces the same result, but it shows how you
* can draw anything you want into the newly created image. It's slower
* than scaleBilinear().
* @param before The original image
* @param scale The scale factor
* @return A scaled version of the original image
*/
private static BufferedImage scale2(BufferedImage before, double scale) {
int w = before.getWidth();
int h = before.getHeight();
// Create a new image of the proper size
int w2 = (int) (w * scale);
int h2 = (int) (h * scale);
BufferedImage after = new BufferedImage(w2, h2, before.getType());
AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp scaleOp
= new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);
Graphics2D g2 = (Graphics2D) after.getGraphics();
// Here, you may draw anything you want into the new image, but we're just drawing
// a scaled version of the original image. This is slower than
// calling scaleOp.filter().
g2.drawImage(before, scaleOp, 0, 0);
g2.dispose();
return after;
}
/**
* I call this one "questionable" because it uses the questionable getScaledImage()
* method. This method is no longer favored because it's slow, as my tests confirm.
* @param before The original image
* @param scale The scale factor
* @return The scaled image.
*/
private static Image questionable(final BufferedImage before, double scale) {
int w2 = (int) (before.getWidth() * scale);
int h2 = (int) (before.getHeight() * scale);
return before.getScaledInstance(w2, h2, Image.SCALE_FAST);
}
To disable all rules on a specific line:
alert('foo'); // eslint-disable-line
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
here is a workable sample cod, considering the image orientation:
#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
CGAffineTransform rectTransform;
switch (img.imageOrientation)
{
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}
- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
//transform visible rect to image orientation
CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);
//crop image
CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
CGImageRelease(imageRef);
return result;
}
Your CLASSPATH variable does not point to the directory containing the javax classes. The CLASSPATH variable specifies where the java compiler should look for java class file resources. If it does not know to look in the javax directory, then it will never find the file(s) you are after.
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {}
orPartial<User>
, or you need to redefine theUser
type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalz
I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Username
is left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "[email protected]";
Here is a working example for you.
@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
return (T) obj;
}
Yes: use urllib.
From the examples in the documentation:
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.geturl() # Prints the final URL with parameters.
>>> print f.read() # Prints the contents
I know it's equal to sizeof(int)
. The size of an int
is really compiler dependent. Back in the day, when processors were 16 bit, an int
was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems.
Still, using sizeof(int)
is the best way to get the size of an integer for the specific system the program is executed on.
EDIT: Fixed wrong statement that int
is 8 bytes on most 64-bit systems. For example, it is 4 bytes on 64-bit GCC.
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
I used declare methods with the public
modifier, because it makes the code more readable, especially with syntax highlighting. In our latest project though, we used Checkstyle which shows a warning with the default configuration for public
modifiers on interface methods, so I switched to ommitting them.
So I'm not really sure what's best, but one thing I really don't like is using public abstract
on interface methods. Eclipse does this sometimes when refactoring with "Extract Interface".
This is how I did grouping by multiple fields branchCode and prdId, Just posting it for someone in need
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
*
* @author charudatta.joshi
*/
public class Product1 {
public BigInteger branchCode;
public BigInteger prdId;
public String accountCode;
public BigDecimal actualBalance;
public BigDecimal sumActBal;
public BigInteger countOfAccts;
public Product1() {
}
public Product1(BigInteger branchCode, BigInteger prdId, String accountCode, BigDecimal actualBalance) {
this.branchCode = branchCode;
this.prdId = prdId;
this.accountCode = accountCode;
this.actualBalance = actualBalance;
}
public BigInteger getCountOfAccts() {
return countOfAccts;
}
public void setCountOfAccts(BigInteger countOfAccts) {
this.countOfAccts = countOfAccts;
}
public BigDecimal getSumActBal() {
return sumActBal;
}
public void setSumActBal(BigDecimal sumActBal) {
this.sumActBal = sumActBal;
}
public BigInteger getBranchCode() {
return branchCode;
}
public void setBranchCode(BigInteger branchCode) {
this.branchCode = branchCode;
}
public BigInteger getPrdId() {
return prdId;
}
public void setPrdId(BigInteger prdId) {
this.prdId = prdId;
}
public String getAccountCode() {
return accountCode;
}
public void setAccountCode(String accountCode) {
this.accountCode = accountCode;
}
public BigDecimal getActualBalance() {
return actualBalance;
}
public void setActualBalance(BigDecimal actualBalance) {
this.actualBalance = actualBalance;
}
@Override
public String toString() {
return "Product{" + "branchCode:" + branchCode + ", prdId:" + prdId + ", accountCode:" + accountCode + ", actualBalance:" + actualBalance + ", sumActBal:" + sumActBal + ", countOfAccts:" + countOfAccts + '}';
}
public static void main(String[] args) {
List<Product1> al = new ArrayList<Product1>();
System.out.println(al);
al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "001", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "002", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "003", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "004", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "005", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("13"), "006", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "007", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "008", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "009", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "010", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "011", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("13"), "012", new BigDecimal("10")));
//Map<BigInteger, Long> counting = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.counting()));
// System.out.println(counting);
//group by branch code
Map<BigInteger, List<Product1>> groupByBrCd = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.toList()));
System.out.println("\n\n\n" + groupByBrCd);
Map<BigInteger, List<Product1>> groupByPrId = null;
// Create a final List to show for output containing one element of each group
List<Product> finalOutputList = new LinkedList<Product>();
Product newPrd = null;
// Iterate over resultant Map Of List
Iterator<BigInteger> brItr = groupByBrCd.keySet().iterator();
Iterator<BigInteger> prdidItr = null;
BigInteger brCode = null;
BigInteger prdId = null;
Map<BigInteger, List<Product>> tempMap = null;
List<Product1> accListPerBr = null;
List<Product1> accListPerBrPerPrd = null;
Product1 tempPrd = null;
Double sum = null;
while (brItr.hasNext()) {
brCode = brItr.next();
//get list per branch
accListPerBr = groupByBrCd.get(brCode);
// group by br wise product wise
groupByPrId=accListPerBr.stream().collect(Collectors.groupingBy(Product1::getPrdId, Collectors.toList()));
System.out.println("====================");
System.out.println(groupByPrId);
prdidItr = groupByPrId.keySet().iterator();
while(prdidItr.hasNext()){
prdId=prdidItr.next();
// get list per brcode+product code
accListPerBrPerPrd=groupByPrId.get(prdId);
newPrd = new Product();
// Extract zeroth element to put in Output List to represent this group
tempPrd = accListPerBrPerPrd.get(0);
newPrd.setBranchCode(tempPrd.getBranchCode());
newPrd.setPrdId(tempPrd.getPrdId());
//Set accCOunt by using size of list of our group
newPrd.setCountOfAccts(BigInteger.valueOf(accListPerBrPerPrd.size()));
//Sum actual balance of our of list of our group
sum = accListPerBrPerPrd.stream().filter(o -> o.getActualBalance() != null).mapToDouble(o -> o.getActualBalance().doubleValue()).sum();
newPrd.setSumActBal(BigDecimal.valueOf(sum));
// Add product element in final output list
finalOutputList.add(newPrd);
}
}
System.out.println("+++++++++++++++++++++++");
System.out.println(finalOutputList);
}
}
Output is as below:
+++++++++++++++++++++++
[Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}]
After Formatting it :
[
Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2},
Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3},
Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1},
Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2},
Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3},
Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}
]
You can do like this
$q = $this->db->get()->row();
return $q->campaign_id;
Documentation : http://www.codeigniter.com/user_guide/database/results.html
surround.vim is going to be your easiest answer. If you are truly set against using it, here are some examples for what you can do. Not necessarily the most efficient, but that's why surround.vim was written.
ciw'Ctrl+r"'
ciw
- Delete the word the cursor is on, and end up in insert mode.'
- add the first quote.Ctrl+r"
- Insert the contents of the "
register, aka the last yank/delete.'
- add the closing quote.
di'hPl2x
di'
- Delete the word enclosed by single quotes.hP
- Move the cursor left one place (on top of the opening quote) and put the just deleted text before the quote.l
- Move the cursor right one place (on top of the opening quote).2x
- Delete the two quotes.
va':s/\%V'\%V/"/g
va'
- Visually select the quoted word and the quotes.:s/
- Start a replacement.\%V'\%V
- Only match single quotes that are within the visually selected region./"/g
- Replace them all with double quotes.var time = moment().toDate(); // This will return a copy of the Date that the moment uses
time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject
, then first get a String
from the result
:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject
:
JSONObject jsonObject = new JSONObject(jsonString);
CREATE OR REPLACE function f_add_col(_tbl regclass, _col text, _type regtype)
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = _tbl
AND attname = _col
AND NOT attisdropped) THEN
RETURN FALSE;
ELSE
EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
RETURN TRUE;
END IF;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT f_add_col('public.kat', 'pfad1', 'int');
Returns TRUE
on success, else FALSE
(column already exists).
Raises an exception for invalid table or type name.
This could be done with a DO
statement, but DO
statements cannot return anything. And if it's for repeated use, I would create a function.
I use the object identifier types regclass
and regtype
for _tbl
and _type
which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col
has still to be sanitized for EXECUTE
with quote_ident()
. More explanation in this related answer:
format()
requires Postgres 9.1+. For older versions concatenate manually:
EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
You can schema-qualify your table name, but you don't have to.
You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).
I query pg_catalog
instead of the information_schema
. Detailed explanation:
Blocks containing an EXCEPTION
clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:
Tip: A block containing an
EXCEPTION
clause is significantly more expensive to enter and exit than a block without one. Therefore, don't useEXCEPTION
without need.
I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import.';
break;
}
?>
You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
Linux is now officially supported in brew - see the Homebrew 2.0.0 blog post. As shown on https://brew.sh, just copy/paste this into a command prompt:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
select * from [tbl] where [link] is not null and len([link]) > 1
For MySQL user:
LENGTH([link]) > 1
Runtime is a general term that refers to any library, framework, or platform that your code runs on.
The C and C++ runtimes are collections of functions.
The .NET runtime contains an intermediate language interpreter, a garbage collector, and more.
The CSS documentation contains industry-standard CSS equivalent for all HTML constructs. That is: most web browsers these days do not explicitly handle SUB
, SUP
, B
, I
and so on - they (kinda sorta) are converted into SPAN
elements with appropriate CSS properties, and the rendering engine only deals with that.
The page is Appendix D. Default style sheet for HTML 4
The bits you want are:
small, sub, sup { font-size: .83em }
sub { vertical-align: sub }
sup { vertical-align: super }
If you don't mind dipping into Rx as part of the monad, you can use TakeLast
:
IEnumerable<int> source = Enumerable.Range(1, 10000);
IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();
If you are using Windows,
make a folder and open git bash from there
in the git bash,
git clone [email protected]:Example/projectName.git
In my case
li {
list-style-type : none;
}
It doesn't show the bullet but leaved some space for the bullet.
I use
li {
list-style-type : '';
}
It works perfectly.
I have solved the same problem with you,here is my operation environment( System:linux Versions:python 3.6 Package:Pyhive) please refer to my answer as follows:
from pyhive import hive
conn = hive.Connection(host='149.129.***.**', port=10000, username='*', database='*',password="*",auth='LDAP')
The key point is to add the reference password & auth and meanwhile set the auth equal to 'LDAP' . Then it works well, any questions please let me know
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
var string = "Hello World";
console.log(charAt(0));
The charAt(0) is JavaScript method, It will return value based on index, here 0 is the index for first letter.
I found the file in question located in /var/lib/jenkins called config.xml, modifying that fixed the issue.
//book[title[@lang='it']]
is actually equivalent to
//book[title/@lang = 'it']
I tried it using vtd-xml, both expressions spit out the same result... what xpath processing engine did you use? I guess it has conformance issue Below is the code
import com.ximpleware.*;
public class test1 {
public static void main(String[] s) throws Exception{
VTDGen vg = new VTDGen();
if (vg.parseFile("c:/books.xml", true)){
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("//book[title[@lang='it']]");
//ap.selectXPath("//book[title/@lang='it']");
int i;
while((i=ap.evalXPath())!=-1){
System.out.println("index ==>"+i);
}
/*if (vn.endsWith(i, "< test")){
System.out.println(" good ");
}else
System.out.println(" bad ");*/
}
}
}
An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.
wordwrap formats string according to limit, seprates them with \n so we have lines smaller than 50, ords are not seprated explodes seprates string according to \n so we have array corresponding to lines list gathers first element.
list($short) = explode("\n",wordwrap($ali ,50));
please rep Evert, since I cant comment or rep.
here is sample run
php > $ali = "ali veli krbin yz doksan esikesiksld sjkas laksjald lksjd asldkjadlkajsdlakjlksjdlkaj aslkdj alkdjs akdljsalkdj ";
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(42) "ali veli krbin yz doksan esikesiksld sjkas"
php > $ali ='';
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(0) ""
Use array_unshift($array, $item);
$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);
will give you
Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
For SQL server, the following will return the first row from giving table.
declare @rowNumber int = 1;
select TOP(@rowNumber) * from [dbo].[someTable];
EXCEPT
select TOP(@rowNumber - 1) * from [dbo].[someTable];
You can loop through the values with something like this:
WHILE @constVar > 0
BEGIN
declare @rowNumber int = @consVar;
select TOP(@rowNumber) * from [dbo].[someTable];
EXCEPT
select TOP(@rowNumber - 1) * from [dbo].[someTable];
SET @constVar = @constVar - 1;
END;
Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.
Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:
String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory saxFactory =
(SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);
Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
tHandler.startElement("", "", "html", new AttributesImpl());
tHandler.startElement("", "", "head", new AttributesImpl());
tHandler.startElement("", "", "title", new AttributesImpl());
tHandler.characters("Hello".toCharArray(), 0, 5);
tHandler.endElement("", "", "title");
tHandler.endElement("", "", "head");
tHandler.startElement("", "", "body", new AttributesImpl());
tHandler.startElement("", "", "p", new AttributesImpl());
tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
tHandler.endElement("", "", "p");
tHandler.endElement("", "", "body");
tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();
Note that XSLT transformer will release you from the burden of escaping special characters like >
, as it takes necessary care of it by itself.
And it is easy to wrap SAX methods like startElement()
and characters()
to something more convenient to one's taste...
a = [2 3 5];
b = [1 1 0];
c = a+b;
starts = zeros(3,3);
ends = [a;b;c];
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal
I use this class and have no problem.
public class WCFs
{
// https://192.168.30.8/myservice.svc?wsdl
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "192.168.30.8";
private static final String SERVICE = "/myservice.svc?wsdl";
private static String SOAP_ACTION = "http://tempuri.org/iWCFserviceMe/";
public static Thread myMethod(Runnable rp)
{
String METHOD_NAME = "myMethod";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Message", "Https WCF Running...");
return _call(rp,METHOD_NAME, request);
}
protected static HandlerThread _call(final RunProcess rp,final String METHOD_NAME, SoapObject soapReq)
{
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
int TimeOut = 5*1000;
envelope.dotNet = true;
envelope.bodyOut = soapReq;
envelope.setOutputSoapObject(soapReq);
final HttpsTransportSE httpTransport_net = new HttpsTransportSE(URL, 443, SERVICE, TimeOut);
try
{
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() // use this section if crt file is handmake
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
KeyStore k = getFromRaw(R.raw.key, "PKCS12", "password");
((HttpsServiceConnectionSE) httpTransport_net.getServiceConnection()).setSSLSocketFactory(getSSLSocketFactory(k, "SSL"));
}
catch(Exception e){}
HandlerThread thread = new HandlerThread("wcfTd"+ Generator.getRandomNumber())
{
@Override
public void run()
{
Handler h = new Handler(Looper.getMainLooper());
Object response = null;
for(int i=0; i<4; i++)
{
response = send(envelope, httpTransport_net , METHOD_NAME, null);
try
{if(Thread.currentThread().isInterrupted()) return;}catch(Exception e){}
if(response != null)
break;
ThreadHelper.threadSleep(250);
}
if(response != null)
{
if(rp != null)
{
rp.setArguments(response.toString());
h.post(rp);
}
}
else
{
if(Thread.currentThread().isInterrupted())
return;
if(rp != null)
{
rp.setExceptionState(true);
h.post(rp);
}
}
ThreadHelper.stopThread(this);
}
};
thread.start();
return thread;
}
private static Object send(SoapSerializationEnvelope envelope, HttpTransportSE androidHttpTransport, String METHOD_NAME, List<HeaderProperty> headerList)
{
try
{
if(headerList != null)
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope, headerList);
else
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
Object res = envelope.getResponse();
if(res instanceof SoapPrimitive)
return (SoapPrimitive) envelope.getResponse();
else if(res instanceof SoapObject)
return ((SoapObject) envelope.getResponse());
}
catch(Exception e)
{}
return null;
}
public static KeyStore getFromRaw(@RawRes int id, String algorithm, String filePassword)
{
try
{
InputStream inputStream = ResourceMaster.openRaw(id);
KeyStore keystore = KeyStore.getInstance(algorithm);
keystore.load(inputStream, filePassword.toCharArray());
inputStream.close();
return keystore;
}
catch(Exception e)
{}
return null;
}
public static SSLSocketFactory getSSLSocketFactory(KeyStore trustKey, String SSLAlgorithm)
{
try
{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustKey);
SSLContext context = SSLContext.getInstance(SSLAlgorithm);//"SSL" "TLS"
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
catch(Exception e){}
return null;
}
}
I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :
I used unsignedBigInteger('user_id') to define the foreign referenced key.
Schema::create('generals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('general_name');
$table->string('status');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('general_id');
$table->foreign('general_id')->references('id')->on('generals');
$table->string('category_name');
$table->string('status');
$table->timestamps();
});
I hope this helps out.
This error is because of multiple project having the offending resources.
Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)
Yes it is deprecated. Replace your SessionFactory with the following:
In Hibernate 4.0, 4.1, 4.2
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
UPDATE:
In Hibernate 4.3 ServiceRegistryBuilder is deprecated. Use the following instead.
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:
var arr = arr.OrderBy(x=>x).ToArray();
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
try using cfg4py:
DISCLAIMER: I'm the author of this module
Pass the array to a method that sorts it with Arrays.sort()
so it only sorts the array the method is using then sets min to array[0]
and max to array[array.length-1]
.
This may be of help to a few who are struggling like I was:
var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];
In addition to Andrew's and Max's solutions, using iframe.focus() resulted in printing parent frame instead of printing only child iframe in IE8. Changing that line fixed it:
function printIframe(id)
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
return false;
}
$services = $this->Service->find('all', array(
'limit' =>4,
'fields' => array('Service.*','ServiceImage.*'),
'joins' => array(
array(
'table' => 'services_images',
'alias' => 'ServiceImage',
'type' => 'INNER',
'conditions' => array(
'ServiceImage.service_id' =>'Service.id'
)
),
),
)
);
It goges to array is null.
In order to resolve this issue for WebApps added to the home screen, both of the top voted workarounds need to be followed. Caching needs to be turned off on the webserver to prevent new requests from being cached going forward and some random input needs to be added to every post request in order for requests that have already been cached to go through. Please refer to my post:
iOS6 - Is there a way to clear cached ajax POST requests for webapp added to home screen?
WARNING: to anyone who implemented a workaround by adding a timestamp to their requests without turning off caching on the server. If your app is added to the home screen, EVERY post response will now be cached, clearing safari cache doesn't clear it and it doesn't seem to expire. Unless someone has a way to clear it, this looks like a potential memory leak!
document.forms['someform'].elements['someelement'].value
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message)
Don't create any segue from Cancel or Done to other VC and only write this code your buttons @IBAction
@IBAction func cancel(sender: AnyObject) {
dismiss(animated: false, completion: nil)
}
HttpClient.get()
applies res.json()
automatically and returns Observable<HttpResponse<string>>
. You no longer need to call this function yourself.
If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.
IInterface
.IInterface
In source, it looks like this:
Any interface you want to be passed as the generic parameter:
public interface IWhatever : IInterface
{
// IWhatever specific declarations
}
IInterface:
public interface IInterface
{
// Nothing in here, keep moving
}
The class on which you want to put the type constraint:
public class WorldPeaceGenerator<T> where T : IInterface
{
// Actual world peace generating code
}
You can use NestedScrollView
instead of ScrollView
. However, when using a Kotlin Lambda, it won't know you want NestedScrollView's setOnScrollChangeListener
instead of the one at View (which is API level 23). You can fix this by specifying the first parameter as a NestedScrollView.
nestedScrollView.setOnScrollChangeListener { _: NestedScrollView, scrollX: Int, scrollY: Int, _: Int, _: Int ->
Log.d("ScrollView", "Scrolled to $scrollX, $scrollY")
}
I think you want to use typeof() here:
function f(id, parameters, callback) {
console.log(typeof(parameters)+" "+typeof(callback));
}
f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"
I know this thread is old, but figured I would throw in what came up with since I just ran into this same issue. It may not be efficient, but I believe it gets the job done.
SELECT TOP 10 p.id, pl.nm, pl.val, pl.txt_val
INTO #yourTempTable
from dm.labs pl
join mas_data.patients p on pl.id = p.id
where pl.nm like '%LDL%' and val is not null
select p.id, pl.nm, pl.val, pl.txt_val
from #yourTempTable
where id IN (select distinct id from #yourTempTable)
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
Modifications to sys.path
only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH
environment variable:
PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH
Note that PATH
is the system path for executables, which is completely separate.
**You can write the above in ~/.bash_profile
and the source it using source ~/.bash_profile
A compiler consists of two major blocks: the 'front end' and the 'back end'. The front end of a compiler analyzes the source code and builds some form of a 'intermediary representation' of said source code which is much easier to analyze by a machine algorithm than is the source code (i.e. whereas the source code e.g. C++ is designed to help the human programmer to write code, the intermediary form is designed to help simplify the algorithm that analyzes said intermediary form easier). The back end of a compiler takes the intermediary form and then converts it to a 'target language'.
Now, the target language for general-use compilers are assembler languages for various processors, but there's nothing to prohibit a compiler back end to produce code in some other language, for as long as said target language is (at least) as flexible as a general CPU assembler.
Now, as you can probably imagine, C is definitely as flexible as a CPU's assembler, such that a C++ to C compiler is really no problem to implement from a technical pov.
So you have: C++ ---frontEnd---> someIntermediaryForm ---backEnd---> C
You may want to check these guys out: http://www.edg.com/index.php?location=c_frontend (the above link is just informative for what can be done, they license their front ends for tens of thousands of dollars)
PS As far as i know, there is no such a C++ to C compiler by GNU, and this totally beats me (if i'm right about this). Because the C language is fairly small and it's internal mechanisms are fairly rudimentary, a C compiler requires something like one man-year work (i can tell you this first hand cause i wrote such a compiler myself may years ago, and it produces a [virtual] stack machine intermediary code), and being able to have a maintained, up-to-date C++ compiler while only having to write a C compiler once would be a great thing to have...
One advantage that the aforementioned copy-webpack-plugin brings that hasn't been explained before is that all the other methods mentioned here still bundle the resources into your bundle files (and require you to "require" or "import" them somewhere). If I just want to move some images around or some template partials, I don't want to clutter up my javascript bundle file with useless references to them, I just want the files emitted in the right place. I haven't found any other way to do this in webpack. Admittedly it's not what webpack originally was designed for, but it's definitely a current use case. (@BreakDS I hope this answers your question - it's only a benefit if you want it)
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
I did it with xlsx and it worked fine.
If you have thousands, consider using a trie. A trie is a tree-like structure that merges the common prefixes of the stored string.
For example, if the strings were
intern
international
internationalize
internet
internets
The trie would store:
intern
-> \0
international
-> \0
-> ize\0
net
->\0
->s\0
The strings requires 57 characters (including the null terminator, '\0') for storage, plus whatever the size of the String object that holds them. (In truth, we should probably round all sizes up to multiples of 16, but...) Call it 57 + 5 = 62 bytes, roughly.
The trie requires 29 (including the null terminator, '\0') for storage, plus sizeof the trie nodes, which are a ref to an array and a list of child trie nodes.
For this example, that probably comes out about the same; for thousands, it probably comes out less as long as you do have common prefixes.
Now, when using the trie in other code, you'll have to convert to String, probably using a StringBuffer as an intermediary. If many of the strings are in use at once as Strings, outside the trie, it's a loss.
But if you're only using a few at the time -- say, to look up things in a dictionary -- the trie can save you a lot of space. Definitely less space than storing them in a HashSet.
You say you're accessing them "serially" -- if that means sequentially an alphabetically, the trie also obviously gives you alphabetical order for free, if you iterate it depth-first.
I just ran into the same problem, but I manage to have my query working in SQLite like this:
@shows = Show.order("datetime(date) ASC, attending DESC")
I hope this might help someone save some time
Open preferences windows (Command key + "," on Mac):
1.Tools
2.Python Integrated Tools
3.Default test runner
If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!
Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
SYSDATE
and GETDATE
perform identically.
SYSDATE
is compatible with Oracle syntax, and GETDATE
is compatible with Microsoft SQL Server syntax.
When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel
. The benefit of extending Swing
components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint()
method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.
Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer
below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.
Here are the basic steps:
JComponent
super()
in your constructorsMouseListener
Put this in the constructor:
enableInputMethods(true);
addMouseListener(this);
Override these methods:
public Dimension getPreferredSize()
public Dimension getMinimumSize()
public Dimension getMaximumSize()
Override this method:
public void paintComponent(Graphics g)
The amount of space you have to work with when drawing your button is defined by getPreferredSize()
, assuming getMinimumSize()
and getMaximumSize()
return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.
And finally, the source code. In case I missed anything.
String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
File file = new File(FILE_NAME);
if((file.length()) <= (1048576)) {
System.out.println("file size is less than 1 mb");
}else {
System.out.println("file size is More than 1 mb");
}
Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb
For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.
Here is a link to the caniuse js MutationObserver
Simple usage with powerful results.
var observer = new MutationObserver(function (mutations) {
//your action here
});
//set up your configuration
//this will watch to see if you insert or remove any children
var config = { subtree: true, childList: true };
//start observing
observer.observe(elementTarget, config);
When you don't need to observe any longer just disconnect.
observer.disconnect();
Check out the MDN documentation for more information
Your call to MessageBox.Show
needs to pass MessageBoxButtons.YesNo
to get the Yes/No buttons instead of the OK button.
Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes
....
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
// user clicked yes
}
else
{
// user clicked no
}
Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX" &&
r.Field<string>("UserName") != "YYYY"
select r;
DataTable newDT = query.CopyToDataTable();
Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.
EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames
:
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where !ignoredUserNames.Contains(r.Field<string>("UserName"))
select r;
DataTable newDT = query.CopyToDataTable();
Ideally you'd want to make this a HashSet<string>
to avoid the Contains
call taking a long time, but if the collection is small enough it won't make much odds.
Add log4jExposeWebAppRoot -> false in your web.xml. It works with me :)
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>path/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
To find the size of an array use the scalar
keyword:
print scalar @array;
To find out the last index of an array there is $#
(Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#
:
print "$#array+1";
Example:
my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";
Output:
3
3
// First Get DataTable as dt
// DataRowComparer Compare columns numbers in each row & data in each row
IEnumerable<DataRow> Distinct = dt.AsEnumerable().Distinct(DataRowComparer.Default);
foreach (DataRow row in Distinct)
{
Console.WriteLine("{0,-15} {1,-15}",
row.Field<int>(0),
row.Field<string>(1));
}
You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.
Example:
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);
You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.
However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).
More information about Gson here.
Remember that the object must implement the Serializable interface.
With Java8 there is a default sort method on the List interface that will allow you to sort the collection if you provide a Comparator. You can easily sort the example in the question as follows:
testList.sort((a, b) -> Double.compare(b, a));
Note: the args in the lambda are swapped when passed in to Double.compare to ensure the sort is descending
I'm assuming you mean that 'use' means read, but what i'll explain for the read case can be basically reversed for the write case.
so you end up with a byte[]. this could represent any kind of data which may need special types of conversions (character, encrypted, etc). let's pretend you want to write this data as is to a file.
firstly you could create a ByteArrayInputStream which is basically a mechanism to supply the bytes to something in sequence.
then you could create a FileOutputStream for the file you want to create. there are many types of InputStreams and OutputStreams for different data sources and destinations.
lastly you would write the InputStream to the OutputStream. in this case, the array of bytes would be sent in sequence to the FileOutputStream for writing. For this i recommend using IOUtils
byte[] bytes = ...;//
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(new File(...));
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
and in reverse
FileInputStream in = new FileInputStream(new File(...));
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
byte[] bytes = out.toByteArray();
if you use the above code snippets you'll need to handle exceptions and i recommend you do the 'closes' in a finally block.
Use +
plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.
checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application
Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.
VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.
Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.
Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:
You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub
in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.
and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.
I hope this has been helpful
Note: cuongle's helfpul answer has all the ingredients, but the solution can be streamlined (no need for .ItemArray
) and can be reframed to better match the question as asked.
To create an (isolated) clone of a given System.Data.DataRow
instance, you can do the following:
// Assume that variable `table` contains the source data table.
// Create an auxiliary, empty, column-structure-only clone of the source data table.
var tableAux = table.Clone();
// Note: .Copy(), by contrast, would clone the data rows also.
// Select the data row to clone, e.g. the 2nd one:
var row = table.Rows[1];
// Import the data row of interest into the aux. table.
// This creates a *shallow clone* of it.
// Note: If you'll be *reusing* the aux. table for single-row cloning later, call
// tableAux.Clear() first.
tableAux.ImportRow(row);
// Extract the cloned row from the aux. table:
var rowClone = tableAux.Rows[0];
Note: Shallow cloning is performed, which works as-is with column values that are value type instances, but more work would be needed to also create independent copies of column values containing reference type instances (and creating such independent copies isn't always possible).
The core team responsible for Postgres is gradually phasing out OIDs.
The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:
CREATE TABLE … WITH OIDS
commanddefault_with_oids (boolean)
compatibility settingThe data type OID
remains in Postgres 12. You can explicitly create a column of the type OID
.
After migrating to Postgres 12, any optionally-defined system column oid
will no longer be invisible by default. Performing a SELECT *
will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.