I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated
I call
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
for Support Toolbar v7 android.support.v7.widget.Toolbar
:
code
toolbar.setBackground(null);
// or
toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
xml (android:background="@null"
or android:background="@android:color/transparent"
)
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@null"
android:minHeight="?attr/actionBarSize"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:ellipsize="start"
android:singleLine="true"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
</android.support.v7.widget.Toolbar>
if Title is invisible, set textColor
I had this issue too. The way I solved it was the following:
android-sdk-x/extras/google_play_services/libproject
. When you import a project, you get the option "Copy project into workspace". UNCHECK IT.This did the trick for me. I hope it helps you too!
If you want to launch from a batch file:
for x86
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
for x64
start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login
Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.
<div class="outer-container">
<div class="inner-container">
<div class="video-overlay">Bug Buck Bunny - Trailer</div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
</div>
</div>
with css as
.outer-container {
border: 1px dotted black;
width: 100%;
height: 100%;
text-align: center;
}
.inner-container {
border: 1px solid black;
display: inline-block;
position: relative;
}
.video-overlay {
position: absolute;
left: 0px;
top: 0px;
margin: 10px;
padding: 5px 5px;
font-size: 20px;
font-family: Helvetica;
color: #FFF;
background-color: rgba(50, 50, 50, 0.3);
}
video {
width: 100%;
height: 100%;
}
here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/
Hope that helps :)
You don't set the behavior of controls via CSS
, only their styling.You can use jquery
or simple javascript
to change the property of the fields.
This is not a problem, like Avada Kedavra said, actually, this is documented here, in the section "Icon Overlay Settings", and I also show bellow. You can read that, and choose the one you like most.
Since it takes quite a while to fetch the status of a working copy, TortoiseSVN uses a cache to store the status so the explorer doesn't get hogged too much when showing the overlays. You can choose which type of cache TortoiseSVN should use according to your system and working copy size here:
Default
Caches all status information in a separate process (TSVNCache.exe). That process watches all drives for changes and fetches the status again if files inside a working copy get modified. The process runs with the least possible priority so other programs don't get hogged because of it. That also means that the status information is not real time but it can take a few seconds for the overlays to change.
Advantage: the overlays show the status recursively, i.e. if a file deep inside a working copy is modified, all folders up to the working copy root will also show the modified overlay. And since the process can send notifications to the shell, the overlays on the left tree view usually change too.
Disadvantage: the process runs constantly, even if you're not working on your projects. It also uses around 10-50 MB of RAM depending on number and size of your working copies.
Shell
Caching is done directly inside the shell extension dll, but only for the currently visible folder. Each time you navigate to another folder, the status information is fetched again.
Advantage: needs only very little memory (around 1 MB of RAM) and can show the status in real time.
Disadvantage: Since only one folder is cached, the overlays don't show the status recursively. For big working copies, it can take more time to show a folder in explorer than with the default cache. Also the mime-type column is not available.
None
With this setting, the TortoiseSVN does not fetch the status at all in Explorer. Because of that, files don't get an overlay and folders only get a 'normal' overlay if they're versioned. No other overlays are shown, and no extra columns are available either.
Advantage: uses absolutely no additional memory and does not slow down the Explorer at all while browsing.
Disadvantage: Status information of files and folders is not shown in Explorer. To see if your working copies are modified, you have to use the “Check for modifications” dialog.
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
Another option is to use one of my personal favorite CSS tools: box-shadow
.
A box shadow is really a drop-shadow on the node. It looks like this:
-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);
The arguments are:
1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect. 0 means no blur.
color: The color of the shadow.
So, you could leave your current design, and add a box-shadow like:
box-shadow: 0px -2px 2px rgba(34,34,34,0.6);
This should give you a 'blurry' top-edge.
This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/
As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.
For version 6, you need a small adjustment when you use Subject. You need to add the generic type.
loadingStatus: Subject<boolean> = new Subject();
I'm using angular material, so instead of a loading text, you can use mat-spinner.
<mat-spinner></mat-spinner>
Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend
And as Miranda recommended into comments, here is also the solution:
The loading screen component:
loading-screen.component.ts
import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';
@Component({
selector: 'app-loading-screen',
templateUrl: './loading-screen.component.html',
styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {
loading: boolean = false;
loadingSubscription: Subscription;
constructor(
private loadingScreenService: LoadingScreenService,
private _elmRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef
) { }
ngAfterViewInit(): void {
this._elmRef.nativeElement.style.display = 'none';
this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
(status: boolean) => {
this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
this._changeDetectorRef.detectChanges();
}
);
}
ngOnDestroy() {
console.log("inside destroy loading component");
this.loadingSubscription.unsubscribe();
}
}
loading-screen.component.html
<div id="overlay">
<mat-spinner class="content"></mat-spinner>
</div>
loading-screen.component.css
#overlay {
position: fixed; /* Sit on top of the page content */
display: block; /* Hidden by default */
width: 100%; /* Full width (cover the whole page) */
height: 100%; /* Full height (cover the whole page) */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
opacity: 0.5;
z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
cursor: progress; /* Add a pointer on hover */
}
.content {
position: absolute;
top: 50%;
left: 50%;
font-size: 50px;
color: white;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
Don't forget to add the component to your root component. In my case, AppComponent
app.component.html
<app-loading-screen></app-loading-screen>
The service that will manage the component: loading-screen.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingScreenService {
constructor() { }
private _loading: boolean = false;
loadingStatus: Subject<boolean> = new Subject();
get loading(): boolean {
console.log("get loading: " + this._loading);
return this._loading;
}
set loading(value) {
console.log("get loading: " + value);
this._loading = value;
this.loadingStatus.next(value);
}
startLoading() {
console.log("startLoading");
this.loading = true;
}
stopLoading() {
console.log("stopLoading");
this.loading = false;
}
}
Here is the http interceptor, which will show/hide the component, using the previous service.
loading-screen-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
activeRequests: number = 0;
constructor(
private loadingScreenService: LoadingScreenService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("inside interceptor");
if (this.activeRequests === 0) {
this.loadingScreenService.startLoading();
}
this.activeRequests++;
return next.handle(request).pipe(
finalize(() => {
this.activeRequests--;
if (this.activeRequests === 0) {
this.loadingScreenService.stopLoading();
}
})
)
};
}
And in your app.module.ts, don't forget to config the interceptor
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingScreenInterceptor,
multi: true
}
]
This one works for me:
html
<ul>
<li> name here </li>
</ul>
CSS
ul li::before {
content: url(../images/check.png);
}
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
This problem can also arise if you include jQuery more than once.
Take a look at List14 example. In getView()
you can call convertView.setBackgroundDrawable()
for each entry. You could have a class member counter to decide which background to call it with to get alternating backgrounds, for example.
Yes you need to use overlays.
You need to get the MapView's overlays and add your new overlay onto it.
Your class extends Overlay, which is a transparent canvas in which you can draw on it like any other canvas.
You can use mapView.getProjection() to get projection of map view.
...
More info found here: http://blogoscoped.com/archive/2008-12-15-n14.html
Simply do the following:
I. Declare a global variable:
var markersArray = [];
II. Define a function:
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
OR
google.maps.Map.prototype.clearOverlays = function() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
III. Push markers in the 'markerArray' before calling the following:
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});
IV. Call the clearOverlays();
or map.clearOverlays();
function wherever required.
That's it!!
This will zoom in and out as well as pan but keep the image within the bounds of the container. Written as a control so add the style to the App.xaml
directly or through the Themes/Viewport.xaml
.
For readability I've also uploaded this on gist and github
I've also packaged this up on nuget
PM > Install-Package Han.Wpf.ViewportControl
./Controls/Viewport.cs:
public class Viewport : ContentControl
{
private bool _capture;
private FrameworkElement _content;
private Matrix _matrix;
private Point _origin;
public static readonly DependencyProperty MaxZoomProperty =
DependencyProperty.Register(
nameof(MaxZoom),
typeof(double),
typeof(Viewport),
new PropertyMetadata(0d));
public static readonly DependencyProperty MinZoomProperty =
DependencyProperty.Register(
nameof(MinZoom),
typeof(double),
typeof(Viewport),
new PropertyMetadata(0d));
public static readonly DependencyProperty ZoomSpeedProperty =
DependencyProperty.Register(
nameof(ZoomSpeed),
typeof(float),
typeof(Viewport),
new PropertyMetadata(0f));
public static readonly DependencyProperty ZoomXProperty =
DependencyProperty.Register(
nameof(ZoomX),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty ZoomYProperty =
DependencyProperty.Register(
nameof(ZoomY),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty OffsetXProperty =
DependencyProperty.Register(
nameof(OffsetX),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty OffsetYProperty =
DependencyProperty.Register(
nameof(OffsetY),
typeof(double),
typeof(Viewport),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty BoundsProperty =
DependencyProperty.Register(
nameof(Bounds),
typeof(Rect),
typeof(Viewport),
new FrameworkPropertyMetadata(default(Rect), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public Rect Bounds
{
get => (Rect) GetValue(BoundsProperty);
set => SetValue(BoundsProperty, value);
}
public double MaxZoom
{
get => (double) GetValue(MaxZoomProperty);
set => SetValue(MaxZoomProperty, value);
}
public double MinZoom
{
get => (double) GetValue(MinZoomProperty);
set => SetValue(MinZoomProperty, value);
}
public double OffsetX
{
get => (double) GetValue(OffsetXProperty);
set => SetValue(OffsetXProperty, value);
}
public double OffsetY
{
get => (double) GetValue(OffsetYProperty);
set => SetValue(OffsetYProperty, value);
}
public float ZoomSpeed
{
get => (float) GetValue(ZoomSpeedProperty);
set => SetValue(ZoomSpeedProperty, value);
}
public double ZoomX
{
get => (double) GetValue(ZoomXProperty);
set => SetValue(ZoomXProperty, value);
}
public double ZoomY
{
get => (double) GetValue(ZoomYProperty);
set => SetValue(ZoomYProperty, value);
}
public Viewport()
{
DefaultStyleKey = typeof(Viewport);
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
private void Arrange(Size desired, Size render)
{
_matrix = Matrix.Identity;
var zx = desired.Width / render.Width;
var zy = desired.Height / render.Height;
var cx = render.Width < desired.Width ? render.Width / 2.0 : 0.0;
var cy = render.Height < desired.Height ? render.Height / 2.0 : 0.0;
var zoom = Math.Min(zx, zy);
if (render.Width > desired.Width &&
render.Height > desired.Height)
{
cx = (desired.Width - (render.Width * zoom)) / 2.0;
cy = (desired.Height - (render.Height * zoom)) / 2.0;
_matrix = new Matrix(zoom, 0d, 0d, zoom, cx, cy);
}
else
{
_matrix.ScaleAt(zoom, zoom, cx, cy);
}
}
private void Attach(FrameworkElement content)
{
content.MouseMove += OnMouseMove;
content.MouseLeave += OnMouseLeave;
content.MouseWheel += OnMouseWheel;
content.MouseLeftButtonDown += OnMouseLeftButtonDown;
content.MouseLeftButtonUp += OnMouseLeftButtonUp;
content.SizeChanged += OnSizeChanged;
content.MouseRightButtonDown += OnMouseRightButtonDown;
}
private void ChangeContent(FrameworkElement content)
{
if (content != null && !Equals(content, _content))
{
if (_content != null)
{
Detatch();
}
Attach(content);
_content = content;
}
}
private double Constrain(double value, double min, double max)
{
if (min > max)
{
min = max;
}
if (value <= min)
{
return min;
}
if (value >= max)
{
return max;
}
return value;
}
private void Constrain()
{
var x = Constrain(_matrix.OffsetX, _content.ActualWidth - _content.ActualWidth * _matrix.M11, 0);
var y = Constrain(_matrix.OffsetY, _content.ActualHeight - _content.ActualHeight * _matrix.M22, 0);
_matrix = new Matrix(_matrix.M11, 0d, 0d, _matrix.M22, x, y);
}
private void Detatch()
{
_content.MouseMove -= OnMouseMove;
_content.MouseLeave -= OnMouseLeave;
_content.MouseWheel -= OnMouseWheel;
_content.MouseLeftButtonDown -= OnMouseLeftButtonDown;
_content.MouseLeftButtonUp -= OnMouseLeftButtonUp;
_content.SizeChanged -= OnSizeChanged;
_content.MouseRightButtonDown -= OnMouseRightButtonDown;
}
private void Invalidate()
{
if (_content != null)
{
Constrain();
_content.RenderTransformOrigin = new Point(0, 0);
_content.RenderTransform = new MatrixTransform(_matrix);
_content.InvalidateVisual();
ZoomX = _matrix.M11;
ZoomY = _matrix.M22;
OffsetX = _matrix.OffsetX;
OffsetY = _matrix.OffsetY;
var rect = new Rect
{
X = OffsetX * -1,
Y = OffsetY * -1,
Width = ActualWidth,
Height = ActualHeight
};
Bounds = rect;
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_matrix = Matrix.Identity;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
if (Content is FrameworkElement element)
{
ChangeContent(element);
}
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (Content is FrameworkElement element)
{
ChangeContent(element);
}
SizeChanged += OnSizeChanged;
Loaded -= OnLoaded;
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
if (_capture)
{
Released();
}
}
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsEnabled && !_capture)
{
Pressed(e.GetPosition(this));
}
}
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (IsEnabled && _capture)
{
Released();
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (IsEnabled && _capture)
{
var position = e.GetPosition(this);
var point = new Point
{
X = position.X - _origin.X,
Y = position.Y - _origin.Y
};
var delta = point;
_origin = position;
_matrix.Translate(delta.X, delta.Y);
Invalidate();
}
}
private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsEnabled)
{
Reset();
}
}
private void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
if (IsEnabled)
{
var scale = e.Delta > 0 ? ZoomSpeed : 1 / ZoomSpeed;
var position = e.GetPosition(_content);
var x = Constrain(scale, MinZoom / _matrix.M11, MaxZoom / _matrix.M11);
var y = Constrain(scale, MinZoom / _matrix.M22, MaxZoom / _matrix.M22);
_matrix.ScaleAtPrepend(x, y, position.X, position.Y);
ZoomX = _matrix.M11;
ZoomY = _matrix.M22;
Invalidate();
}
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
if (_content?.IsMeasureValid ?? false)
{
Arrange(_content.DesiredSize, _content.RenderSize);
Invalidate();
}
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
Detatch();
SizeChanged -= OnSizeChanged;
Unloaded -= OnUnloaded;
}
private void Pressed(Point position)
{
if (IsEnabled)
{
_content.Cursor = Cursors.Hand;
_origin = position;
_capture = true;
}
}
private void Released()
{
if (IsEnabled)
{
_content.Cursor = null;
_capture = false;
}
}
private void Reset()
{
_matrix = Matrix.Identity;
if (_content != null)
{
Arrange(_content.DesiredSize, _content.RenderSize);
}
Invalidate();
}
}
./Themes/Viewport.xaml:
<ResourceDictionary ... >
<Style TargetType="{x:Type controls:Viewport}"
BasedOn="{StaticResource {x:Type ContentControl}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:Viewport}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}">
<Grid ClipToBounds="True"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}">
<Grid x:Name="PART_Container">
<ContentPresenter x:Name="PART_Presenter" />
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
./App.xaml
<Application ... >
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="./Themes/Viewport.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Usage:
<viewers:Viewport>
<Image Source="{Binding}"/>
</viewers:Viewport>
Any issues, give me a shout.
Happy coding :)
use extent with custom function to handle multiple inheritance with es6
var aggregation = (baseClass, ...mixins) => {_x000D_
let base = class _Combined extends baseClass {_x000D_
constructor (...args) {_x000D_
super(...args)_x000D_
mixins.forEach((mixin) => {_x000D_
mixin.prototype.initializer.call(this)_x000D_
})_x000D_
}_x000D_
}_x000D_
let copyProps = (target, source) => {_x000D_
Object.getOwnPropertyNames(source)_x000D_
.concat(Object.getOwnPropertySymbols(source))_x000D_
.forEach((prop) => {_x000D_
if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))_x000D_
return_x000D_
Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))_x000D_
})_x000D_
}_x000D_
mixins.forEach((mixin) => {_x000D_
copyProps(base.prototype, mixin.prototype)_x000D_
copyProps(base, mixin)_x000D_
})_x000D_
return base_x000D_
}_x000D_
_x000D_
class Colored {_x000D_
initializer () { this._color = "white" }_x000D_
get color () { return this._color }_x000D_
set color (v) { this._color = v }_x000D_
}_x000D_
_x000D_
class ZCoord {_x000D_
initializer () { this._z = 0 }_x000D_
get z () { return this._z }_x000D_
set z (v) { this._z = v }_x000D_
}_x000D_
_x000D_
class Shape {_x000D_
constructor (x, y) { this._x = x; this._y = y }_x000D_
get x () { return this._x }_x000D_
set x (v) { this._x = v }_x000D_
get y () { return this._y }_x000D_
set y (v) { this._y = v }_x000D_
}_x000D_
_x000D_
class Rectangle extends aggregation(Shape, Colored, ZCoord) {}_x000D_
_x000D_
var rect = new Rectangle(7, 42)_x000D_
rect.z = 1000_x000D_
rect.color = "red"_x000D_
console.log(rect.x, rect.y, rect.z, rect.color)
_x000D_
You can also try clicking by JavaScript:
WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);
Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.
Required Format Allow these 3:
Don't Allow other formats:
validatePnrAndTicketNumber(){
let alphaNumericRegex=/^[a-zA-Z0-9]*$/;
let numericRegex=/^[0-9]*$/;
let numericdashRegex=/^(([1-9]{3})\-?([0-9]{10}))$/;
this.currBookingRefValue = this.requestForm.controls["bookingReference"].value;
if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else{
this.requestForm.controls["bookingReference"].setErrors({'pattern': true});
}
}
<input name="booking_reference" type="text" [class.input-not-empty]="bookingRef.value"
class="glyph-input form-control floating-label-input" id="bookings_bookingReference"
value="" maxlength="14" aria-required="true" role="textbox" #bookingRef
formControlName="bookingReference" (focus)="resetMessageField()" (blur)="validatePnrAndTicketNumber()"/>
If you want a simple regex then it won't be accurate. https://www.freeformatter.com/java-regex-tester.html#ad-output offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.
ISO date format (yyyy-mm-dd):
^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.
^[0-9]{4}([- /.])(((0[13578]|(10|12))\1(0[1-9]|[1-2][0-9]|3[0-1]))|(02\1(0[1-9]|[1-2][0-9]))|((0[469]|11)\1(0[1-9]|[1-2][0-9]|30)))$
United States date format (mm/dd/yyyy)
^(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02/(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))/[0-9]{4}$
Hours and minutes, 24 hours format (HH:MM):
^(20|21|22|23|[01]\d|\d)((:[0-5]\d){1,2})$
Good luck
I had the same problem. When I run a php file, the web browser showed me the php code instead of execute it. I had tried many times: uninstall/reinstall the wampserver64, working around the PHP/Apache settings/modules, etc. After 2 days: I realised that when I tried to run the php file within the notepad++ by pressing the default combination "ctrl + alt + shift + R" for chrome. It was trying to execute my php file like: "file///C:/wamp64/www/bla/bla.." in my chrome's address bar. That was my problem. I made the changes according to page Configuring Notepad++ to run php on localhost?. My problem was solved. But after 2 days..
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
def remove_chars(line):
line7=line[7].translate(None,'abcd')
return line[:7]+[line7]+line[8:]
line= ['ad','da','sdf','asd',
'3424','342sfas','asdfaf','sdfa',
'afase']
print line[7]
line = remove_chars(line)
print line[7]
This is the autofilter macro you could base a function off of:
Selection.AutoFilter
ActiveSheet.Range("$A$1:$A$10").AutoFilter Field:=1, Criteria1:="=*-*", Operator:=xlAnd
Selection.AutoFilter
I use this autofilter function to delete matching rows:
Public Sub FindDelete(sCol As String, vSearch As Variant)
'Simple find and Delete
Dim lLastRow As Integer
Dim rng As Range
Dim rngDelete As Range
Range(sCol & 1).Select
[2:2].Insert
Range(sCol & 2) = "temp"
With ActiveSheet
.usedrange
lLastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
Set rng = Range(sCol & 2, Cells(lLastRow, sCol))
rng.AutoFilter Field:=1, Criteria1:=vSearch, Operator:=xlAnd
Set rngDelete = rng.SpecialCells(xlCellTypeVisible)
rng.AutoFilter
rngDelete.EntireRow.Delete
.usedrange
End With
End Sub
call it like:
call FindDelete "A", "=*-*"
It's saved me a lot of work. Good luck!
I had a similar problem going through a tutorial.
# git mv README README.markdown
fatal: bad source, source=README, destination=README.markdown
I included the filetype in the source file:
# git mv README.rdoc README.markdown
and it worked perfectly. Don't forget to commit the changes with i.e.:
# git commit -a -m "Improved the README"
Sometimes it is simple little things like that, that piss us off. LOL
In a similar situation like this where I had to write Test Case which is dependent on Environment Variable, I tried following:
I wasted a day using the above two approaches, but of no avail. Then Maven came to my rescue. We can set Environment Variables or System Properties through Maven POM file which I think best way to do Unit Testing for Maven based project. Below is the entry I made in POM file.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<PropertyName1>PropertyValue1</PropertyName1>
<PropertyName2>PropertyValue2</PropertyName2>
</systemPropertyVariables>
<environmentVariables>
<EnvironmentVariable1>EnvironmentVariableValue1</EnvironmentVariable1>
<EnvironmentVariable2>EnvironmentVariableValue2</EnvironmentVariable2>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
After this change, I ran Test Cases again and suddenly all worked as expected. For reader's information, I explored this approach in Maven 3.x, so I have no idea on Maven 2.x.
Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...
npm install --save koa-cors
...and use it in the code:
const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());
problem solved.
There are nothing call virtual class in C#.
For functions
You can decide with your requirement.
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
You can use it in a more compact way as:
var tifs = {1: 'Joe', 2: 'Jane'};
...
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }
</select>
)
And another slightly different flavour:
Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)
I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.
Save the file as getopt.sh
:
#!/bin/bash
function get_variable_name_for_option {
local OPT_DESC=${1}
local OPTION=${2}
local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")
if [[ "${VAR}" == "${1}" ]]; then
echo ""
else
echo ${VAR}
fi
}
function parse_options {
local OPT_DESC=${1}
local INPUT=$(get_input_for_getopts "${OPT_DESC}")
shift
while getopts ${INPUT} OPTION ${@};
do
[ ${OPTION} == "?" ] && usage
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
done
check_for_required "${OPT_DESC}"
}
function check_for_required {
local OPT_DESC=${1}
local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
while test -n "${REQUIRED}"; do
OPTION=${REQUIRED:0:1}
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
REQUIRED=${REQUIRED:1}
done
}
function get_input_for_getopts {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_optional {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_required {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}
function usage {
printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
exit 10
}
Then you can use it like this:
#!/bin/bash
#
# [ and ] defines optional arguments
#
# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}
echo ${USER}
echo ${START_DATE_TIME}
I recently needed to use a generic approach. I came across with this solution:
#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
# OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
# ~$ echo get_options ${OPT_DESC}
# a:b:c
# ~$
#
# Required options
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"
# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"
function usage {
IFS="|"
printf "%s" ${0}
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "-${i:0:1} $VARNAME"
done
for i in ${OPTIONAL_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "[-${i:0:1} $VARNAME]"
done
printf "\n"
unset IFS
exit
}
# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# OPTIONS=$(get_options ${OPT_DESC})
# echo "${OPTIONS}"
#
# Output:
# "h:f:PW"
function get_options {
echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}
# Auxiliary function that returns all variable names separated by '|'
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# VARNAMES=$(get_values ${OPT_DESC})
# echo "${VARNAMES}"
#
# Output:
# "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}
# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
# $1: The options description (SEE TOP)
# $2: The option which the variable name wants to be retrieved
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# H_VAR=$(get_variable_name ${OPT_DESC} "h")
# echo "${H_VAR}"
#
# Output:
# "H_VAR"
function get_variable_name {
VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
if [[ ${VAR} == ${1} ]]; then
echo ""
else
echo ${VAR}
fi
}
# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})
# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})
# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")
# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
[[ ${OPTION} == ":" ]] && usage
VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
[[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done
shift $(($OPTIND - 1))
# Checks for required options. Report an error and exits if
# required options are missing.
# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
[[ -v ${VARNAME} ]] || usage
done
unset IFS
# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
[[ -v ${VARNAME} ]] || usage
printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}
I didn't test this roughly, so I could have some bugs in there.
Simplest way,
Controller:
[HttpGet("empId={empId}&startDate={startDate}&endDate={endDate}")]
public IEnumerable<Validate> Get(int empId, string startDate, string endDate){}
Postman Request:
{router}/empId=1&startDate=2020-20-20&endDate=2020-20-20
Learning point: Request exact pattern will be accepted by the Controller.
Unless you have sudo permissions to change it or its in your own usergroup/account you will not be able to get into it.
Check out man chmod
in the terminal for more information about changing permissions of a directory.
You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)
EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).
See "URL Encoding (or: 'What are those "%20
" codes in URLs?')".
I have solved this creating a custom View:
public class FractionalSizeView extends View {
public FractionalSizeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FractionalSizeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width * 70 / 100, 0);
}
}
This is invisible strut I can use to align other views within RelativeLayout.
A service creation example of using backslashes with many double quotes.
C:\Windows\system32>sc.exe create teagent binpath= "\"C:\Program Files\Tripwire\TE\Agent\bin\wrapper.exe\" -s \"C:\Program Files\Tripwire\TE\Agent\bin\agent.conf\"" DisplayName= "Tripwire Enterprise Agent"
[SC] CreateService SUCCESS
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
If you have 2 NSString literals, you can also just do this:
NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";
That's also useful for joining #defines:
#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB
Enjoy.
There is no need for using NSAttributedString
. All you need is a simple label with the proper textColor
. Plus this simple solution will work with all versions of iOS, not just iOS 6.
But if you needlessly wish to use NSAttributedString
, you can do something like this:
UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
Similar to manix's answer but in one place. Middleware to force HTTPS
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ForceHttps
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!app()->environment('local')) {
// for Proxies
Request::setTrustedProxies([$request->getClientIp()],
Request::HEADER_X_FORWARDED_ALL);
if (!$request->isSecure()) {
return redirect()->secure($request->getRequestUri());
}
}
return $next($request);
}
}
Another way...
# translate long options to short
for arg
do
delim=""
case "$arg" in
--help) args="${args}-h ";;
--verbose) args="${args}-v ";;
--config) args="${args}-c ";;
# pass through anything else
*) [[ "${arg:0:1}" == "-" ]] || delim="\""
args="${args}${delim}${arg}${delim} ";;
esac
done
# reset the translated args
eval set -- $args
# now we can process with getopt
while getopts ":hvc:" opt; do
case $opt in
h) usage ;;
v) VERBOSE=true ;;
c) source $OPTARG ;;
\?) usage ;;
:)
echo "option -$OPTARG requires an argument"
usage
;;
esac
done
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
xlBook.Save();
xlBook.Close(true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
try this.. it worked for me... you should release that xl application object to stop the process.
Add just these two lines before the datetime property in your model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
and result will be :
Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:
For example a recursive class could be a binary tree (or any tree):
class tree():
def __init__(self):
'''Initialise the tree'''
self.Data = None
self.Count = 0
self.LeftSubtree = None
self.RightSubtree = None
def Insert(self, data):
'''Add an item of data to the tree'''
if self.Data == None:
self.Data = data
self.Count += 1
elif data < self.Data:
if self.LeftSubtree == None:
# tree is a recurive class definition
self.LeftSubtree = tree()
# Insert is a recursive function
self.LeftSubtree.Insert(data)
elif data == self.Data:
self.Count += 1
elif data > self.Data:
if self.RightSubtree == None:
self.RightSubtree = tree()
self.RightSubtree.Insert(data)
if __name__ == '__main__':
T = tree()
# The root node
T.Insert('b')
# Will be put into the left subtree
T.Insert('a')
# Will be put into the right subtree
T.Insert('c')
As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.
Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :
import sys
sys.getrecursionlimit()
and to set it :
import sys #(if you haven't already)
sys.setrecursionlimit()
edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how
To answer the WHY in your question:
Because the equality operator can only be applied to simple variable types, such as float
s, int
s, or char
s, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character strings character by character.
Solution for MAC. run the command
sudo gem update
then type your Mac password when prompted
MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed
.
MySQL suggests:
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem.
I found something almost working here https://stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-ja vascript
`function AnticipatedSyncFunction(){
var ret;
setTimeout(function(){
var startdate = new Date()
ret = "hello" + startdate;
},3000);
while(ret === undefined) {
require('deasync').runLoopOnce();
}
return ret;
}
var output = AnticipatedSyncFunction();
var startdate = new Date()
console.log(startdate)
console.log("output="+output);`
The unique problem is the date printed isn't correct but the process at least is sequential.
I know the answer for this question is posted a long back, but I wanted to share my answer for the same.
For finding the one’s complement of a number, first find its binary equivalent. Here, decimal number 2
is represented as 0000 0010
in binary form. Now taking its one’s complement by inverting (flipping all 1’s into 0’s and all 0’s into 1’s) all the digits of its binary representation, which will result in:
0000 0010 ? 1111 1101
This is the one’s complement of the decimal number 2. And since the first bit, i.e., the sign bit is 1 in the binary number, it means that the sign is negative for the number it stored. (here, the number referred to is not 2 but the one’s complement of 2).
Now, since the numbers are stored as 2’s complement (taking the one’s complement of a number plus one), so to display this binary number, 1111 1101
, into decimal, first we need to find its 2’s complement, which will be:
1111 1101 ? 0000 0010 + 1 ? 0000 0011
This is the 2’s complement. The decimal representation of the binary number, 0000 0011
, is 3
. And, since the sign bit was one as mentioned above, so the resulting answer is -3
.
Hint: If you read this procedure carefully, then you would have observed that the result for the one’s complement operator is actually, the number (operand - on which this operator is applied) plus one with a negative sign. You can try this with other numbers too.
Just an addition to other wonderful answers:
AND: The result of true and unknown is unknown, false and unknown is false,
while unknown and unknown is unknown.
OR: The result of true or unknown is true, false or unknown is unknown, while unknown or unknown is unknown.
NOT: The result of not unknown is unknown
If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine.
Here is one way of doing it:
<%
Dim message
message = "This is my message"
Response.Write("<script language=VBScript>MsgBox """ + message + """</script>")
%>
You can use on another class
public ArrayList<Integer> myNumbers = new Foo().myNumbers();
or
Foo myClass = new Foo();
public ArrayList<Integer> myNumbers = myclass.myNumbers();
If you want to redirect the output to a log file to look for errors or something. You can do something like this.
sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF
If you don't want to make it final, you can always just make it a global variable.
the best way it is create object with list of dynamic functions like:
const USER = 'user';
const userModule = {
[USER + 'Action'] : function () { ... },
[USER + 'OnClickHandler'] : function () { ... },
[USER + 'OnCreateHook'] : function () { ... },
}
You should install the mysql server which hosts in your localhost. Then install the workbench. Still if you are getting the error GOTO:
(In MAC:)
System preferences>Mysql(Will be listed at the bottom,else server is not installed in your machine).
Check server status and start the Mysql server.
Try connecting to localhost with default port number.
Compilation:
#built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Gradle files
.gradle/
build/
/*/build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Windows thumbnail db
Thumbs.db
# OSX files
.DS_Store
# Eclipse project files
.classpath
.project
# Android Studio
*.iml
.idea
#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
.gradle
build/
# Intellij project files
*.iml
*.ipr
*.iws
.idea/
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
I come across with same requirement where, I wants to show responsive image map which can resize with any screen size and important thing is, i want to highlight that coordinates.
So i tried many libraries which can resize coordinates according to screen size and event. And i got best solution(jquery.imagemapster.min.js) which works fine with almost all browsers. Also i have integrated it with Summer Plgin which create image map.
var resizeTime = 100;
var resizeDelay = 100;
$('img').mapster({
areas: [
{
key: 'tbl',
fillColor: 'ff0000',
staticState: true,
stroke: true
}
],
mapKey: 'state'
});
// Resize the map to fit within the boundaries provided
function resize(maxWidth, maxHeight) {
var image = $('img'),
imgWidth = image.width(),
imgHeight = image.height(),
newWidth = 0,
newHeight = 0;
if (imgWidth / maxWidth > imgHeight / maxHeight) {
newWidth = maxWidth;
} else {
newHeight = maxHeight;
}
image.mapster('resize', newWidth, newHeight, resizeTime);
}
function onWindowResize() {
var curWidth = $(window).width(),
curHeight = $(window).height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function () {
var newWidth = $(window).width(),
newHeight = $(window).height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
_x000D_
img[usemap] {
border: none;
height: auto;
max-width: 100%;
width: auto;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.imagemapster.min.js"></script>
<img src="https://discover.luxury/wp-content/uploads/2016/11/Cities-With-the-Most-Michelin-Star-Restaurants-1024x581.jpg" alt="" usemap="#map" />
<map name="map">
<area shape="poly" coords="777, 219, 707, 309, 750, 395, 847, 431, 916, 378, 923, 295, 870, 220" href="#" alt="poly" title="Polygon" data-maphilight='' state="tbl"/>
<area shape="circle" coords="548, 317, 72" href="#" alt="circle" title="Circle" data-maphilight='' state="tbl"/>
<area shape="rect" coords="182, 283, 398, 385" href="#" alt="rect" title="Rectangle" data-maphilight='' state="tbl"/>
</map>
_x000D_
Hope help it to someone.
In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.
import javafx.fxml.Initializable;
class MyController implements Initializable {
@FXML private TableView<MyModel> tableView;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.getItems().addAll(getDataFromSource());
}
}
Parameters:
location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized.
And the note of the docs why the simple way of using @FXML public void initialize()
works:
NOTE
This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.
import java.util.Arrays;
class Soft{
public static void main(String[] args){
int[] nums=range(9, 12);
System.out.println(Arrays.toString(nums));
}
static int[] range(int low, int high){
int[] a=new int[high-low];
for(int i=0,j=low;i<high-low;i++,j++){
a[i]=j;
}
return a;
}
}
My code is similar to Python`s range :)
DECODE(SUBSTR(STATUS,1,1),'a','Active','i','Inactive','t','Terminated','N/A')
When the html page is rendered, display a spinner immediately (while React loads), and hide it after React is ready.
Since the spinner is rendered in pure HTML/CSS (outside of the React domain), React shouldn't control the showing/hiding process directly, and the implementation should be transparent to React.
Since you render react into a DOM container - <div id="app"></div>
, you can add a spinner to that container, and when react will load and render, the spinner will disappear.
You can't add a DOM element (a div for example) inside the react root, since React will replace the contents of the container as soon as ReactDOM.render()
is called. Even if you render null
, the content would still be replaced by a comment - <!-- react-empty: 1 -->
. This means that if you want to display the loader while the main component mounts, data is loading, but nothing is actually rendered, a loader markup placed inside the container (<div id="app"><div class="loader"></div></div>
for example) would not work.
A workaround is to add the spinner class to the react container, and use the :empty
pseudo class. The spinner will be visible, as long as nothing is rendered into the container (comments don't count). As soon as react renders something other than comment, the loader will disappear.
Example 1
In the example you can see a component that renders null
until it's ready. The container is the loader as well - <div id="app" class="app"></div>
, and the loader's class will only work if it's :empty
(see comments in code):
class App extends React.Component {_x000D_
state = {_x000D_
loading: true_x000D_
};_x000D_
_x000D_
componentDidMount() {_x000D_
// this simulates an async action, after which the component will render the content_x000D_
demoAsyncCall().then(() => this.setState({ loading: false }));_x000D_
}_x000D_
_x000D_
render() {_x000D_
const { loading } = this.state;_x000D_
_x000D_
if(loading) { // if your component doesn't have to wait for an async action, remove this block _x000D_
return null; // render null when app is not ready_x000D_
}_x000D_
_x000D_
return (_x000D_
<div>I'm the app</div>_x000D_
); _x000D_
}_x000D_
}_x000D_
_x000D_
function demoAsyncCall() {_x000D_
return new Promise((resolve) => setTimeout(() => resolve(), 2500));_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<App />,_x000D_
document.getElementById('app')_x000D_
);
_x000D_
.loader:empty {_x000D_
position: absolute;_x000D_
top: calc(50% - 4em);_x000D_
left: calc(50% - 4em);_x000D_
width: 6em;_x000D_
height: 6em;_x000D_
border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
border-left: 1.1em solid #000000;_x000D_
border-radius: 50%;_x000D_
animation: load8 1.1s infinite linear;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
0% {_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app" class="loader"></div> <!-- add class loader to container -->
_x000D_
Example 2
A variation on using the :empty
pseudo class to show/hide a selector, is setting the spinner as a sibling element to the app container, and showing it as long as the container is empty using the adjacent sibling combinator (+
):
class App extends React.Component {_x000D_
state = {_x000D_
loading: true_x000D_
};_x000D_
_x000D_
componentDidMount() {_x000D_
// this simulates an async action, after which the component will render the content_x000D_
demoAsyncCall().then(() => this.setState({ loading: false }));_x000D_
}_x000D_
_x000D_
render() {_x000D_
const { loading } = this.state;_x000D_
_x000D_
if(loading) { // if your component doesn't have to wait for async data, remove this block _x000D_
return null; // render null when app is not ready_x000D_
}_x000D_
_x000D_
return (_x000D_
<div>I'm the app</div>_x000D_
); _x000D_
}_x000D_
}_x000D_
_x000D_
function demoAsyncCall() {_x000D_
return new Promise((resolve) => setTimeout(() => resolve(), 2500));_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<App />,_x000D_
document.getElementById('app')_x000D_
);
_x000D_
#app:not(:empty) + .sk-cube-grid {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.sk-cube-grid {_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
margin: 100px auto;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube {_x000D_
width: 33%;_x000D_
height: 33%;_x000D_
background-color: #333;_x000D_
float: left;_x000D_
animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube1 {_x000D_
animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube2 {_x000D_
animation-delay: 0.3s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube3 {_x000D_
animation-delay: 0.4s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube4 {_x000D_
animation-delay: 0.1s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube5 {_x000D_
animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube6 {_x000D_
animation-delay: 0.3s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube7 {_x000D_
animation-delay: 0s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube8 {_x000D_
animation-delay: 0.1s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube9 {_x000D_
animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
@keyframes sk-cubeGridScaleDelay {_x000D_
0%,_x000D_
70%,_x000D_
100% {_x000D_
transform: scale3D(1, 1, 1);_x000D_
}_x000D_
35% {_x000D_
transform: scale3D(0, 0, 1);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
<!-- add class loader to container -->_x000D_
_x000D_
<div class="sk-cube-grid">_x000D_
<div class="sk-cube sk-cube1"></div>_x000D_
<div class="sk-cube sk-cube2"></div>_x000D_
<div class="sk-cube sk-cube3"></div>_x000D_
<div class="sk-cube sk-cube4"></div>_x000D_
<div class="sk-cube sk-cube5"></div>_x000D_
<div class="sk-cube sk-cube6"></div>_x000D_
<div class="sk-cube sk-cube7"></div>_x000D_
<div class="sk-cube sk-cube8"></div>_x000D_
<div class="sk-cube sk-cube9"></div>_x000D_
</div>
_x000D_
To have a more fine grained control over the spinners display state, create two functions showSpinner
and hideSpinner
, and pass them to the root container via props. The functions can manipulate the DOM, or do whatever needed to control the spinner. In this way, React is not aware of the "outside world", nor needs to control the DOM directly. You can easily replace the functions for testing, or if you need to change the logic, and you can pass them to other components in the React tree.
Example 1
const loader = document.querySelector('.loader');_x000D_
_x000D_
// if you want to show the loader when React loads data again_x000D_
const showLoader = () => loader.classList.remove('loader--hide');_x000D_
_x000D_
const hideLoader = () => loader.classList.add('loader--hide');_x000D_
_x000D_
class App extends React.Component {_x000D_
componentDidMount() {_x000D_
this.props.hideLoader();_x000D_
}_x000D_
_x000D_
render() { _x000D_
return (_x000D_
<div>I'm the app</div>_x000D_
); _x000D_
}_x000D_
}_x000D_
_x000D_
// the setTimeout simulates the time it takes react to load, and is not part of the solution_x000D_
setTimeout(() => _x000D_
// the show/hide functions are passed as props_x000D_
ReactDOM.render(_x000D_
<App_x000D_
hideLoader={hideLoader}_x000D_
showLoader={showLoader} _x000D_
/>,_x000D_
document.getElementById('app')_x000D_
)_x000D_
, 1000);
_x000D_
.loader {_x000D_
position: absolute;_x000D_
top: calc(50% - 4em);_x000D_
left: calc(50% - 4em);_x000D_
width: 6em;_x000D_
height: 6em;_x000D_
border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
border-left: 1.1em solid #000000;_x000D_
border-radius: 50%;_x000D_
animation: load8 1.1s infinite linear;_x000D_
transition: opacity 0.3s;_x000D_
}_x000D_
_x000D_
.loader--hide {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
0% {_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
_x000D_
<div class="loader"></div>
_x000D_
Example 2 - hooks
This example uses the useEffect
hook to hide the spinner after the component mounts.
const { useEffect } = React;_x000D_
_x000D_
const loader = document.querySelector('.loader');_x000D_
_x000D_
// if you want to show the loader when React loads data again_x000D_
const showLoader = () => loader.classList.remove('loader--hide');_x000D_
_x000D_
const hideLoader = () => loader.classList.add('loader--hide');_x000D_
_x000D_
const App = ({ hideLoader }) => {_x000D_
useEffect(hideLoader, []);_x000D_
_x000D_
return (_x000D_
<div>I'm the app</div>_x000D_
); _x000D_
}_x000D_
_x000D_
// the setTimeout simulates the time it takes react to load, and is not part of the solution_x000D_
setTimeout(() => _x000D_
// the show/hide functions are passed as props_x000D_
ReactDOM.render(_x000D_
<App_x000D_
hideLoader={hideLoader}_x000D_
showLoader={showLoader} _x000D_
/>,_x000D_
document.getElementById('app')_x000D_
)_x000D_
, 1000);
_x000D_
.loader {_x000D_
position: absolute;_x000D_
top: calc(50% - 4em);_x000D_
left: calc(50% - 4em);_x000D_
width: 6em;_x000D_
height: 6em;_x000D_
border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
border-left: 1.1em solid #000000;_x000D_
border-radius: 50%;_x000D_
animation: load8 1.1s infinite linear;_x000D_
transition: opacity 0.3s;_x000D_
}_x000D_
_x000D_
.loader--hide {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
0% {_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
_x000D_
<div class="loader"></div>
_x000D_
Under browsers supporting js 1.8:
[i for(i in obj)]
funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:
<h3>Your Text</h3><div class="border-shadow"></div>
and the css:
.shadow {
width:100%;
height:1px; // = "border height (without the shadow)!"
background:#000; // = "border color!"
-webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
-moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
}
Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow
unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.
function unlinkr($dir, $pattern = "*") {
// find all files and folders matching pattern
$files = glob($dir . "/$pattern");
//interate thorugh the files and folders
foreach($files as $file){
//if it is a directory then re-call unlinkr function to delete files inside this directory
if (is_dir($file) and !in_array($file, array('..', '.'))) {
echo "<p>opening directory $file </p>";
unlinkr($file, $pattern);
//remove the directory itself
echo "<p> deleting directory $file </p>";
rmdir($file);
} else if(is_file($file) and ($file != __FILE__)) {
// make sure you don't delete the current script
echo "<p>deleting file $file </p>";
unlink($file);
}
}
}
if you want to delete all files and folders where you place this script then call it as following
//get current working directory
$dir = getcwd();
unlinkr($dir);
if you want to just delete just php files then call it as following
unlinkr($dir, "*.php");
you can use any other path to delete the files as well
unlinkr("/home/user/temp");
This will delete all files in home/user/temp directory.
I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:
class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}
This way variables penguin
and lion
infer concrete type Penguin
or Lion
even in the TypeScript intellisense.
const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.
const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.
In case you are using Silex add the Symfony Asset as a dependency:
composer require symfony/asset
Then you may register Asset Service Provider:
$app->register(new Silex\Provider\AssetServiceProvider(), array(
'assets.version' => 'v1',
'assets.version_format' => '%s?version=%s',
'assets.named_packages' => array(
'css' => array(
'version' => 'css2',
'base_path' => __DIR__.'/../public_html/resources/css'
),
'images' => array(
'base_urls' => array(
'https://img.example.com'
)
),
),
));
Then in your Twig template file in head section:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% block head %}
<link rel="stylesheet" href="{{ asset('style.css') }}" />
{% endblock %}
</head>
<body>
</body>
</html>
When doing git rebase -i
there is this interesting bit in the doc:
If you want to fold two or more commits into one, replace the command
"pick"
for the second and subsequent commits with"squash"
or"fixup"
. If the commits had different authors, the folded commit will be attributed to the author of the first commit. The suggested commit message for the folded commit is the concatenation of the commit messages of the first commit and of those with the"squash"
command, but omits the commit messages of commits with the"fixup"
command.
A-B-C-D-E-F
,B
and D
(= 2 commits),then you can do:
git config user.name "Correct new name"
git config user.email "[email protected]"
git commit --allow-empty -m "empty"
git rebase -i B^
B^
selects the parent of B
.pick
to squash
for those.Example of what git rebase -i B^
will give you:
pick sha-commit-B some message
pick sha-commit-C some message
pick sha-commit-D some message
pick sha-commit-E some message
pick sha-commit-F some message
# pick sha-commit-empty1 empty
# pick sha-commit-empty2 empty
change that to:
# change commit B's author
pick sha-commit-empty1 empty
squash sha-commit-B some message
# leave commit C alone
pick sha-commit-C some message
# change commit D's author
pick sha-commit-empty2 empty
squash sha-commit-D some message
# leave commit E-F alone
pick sha-commit-E some message
pick sha-commit-F some message
It will prompt you to edit the messages:
# This is a combination of 2 commits.
# The first commit's message is:
empty
# This is the 2nd commit message:
...some useful commit message there...
and you can just remove the first few lines.
For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:
class DropTables < ActiveRecord::Migration
def up
drop_table :table_you_dont_want
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do
select field from table where field REGEXP '^-?[0-9]+$';
this is reasonably fast. If your field is numeric, just test for
ceil(field) = field
instead.
The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
If you're trying to import something from a sub-folder e.g. ./feature/email.py
, the code will look like importlib.import_module("feature.email")
You can't import anything if there is no __init__.py
in the folder with file you are trying to import
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:
The lingo in excel is different, you don't "declare variables", you "name" cells or arrays.
A good overview of how you do that is below: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010342417.aspx
In ruby, the constant __FILE__
will always give you the path of the script you're running.
On Linux, /usr/bin/env
is your friend:
#! /usr/bin/env ruby
# Extension of this script does not matter as long
# as it is executable (chmod +x)
puts File.expand_path(__FILE__)
On Windows it depends whether or not .rb files are associated with ruby. If they are:
# This script filename must end with .rb
puts File.expand_path(__FILE__)
If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:
my_script.cmd:
@ruby %~dp0\my_script.rb
my_script.rb:
puts File.expand_path(__FILE__)
Using the auxww
flags, you will see the full path to output in both your terminal window and from shell scripts.
darragh@darraghserver ~ $uname -a
SunOS darraghserver 5.10 Generic_142901-13 i86pc i386 i86pc
darragh@darraghserver ~ $which ps
/usr/bin/ps<br>
darragh@darraghserver ~ $/usr/ucb/ps auxww | grep ps
darragh 13680 0.0 0.0 3872 3152 pts/1 O 14:39:32 0:00 /usr/ucb/ps -auxww
darragh 13681 0.0 0.0 1420 852 pts/1 S 14:39:32 0:00 grep ps
ps aux
lists all processes executed by all users. See man ps
for details. The ww
flag sets unlimited width.
-w Wide output. Use this option twice for unlimited width.
w Wide output. Use this option twice for unlimited width.
I found the answer on the following blog:
http://www.snowfrog.net/2010/06/10/solaris-ps-output-truncated-at-80-columns/
This works for MVC 5:
<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
Link text
</a>
There's probably a really neat RegExp, but I'm noob in that area, so instead...
String s = "test string (67)";
s = s.substring(s.indexOf("(") + 1);
s = s.substring(0, s.indexOf(")"));
System.out.println(s);
There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.
And then you can copy for example the file "test.txt" from a remote host to the local host
scp [email protected]:test.txt /local/dir
@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.
In UNIX, absolute paths must start with '/'.
If the assembly is different from the namespace in which your class is contained, you have to specfiy it explicitly.
ex:-
xmlns:Local="clr-namespace:MusicPlayer.Controls;assembly=MusicPlayer"
This is commonly caused by running out of file descriptors.
There is the systems total file descriptor limit, what do you get from the command:
sysctl fs.file-nr
This returns counts of file descriptors:
<in_use> <unused_but_allocated> <maximum>
To find out what a users file descriptor limit is run the commands:
sudo su - <username>
ulimit -Hn
To find out how many file descriptors are in use by a user run the command:
sudo lsof -u <username> 2>/dev/null | wc -l
So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.
fs.file-max = 204708
try:
var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
alert(newJ.TeamList[0].teamname);
Use Assembly.GetTypes
. For example:
Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
Console.WriteLine(type.FullName);
}
I found this VB script:
Works like a charm. Configured as a function with a very simple function call:
SaveWebBinary "http://server/file1.ext1", "C:/file2.ext2"
Originally from: http://www.ericphelps.com/scripting/samples/BinaryDownload/index.htm
Here is the full code for redundancy:
Function SaveWebBinary(strUrl, strFile) 'As Boolean
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Const ForWriting = 2
Dim web, varByteArray, strData, strBuffer, lngCounter, ado
On Error Resume Next
'Download the file with any available object
Err.Clear
Set web = Nothing
Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
If web Is Nothing Then Set web = CreateObject("WinHttp.WinHttpRequest")
If web Is Nothing Then Set web = CreateObject("MSXML2.ServerXMLHTTP")
If web Is Nothing Then Set web = CreateObject("Microsoft.XMLHTTP")
web.Open "GET", strURL, False
web.Send
If Err.Number <> 0 Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
If web.Status <> "200" Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
varByteArray = web.ResponseBody
Set web = Nothing
'Now save the file with any available method
On Error Resume Next
Set ado = Nothing
Set ado = CreateObject("ADODB.Stream")
If ado Is Nothing Then
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(strFile, ForWriting, True)
strData = ""
strBuffer = ""
For lngCounter = 0 to UBound(varByteArray)
ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
Next
ts.Close
Else
ado.Type = adTypeBinary
ado.Open
ado.Write varByteArray
ado.SaveToFile strFile, adSaveCreateOverWrite
ado.Close
End If
SaveWebBinary = True
End Function
From the documentation I found this
JObject o = new JObject(
new JProperty("Name", "John Smith"),
new JProperty("BirthDate", new DateTime(1983, 3, 20))
);
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
Console.WriteLine(p.Name);
The class definition for Person
should be compatible to the following:
class Person {
public string Name { get; internal set; }
public DateTime BirthDate { get; internal set; }
}
Edit
If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I have been searching for this for ages on my CM 11 android phone, running kitkat.
Well.. finally I found it. It's hidden in a totally unintuitive location:
Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.
Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).
I know it has been more than 1 decade since this was was asked, but I just put my thinking on this for the n-th time in my programmer life, and found a possible solution that I don't know if I entirely like yet. I have not seen this methodology documented before, so I will name it the "private/public dollar pattern" or _$ / $ pattern.
var ownFunctionResult = this.$("functionName"[, arg1[, arg2 ...]]);
var ownFieldValue = this._$("fieldName"[, newValue]);
var objectFunctionResult = objectX.$("functionName"[, arg1[, arg2 ...]]);
//Throws an exception. objectX._$ is not defined
var objectFieldValue = objectX._$("fieldName"[, newValue]);
The concept uses a ClassDefinition function that returns a Constructor function that returns an Interface object. The interface's only method is $
which receives a name
argument to invoke the corresponding function in the constructor object, any additional arguments passed after name
are passed in the invocation.
The globally-defined helper function ClassValues
stores all fields in an object as needed. It defines the _$
function to access them by name
. This follows a short get/set pattern so if value
is passed, it will be used as the new variable value.
var ClassValues = function (values) {
return {
_$: function _$(name, value) {
if (arguments.length > 1) {
values[name] = value;
}
return values[name];
}
};
};
The globally defined function Interface
takes an object and a Values
object to return an _interface
with one single function $
that examines obj
to find a function named after the parameter name
and invokes it with values
as the scoped object. The additional arguments passed to $
will be passed on the function invocation.
var Interface = function (obj, values, className) {
var _interface = {
$: function $(name) {
if (typeof(obj[name]) === "function") {
return obj[name].apply(values, Array.prototype.splice.call(arguments, 1));
}
throw className + "." + name + " is not a function.";
}
};
//Give values access to the interface.
values.$ = _interface.$;
return _interface;
};
In the sample below, ClassX
is assigned to the result of ClassDefinition
, which is the Constructor
function. Constructor
may receive any number of arguments. Interface
is what external code gets after calling the constructor.
var ClassX = (function ClassDefinition () {
var Constructor = function Constructor (valA) {
return Interface(this, ClassValues({ valA: valA }), "ClassX");
};
Constructor.prototype.getValA = function getValA() {
//private value access pattern to get current value.
return this._$("valA");
};
Constructor.prototype.setValA = function setValA(valA) {
//private value access pattern to set new value.
this._$("valA", valA);
};
Constructor.prototype.isValAValid = function isValAValid(validMessage, invalidMessage) {
//interface access pattern to call object function.
var valA = this.$("getValA");
//timesAccessed was not defined in constructor but can be added later...
var timesAccessed = this._$("timesAccessed");
if (timesAccessed) {
timesAccessed = timesAccessed + 1;
} else {
timesAccessed = 1;
}
this._$("timesAccessed", timesAccessed);
if (valA) {
return "valA is " + validMessage + ".";
}
return "valA is " + invalidMessage + ".";
};
return Constructor;
}());
There is no point in having non-prototyped functions in Constructor
, although you could define them in the constructor function body. All functions are called with the public dollar pattern this.$("functionName"[, param1[, param2 ...]])
. The private values are accessed with the private dollar pattern this._$("valueName"[, replacingValue]);
. As Interface
does not have a definition for _$
, the values cannot be accessed by external objects. Since each prototyped function body's this
is set to the values
object in function $
, you will get exceptions if you call Constructor sibling functions directly; the _$ / $ pattern needs to be followed in prototyped function bodies too. Below sample usage.
var classX1 = new ClassX();
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
console.log("classX1.valA: " + classX1.$("getValA"));
classX1.$("setValA", "v1");
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
var classX2 = new ClassX("v2");
console.log("classX1.valA: " + classX1.$("getValA"));
console.log("classX2.valA: " + classX2.$("getValA"));
//This will throw an exception
//classX1._$("valA");
And the console output.
classX1.valA is invalid.
classX1.valA: undefined
classX1.valA is valid.
classX1.valA: v1
classX2.valA: v2
The _$ / $ pattern allows full privacy of values in fully-prototyped classes. I don't know if I will ever use this, nor if it has flaws, but hey, it was a good puzzle!
Assuming a Windows installation, do please refer to this:
http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php
- Uninstall all Oracle components using the Oracle Universal Installer (OUI).
- Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
- Delete any references to Oracle services left behind in the following part of the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora*
It should be pretty obvious which ones relate to Oracle.- Reboot your machine.
- Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
- Delete the "C:\Program Files\Oracle" directory.
- Empty the contents of your "C:\temp" directory.
- Empty your recycle bin.
Calling additional attention to some great comments that were left here:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE
key from the registry.%ORACLE_HOME%
.%PATH%
.This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.
Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.
(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)
Per Jquery docs
The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.
In order to retrieve the value store in the text box with id txtEmail, you can use
$("#txtEmail").val()
The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).
You can also use meta refresh tag. It also requires DOM to be loaded.
This is a problem with your remote. When you do git push origin master
, origin
is the remote and master
is the branch you're pushing.
When you do this:
git remote
I bet the list does not include origin
. To re-add the origin remote:
git remote add origin [email protected]:your_github_username/your_github_app.git
Or, if it exists but is formatted incorrectly:
git remote rm origin
git remote add origin [email protected]:your_github_username/your_github_app.git
style="?android:attr/listSeparatorTextViewStyle
Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())
To fix the blank PDF issue in post request to get stream data like PDF, we need to add response type as 'arraybuffer' or 'blob' in request
$.ajax({
url: '<URL>',
type: "POST",
dataType: 'arraybuffer',
success: function(data) {
let blob = new Blob([data], {type: 'arraybuffer'});
let link = document.createElement('a');
let objectURL = window.URL.createObjectURL(blob);
link.href = objectURL;
link.target = '_self';
link.download = "fileName.pdf";
(document.body || document.documentElement).appendChild(link);
link.click();
setTimeout(()=>{
window.URL.revokeObjectURL(objectURL);
link.remove();
}, 100);
}
});
import time
from datetime import datetime
t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())
result: 3.0
In one line of 6 words:
git checkout --orphan new_root_branch && git commit
This selector $("ul [data-slide='" + current +"']");
will work for following structure:
<ul><li data-slide="item"></li></ul>
While this $("ul[data-slide='" + current +"']");
will work for:
<ul data-slide="item"><li></li></ul>
# Method 1
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
There are many more methods but these two are most common. Hope this helped!
If you use custom Makefiles, you can double click on the .includes file and add it there.
In case it's useful to anyone else, working on a Code-First approach using attribute mappings, I wanted something that just left me needing to bind an entity in the object model. So thanks to Carnotaurus' answer, I extended it as per their own suggestion and made a couple of tweaks.
This relies therefore on this solution comprising TWO parts, both of which are SQL Scalar-Valued functions:
- An 'Initial Caps' function (taken from: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8a58dbe1-7a4b-4287-afdc-bfecb4e69b23/similar-to-initcap-in-sql-server-tsql and slightly modified to meet my needs)
ALTER function [dbo].[ProperCase] (@cStringToProper varchar(8000))
returns varchar(8000)
as
begin
declare @Position int
select @cStringToProper = stuff(lower(@cStringToProper) , 1 , 1 , upper(left(@cStringToProper , 1)))
, @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
while @Position > 0
select @cStringToProper = stuff(@cStringToProper , @Position , 2 , upper(substring(@cStringToProper , @Position , 2)))
, @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
select @cStringToProper = replace(@cStringToProper, '_','')
return @cStringToProper
end
The output function itself, which extends Carnotaurus' solution by:
- Correctly outputting newline characters
- Performing some basic tabulation
- Writing out an appropriate a [Table] mapping (as suggested)
- Writing out an appropriate [Column] mapping, including the type name (as suggested)
- Allowing the Entity name to differ from the name of the table
- Fixes the limitation of the Print @Result truncating when you have tables with a large number of columns
CREATE FUNCTION [dbo].[GetEntityObject] (@NameSpace NVARCHAR(MAX), @TableName NVARCHAR(MAX), @EntityName NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN
DECLARE @result NVARCHAR(MAX)
SET @result = @result + 'using System;' + CHAR(13) + CHAR(13)
IF (@NameSpace IS NOT NULL) BEGIN
SET @result = @result + 'namespace ' + @NameSpace + CHAR(13) + '{' + CHAR(13) END
SET @result = @result + '[Table(name: ' + CHAR(34) + @TableName + CHAR(34) + ')]' + CHAR(13) SET @result = @result + 'public class ' + @EntityName + CHAR(13) + '{' + CHAR(13)
SET @result = @result + '#region Instance Properties' + CHAR(13)
SELECT @result = @result + CHAR(13) + '[Column(name: ' + CHAR(34) + OriginalColumnName + CHAR(34) + ', TypeName = ' + CHAR(34) + DataType
+ CHAR(34) + ')]' + CHAR(13)
+ 'public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13) FROM (
SELECT dbo.ProperCase (c.COLUMN_NAME) AS ColumnName
, CASE c.DATA_TYPE
WHEN 'bigint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
WHEN 'binary' THEN 'Byte[]'
WHEN 'bit' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END
WHEN 'char' THEN 'String'
WHEN 'date' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime2' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetimeoffset' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END
WHEN 'decimal' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'float' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Single?' ELSE 'Single' END
WHEN 'image' THEN 'Byte[]'
WHEN 'int' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
WHEN 'money' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nchar' THEN 'String'
WHEN 'ntext' THEN 'String'
WHEN 'numeric' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nvarchar' THEN 'String'
WHEN 'real' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Double?' ELSE 'Double' END
WHEN 'smalldatetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'smallint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END
WHEN 'smallmoney' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'text' THEN 'String'
WHEN 'time' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END
WHEN 'timestamp' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'tinyint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END
WHEN 'uniqueidentifier' THEN 'Guid'
WHEN 'varbinary' THEN 'Byte[]'
WHEN 'varchar' THEN 'String'
ELSE 'Object'
END AS ColumnType
, c.ORDINAL_POSITION , c.COLUMN_NAME as OriginalColumnName ,c.DATA_TYPE as DataType
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME = @TableName) t ORDER BY t.ORDINAL_POSITION
SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)
SET @result = @result + '}' + CHAR(13)
IF (@TableName IS NOT NULL) BEGIN
SET @result = @result + CHAR(13) + '}' END
return @result END
Usage from within MS SQL Management Studio:
SELECT dbo.GetEntityObject('MyNameSpace', 'MyTableName', 'MyEntityName')
will result in a column value you can copy and paste into Visual Studio.
If it helps anyone, then great!
a {background-color:transparent !important;}
Tested Eli Grey's universal solution, only worked after I simplified the code to
'use strict';
(() => {
const modified_inputs = new Set();
const defaultValue = 'defaultValue';
// store default values
addEventListener('beforeinput', evt => {
const target = evt.target;
if (!(defaultValue in target.dataset)) {
target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener('input', evt => {
const target = evt.target;
let original = target.dataset[defaultValue];
let current = ('' + (target.value || target.textContent)).trim();
if (original !== current) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
});
addEventListener(
'saved',
function(e) {
modified_inputs.clear()
},
false
);
addEventListener('beforeunload', evt => {
if (modified_inputs.size) {
const unsaved_changes_warning = 'Changes you made may not be saved.';
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
})();
The modifications to his is deleted the usage of target[defaultValue]
and only use target.dataset[defaultValue]
to store the real default value.
And I added a 'saved' event listener where the 'saved' event will be triggered by yourself on your saving action succeeded.
But this 'universal' solution only works in browsers, not works in app's webview, for example, wechat browsers.
To make it work in wechat browsers(partially) also, another improvements again:
'use strict';
(() => {
const modified_inputs = new Set();
const defaultValue = 'defaultValue';
// store default values
addEventListener('beforeinput', evt => {
const target = evt.target;
if (!(defaultValue in target.dataset)) {
target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener('input', evt => {
const target = evt.target;
let original = target.dataset[defaultValue];
let current = ('' + (target.value || target.textContent)).trim();
if (original !== current) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
if(modified_inputs.size){
const event = new Event('needSave')
window.dispatchEvent(event);
}
});
addEventListener(
'saved',
function(e) {
modified_inputs.clear()
},
false
);
addEventListener('beforeunload', evt => {
if (modified_inputs.size) {
const unsaved_changes_warning = 'Changes you made may not be saved.';
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
const ua = navigator.userAgent.toLowerCase();
if(/MicroMessenger/i.test(ua)) {
let pushed = false
addEventListener('needSave', evt => {
if(!pushed) {
pushHistory();
window.addEventListener("popstate", function(e) {
if(modified_inputs.size) {
var cfi = confirm('???????????' + JSON.stringify(e));
if (cfi) {
modified_inputs.clear()
history.go(-1)
}else{
e.preventDefault();
e.stopPropagation();
}
}
}, false);
}
pushed = true
});
}
function pushHistory() {
var state = {
title: document.title,
url: "#flag"
};
window.history.pushState(state, document.title, "#flag");
}
})();
Anderscc has got it correct. Thanks. It worked for me but not 100%.
I had to set
$mail->SMTPDebug = 0;
Setting it to 1, can cause errors especially if you are passing some data as json to next page. Example - Performing verification if mail is sent, using json to pass data through ajax.
I had to lower my gmail account security settings to get rid of errors: " SMTP connect() failed " and " SMTP ERROR: Password command failed "
Solution: This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).
Links that fix the problem (you must be logged into google account):
view recent attempts to use the account and accept suspicious access.
link to disable the feature of blocking suspicious apps/technologies:
Note: You can go to the following stackoverflow answer link for more detailed reference.
From the Active Record docs:
$this->db->where_in();
Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
Worked here too:
Sub test544()
Dim chromePath As String
chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromePath & " -url http:google.ca")
End Sub
Kotlin Solution :
private fun locationEnabled() : Boolean {
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
/** length should be less than 4 (for int) **/
public long byteToInt(byte[] bytes, int length) {
int val = 0;
if(length>4) throw new RuntimeException("Too big to fit in int");
for (int i = 0; i < length; i++) {
val=val<<8;
val=val|(bytes[i] & 0xFF);
}
return val;
}
If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.
Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.
First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.
Background: All depends on your Office (Runtimes Engines) installation.
If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.
If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.
To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
If it returns nothing, then they match:
cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm
use Date function directly. Hope it works
You can use boost
#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );
The NetBeans IDE checks for syntax errors, unusued variables and such. It's not automated, but works fine for small or medium projects.
This should help:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Very good link: Validate decimal numbers in JavaScript - IsNumeric()
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
I found the best solution after many attempts for this problem.
youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}
You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.
In my case I was trying to run postgres through docker. Initially I was running as :
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password POSTGRES_USER=test_user POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres
I was missing -e after each environment variable. Changing the above command to the one below worked
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password -e POSTGRES_USER=test_user -e POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres
There's another nice solution which you can use in your layout xml files directly and does not require to use setTypeface
.
It is Joan Zapata's Iconify. You can read here what's new in Iconify v2. It includes 9 different font libraries which you can simply use by adding dependencies to your build.gradle file.
In the layout xml files it's possible to choose between these widgets:
com.joanzapata.iconify.widget.IconTextview
com.joanzapata.iconify.widget.IconButton
com.joanzapata.iconify.widget.IconToggleButton
I managed to solve this issue without the need to change any markup with the following piece of jQuery. I had a similar problem where I wanted a tooltip on a button that was already using data-toggle for a modal. All you will need to do here is add the title to the button.
$('[data-toggle="modal"][title]').tooltip();
Find the latest version of chromedriver
here.
Once downloaded, unzip it at the root of your Python installation, e.g., C:/Program Files/Python-3.5
, and that's it.
You don't even need to specify the path anywhere and/or add chromedriver
to your path or the like.
I just did it on a clean Python installation and that works.
The No input file specified is a message you are presented with because of the implementation of PHP on your server, which in this case indicates a CGI implementation (can be verified with phpinfo()
).
Now, to properly explain this, you need to have some basic understanding on how your system works with URL's. Based on your .htaccess file, it seems that your CMS expects the URL to passed along as a PATH_INFO
variable. CGI and FastCGI implementations do not have PATH_INFO
available, so when trying to pass the URI along, PHP fails with that message.
We need to find an alternative.
One option is to try and fix this. Looking into the documentation for core php.ini directives you can see that you can change the workings for your implementation. Although, GoDaddy probably won't allow you to change PHP settings on a shared enviroment.
We need to find an alternative to modifying PHP settings
Looking into system/uri.php
on line 40, you will see that the CMS attempts two types of URI detection - the first being PATH_INFO
, which we just learned won't work - the other being the REQUEST_URI
.
This should basically, be enough - but the parsing of the URI passed, will cause you more trouble, as the URI, which you could pass to REQUEST_URI
variable, forces parse_url()
to only return the URL path - which basically puts you back to zero.
Now, there's actually only one possibilty left - and that's changing the core of the CMS. The URI detection part is insufficient.
Add QUERY_STRING
to the array on line 40 as the first element in system/uri.php
and change your .htaccess to look like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
This will pass the URI you request to index.php
as QUERY_STRING
and have the URI detection to find it.
This, on the other hand, makes it impossible to update the CMS without changing core files till this have been fixed. That sucks...
Need a better option?
Find a better CMS.
There are other ways of tracking what tab you're on; perhaps setting a cookie, or a value in a hidden field, etc etc.
I would say that if you don't want the page jumping on load, you would be better off using one of these other options rather than the hash, because the main reason for using the hash in preference to them is to allow exactly what you're wanting to block.
Another point - the page won't jump if your hash links don't match the names of the tags in the document, so perhaps if you want to keep using the hash you could manipulate the content so that the tags are named differently. If you use a consistent prefix, you will still be able to use Javascript to jump between then.
Hope that helps.
Change this line:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
You also might notice a little lag because 0deg and 360deg are the same spot, so it is going from spot 1 in a circle back to spot 1. It is really insignificant, but to fix it, all you have to do is change 360deg to 359deg
my jsfiddle illustrates your animation:
#myImg {
-webkit-animation: rotation 2s infinite linear;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
Also what might be more resemblant of the apple loading icon would be an animation that transitions the opacity/color of the stripes of gray instead of rotating the icon.
decodeURIComponent(mystring);
you can get passed parameters by using this bit of code:
//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Or this one-liner to get the parameters:
location.search.split("your_parameter=")[1]
Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:
function sql_debug($sql_string, array $params = null) {
if (!empty($params)) {
$indexed = $params == array_values($params);
foreach($params as $k=>$v) {
if (is_object($v)) {
if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
else continue;
}
elseif (is_string($v)) $v="'$v'";
elseif ($v === null) $v='NULL';
elseif (is_array($v)) $v = implode(',', $v);
if ($indexed) {
$sql_string = preg_replace('/\?/', $v, $sql_string, 1);
}
else {
if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
$sql_string = str_replace($k,$v,$sql_string);
}
}
}
return $sql_string;
}
If you are having problems with untracked files, this 3-line script will help you.
git rm -r --cached .
git add -A
git commit -am 'fix'
Then just git push
If you are presenting a ViewController modally, and want to go back to the root ViewController, take care to dismiss this modally presented ViewController before you go back to the root ViewController otherwise this ViewController will not be removed from Memory and cause Memory leaks.
I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(0, 2)
host.set_ylim(0, 2)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.legend()
plt.draw()
plt.show()
Look at my plugin for developing swing application. It is as easy as that of netbeans': http://code.google.com/p/visualswing4eclipse/
Just create a new branch:
git checkout -b newBranch
And if you do git status
you'll see that the state of the code hasn't changed and you can commit it to the new branch.
IntelliJ has no option to click on a file and choose "Add to .gitignore" like Eclipse has.
The quickest way to add a file or folder to .gitignore without typos is:
Additional info: There is a .ignore plugin available for IntelliJ which adds a "Add to .gitignore" item to the popup menu when you right-click a file. It works like a charm.
Read from excel, modify and write back
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
public string Export(DataTable dt, bool headers = false)
{
var wb = _xl.Workbooks.Add();
var sheet = (Excel.Worksheet)wb.ActiveSheet;
//process columns
for (int i = 0; i < dt.Columns.Count; i++)
{
var col = dt.Columns[i];
//added columns to the top of sheet
var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
currentCell.Value = col.ToString();
currentCell.Font.Bold = true;
//process rows
for (int j = 0; j < dt.Rows.Count; j++)
{
var row = dt.Rows[j];
//added rows to sheet
var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
cell.Value = row[i];
}
currentCell.EntireColumn.AutoFit();
}
var fileName="{somepath/somefile.xlsx}";
wb.SaveCopyAs(fileName);
_xl.Quit();
return fileName;
}
Try this it worked in Ubuntu and RedHat:
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
For Windows:
java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
For Mac
java -XX:+PrintFlagsFinal -version | grep -iE 'heapsize|permsize|threadstacksize'
The output of all this commands resembles the output below:
uintx InitialHeapSize := 20655360 {product}
uintx MaxHeapSize := 331350016 {product}
uintx PermSize = 21757952 {pd product}
uintx MaxPermSize = 85983232 {pd product}
intx ThreadStackSize = 1024 {pd product}
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)
To find the size in MB, divide the value with (1024*1024).
foreach syntax is quick and easy. for syntax is a little more complex, but is also more flexible.
foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items.
The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.
Bottom line- use foreach to quickly iterate all of the items in a collection. Use for to iterate a subset of the items of the collection or to modify the items as they are iterated.
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
needs to be:
var t = document.getElementById("table"),
tableRows = t.getElementsByTagName("tr"),
r = [], i, len, tds, j, jlen;
for ( i =0, len = tableRows.length; i<len; i++) {
tds = tableRows[i].getElementsByTagName('td');
for( j = 0, jlen = tds.length; j < jlen; j++) {
r.push(tds[j]);
}
}
Because getElementsByTagName
returns a NodeList
an Array-like structure. So you need to loop through the return nodes and then populate you r
like above.
If you review the process of SSL negotiation at Wikipedia, you will know that at the beginning ClientHello and ServerHello messages are sent between the browser and the server.
Only if the cyphers provided in ClientHello have overlapping items on the server, ServerHello message will contain a cypher that both sides support. Otherwise, SSL connection will not be initiated as there is no common cypher.
To resolve the problem, you need to install cyphers (usually at OS level), instead of trying hard on the browser (usually the browser relies on the OS). I am familiar with Windows and IE, but I know little about Linux and Firefox, so I can only point out what's wrong but cannot deliver you a solution.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
Yes if the structure is of the same type. Think it as a memory copy.
just simply use list.pop()
now if you want it the other way use : list.popleft()
help('nonlocal') The
nonlocal
statement
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
The
nonlocal
statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.Names listed in a
nonlocal
statement, unlike to those listed in aglobal
statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).Names listed in a
nonlocal
statement must not collide with pre- existing bindings in the local scope.See also:
PEP 3104 - Access to Names in Outer Scopes
The specification for thenonlocal
statement.Related help topics: global, NAMESPACES
Source: Python Language Reference
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
For editing Excel files from within a C# application, I recently started using NPOI. I'm very satisfied with it.
Please refer to this link: Reading date as a string not float from excel using python xlrd
it worked for me:
in shot this the link has:
import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime
This will do what you are looking for in C# (WebDriver/Selenium 2.0)
var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);
And never use Thread.Sleep because it makes your tests unreliable
SELECT DATECOL - DATEPART(weekday, DATECOL), DATECOL - DATEPART(weekday, DATECOL) + 7
In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:
using System.Data.OracleClient;
There are some system requirements here that you should verify are OK in your scenario.
Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.
I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.
Code with Excepion
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
After Fixes:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
Use readLines()
(with warn = FALSE
) to read the file into a character vector first.
After that use the text =
option to read the vector into a data frame with read.table()
pheasant <- read.table(
text = readLines(file.choose(), warn = FALSE),
header = TRUE,
sep = ","
)
Put 0 as default in SQL or add 0 into your area of table
I finally found here how to do it. To fix it, I needed another dependency:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
By including this dependency, Spring will automatically register a converter for it, as described here. After that, you need to add the following to application.properties:
spring.jackson.serialization.write_dates_as_timestamps=false
This will ensure that a correct converter is used, and dates will be printed in the format of 2016-03-16T13:56:39.492
Annotations are only needed in case you want to change the date format.
append
returns None, so at the second iteration you are calling method append
of NoneType. Just remove the assignment:
for i in range(0, n):
list1.append([i])
db.collection.update( { _id:...} , { $set: { some_key : new_info } }
to
db.collection.update( { _id: ..} , { $set: { some_key: { param1: newValue} } } );
Hope this help!
While there are two excellent answers telling you how to do it, I feel that another answer is missing: In most cases you shouldn't do it at all.
Arrays are cumbersome, in most cases you are better off using the Collection API.
With Collections, you can add and remove elements and there are specialized Collections for different functionality (index-based lookup, sorting, uniqueness, FIFO-access, concurrency etc.).
While it's of course good and important to know about Arrays and their usage, in most cases using Collections makes APIs a lot more manageable (which is why new libraries like Google Guava hardly use Arrays at all).
So, for your scenario, I'd prefer a List of Lists, and I'd create it using Guava:
List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
The error is self explanatory:
A good check I often use is to use telnet, eg on a windows command prompt run:
telnet 127.0.0.1 1433
If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem
\d is a digit, + is 1 or more, so a sequence of 1 or more digits
From release version 2.7.9/3.4.3 on, Python by default attempts to perform certificate validation.
This has been proposed in PEP 467, which is worth a read: https://www.python.org/dev/peps/pep-0476/
The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).
Relevant documentation:
https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection
This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.
https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection
Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.
Note that the new built-in verification is based on the system-provided certificate database. Opposed to that, the requests package ships its own certificate bundle. Pros and cons of both approaches are discussed in the Trust database section of PEP 476.
Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ?
is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.
What does the DUMP
function show is actually stored in the database?
SELECT column_name,
dump(column_name,1016)
FROM your_table
WHERE <<predicate that returns just the sample data you posted>>
What application are you using to view the data? What is the client's NLS_LANG
set to?
What is the database and national character set? Is the data stored in a VARCHAR2
column? Or NVARCHAR2
?
SELECT parameter, value
FROM v$nls_parameters
WHERE parameter LIKE '%CHARACTERSET';
If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE
would need to be something like
UPDATE table_name
SET column1 = REPLACE(column1, chr(25), q'[']'),
column2 = REPLACE(column2, chr(25), q'[']'),
...
columnN = REPLACE(columnN, chr(25), q'[']')
WHERE INSTR(column1,chr(25)) > 0
OR INSTR(column2,chr(25)) > 0
...
OR INSTR(columnN,chr(25)) > 0
I found that I had bound jFormattedCheckBox1.foreground
to jCheckBox1[${selected}]
.... this was the problem. Thank you for your help.
It seems that a color should not be able to be bound to a boolean
. I guess bindings are an advanced feature?
I found the problem by deleting all of the controls, then running, then undoing and then deleting one at a time. When I found the offending control, I examined the properties.
I found things not to like about all the above solutions, so I came up with my own. This version makes sure parts are joined with a single slash and leaves leading and trailing slashes alone. No pip install
, no urllib.parse.urljoin
weirdness.
In [1]: from functools import reduce
In [2]: def join_slash(a, b):
...: return a.rstrip('/') + '/' + b.lstrip('/')
...:
In [3]: def urljoin(*args):
...: return reduce(join_slash, args) if args else ''
...:
In [4]: parts = ['https://foo-bar.quux.net', '/foo', 'bar', '/bat/', '/quux/']
In [5]: urljoin(*parts)
Out[5]: 'https://foo-bar.quux.net/foo/bar/bat/quux/'
In [6]: urljoin('https://quux.com/', '/path', 'to/file///', '//here/')
Out[6]: 'https://quux.com/path/to/file/here/'
In [7]: urljoin()
Out[7]: ''
In [8]: urljoin('//','beware', 'of/this///')
Out[8]: '/beware/of/this///'
In [9]: urljoin('/leading', 'and/', '/trailing/', 'slash/')
Out[9]: '/leading/and/trailing/slash/'
For the same reason you do it in C; assignment is an expression, so you put the literal on the left so that you can't overwrite it if you accidentally use =
instead of ==
.
Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.
You can do this instead:
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))
You can use UITableViewRowAction
's backgroundColor
to set custom image or view. The trick is using UIColor(patternImage:)
.
Basically the width of UITableViewRowAction
area is decided by its title, so you can find a exact length of title(or whitespace) and set the exact size of image with patternImage
.
To implement this, I made a UIView
's extension method.
func image() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return UIImage()
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
and to make a string with whitespace and exact length,
fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
let kPadding: CGFloat = 20
let mutable = NSMutableString(string: "")
let attribute = [NSFontAttributeName: font]
while mutable.size(attributes: attribute).width < width - (2 * kPadding) {
mutable.append(" ")
}
return mutable as String
}
and now, you can create UITableViewRowAction
.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let whitespace = whitespaceString(width: kCellActionWidth)
let deleteAction = UITableViewRowAction(style: .`default`, title: whitespace) { (action, indexPath) in
// do whatever you want
}
// create a color from patter image and set the color as a background color of action
let kActionImageSize: CGFloat = 34
let view = UIView(frame: CGRect(x: 0, y: 0, width: kCellActionWidth, height: kCellHeight))
view.backgroundColor = UIColor.white
let imageView = UIImageView(frame: CGRect(x: (kCellActionWidth - kActionImageSize) / 2,
y: (kCellHeight - kActionImageSize) / 2,
width: 34,
height: 34))
imageView.image = UIImage(named: "x")
view.addSubview(imageView)
let image = view.image()
deleteAction.backgroundColor = UIColor(patternImage: image)
return [deleteAction]
}
The result will look like this.
Another way to do this is to import custom font which has the image you want to use as a font and use UIButton.appearance
. However this will affect other buttons unless you manually set other button's font.
From iOS 11, it will show this message [TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.
. Currently it is still working, but it wouldn't work in the future update.
==========================================
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
// Perform your action here
completion(true)
}
let muteAction = UIContextualAction(style: .normal, title: "Mute") { (action, view, completion) in
// Perform your action here
completion(true)
}
deleteAction.image = UIImage(named: "icon.png")
deleteAction.backgroundColor = UIColor.red
return UISwipeActionsConfiguration(actions: [deleteAction, muteAction])
}
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
You can create a form in VBA, with code to increase the width of a label control as your code progresses. You can use the width property of a label control to resize it. You can set the background colour property of the label to any colour you choose. This will let you create your own progress bar.
The label control that resizes is a quick solution. However, most people end up creating individual forms for each of their macros. I use the DoEvents function and a modeless form to use a single form for all your macros.
Here is a blog post I wrote about it: http://strugglingtoexcel.wordpress.com/2014/03/27/progress-bar-excel-vba/
All you have to do is import the form and a module into your projects, and call the progress bar with: Call modProgress.ShowProgress(ActionIndex, TotalActions, Title.....)
I hope this helps.
Override timeout with SimpleClientHttpRequestFactory
//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
SimpleClientHttpRequestFactory clientHttpRequestFactory
= new SimpleClientHttpRequestFactory();
//Connect timeout
clientHttpRequestFactory.setConnectTimeout(10_000);
//Read timeout
clientHttpRequestFactory.setReadTimeout(10_000);
return clientHttpRequestFactory;
}
HTTPClient provides other useful features such as connection pool, idle connection management etc.
Read More : Spring RestTemplate + HttpClient configuration example
Override timeout with HttpComponentsClientHttpRequestFactory
//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
//Connect timeout
clientHttpRequestFactory.setConnectTimeout(10_000);
//Read timeout
clientHttpRequestFactory.setReadTimeout(10_000);
return clientHttpRequestFactory;
}
reference: Spring RestTemplate timeout configuration example
The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):
SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
FROM dbo.tableZ AS t
ORDER BY t.A;
Not sure what the variables in your question are supposed to represent (they don't match).
Node should support using the http_proxy environmental variable - so it is cross platform and works on system settings rather than requiring a per-application configuration.
Using the provided solutions, I would recommend the following:
Coffeescript
get_url = (url, response) ->
if process.env.http_proxy?
match = process.env.http_proxy.match /^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i
if match
http.get { host: match[2], port: (if match[4]? then match[4] else 80), path: url }, response
return
http.get url, response
Javascript
get_url = function(url, response) {
var match;
if (process.env.http_proxy != null) {
match = process.env.http_proxy.match(/^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i);
if (match) {
http.get({
host: match[2],
port: (match[4] != null ? match[4] : 80),
path: url
}, response);
return;
}
}
return http.get(url, response);
};
Usage To use the method, effectively just replace http.get, for instance the following writes the index page of google to a file called test.htm:
file = fs.createWriteStream path.resolve(__dirname, "test.htm")
get_url "http://www.google.com.au/", (response) ->
response.pipe file
response.on "end", ->
console.log "complete"
node-schedule A cron-like and not-cron-like job scheduler for Node.
You can try to use btn-sm, btn-xs and btn-lg classes like this:
.btn-xl {
padding: 10px 20px;
font-size: 20px;
border-radius: 10px;
}
You can make use of Bootstrap .btn-group-justified
css class. Or you can simply add:
.btn-xl {
padding: 10px 20px;
font-size: 20px;
border-radius: 10px;
width:50%; //Specify your width here
}
Basically, no you have to make three delete statements in a transaction, children first and then parents. Setting up cascading deletes is a good idea if this is not a one-off thing and its existence won't conflict with any existing trigger setup.
The provided examples, using csv
modules, are great! Besides, you can always simply write to a text file using formatted strings, like the following tentative example:
l = [[1, 2], [2, 3], [4, 5]]
out = open('out.csv', 'w')
for row in l:
for column in row:
out.write('%d;' % column)
out.write('\n')
out.close()
I used ;
as separator, because it works best with Excell (one of your requirements).
Hope it helps!
As per the REST Implementation,
1) Path variables are used for the direct action on the resources, like a contact or a song
ex..
GET etc /api/resource/{songid} or
GET etc /api/resource/{contactid} will return respective data.
2) Query perms/argument are used for the in-direct resources like metadata of a song ex.., GET /api/resource/{songid}?metadata=genres it will return the genres data for that particular song.
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
If you are dealing with images, use getimagesize. Unlike file_exists, this built-in function supports remote files. It will return an array that contains the image information (width, height, type..etc). All you have to do is to check the first element in the array (the width). use print_r to output the content of the array
$imageArray = getimagesize("http://www.example.com/image.jpg");
if($imageArray[0])
{
echo "it's an image and here is the image's info<br>";
print_r($imageArray);
}
else
{
echo "invalid image";
}
Faced this issue on Android studio 4.1, windows 10.
The solution that worked for me:
1 - Go to gradle.properties file which is in the root directory of the project.
2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.
3 - Now close any open project from File -> close project.
4 - On the Welcome window, Go to Configure > Settings.
5 - Go to Build, Execution, Deployment > Compiler
6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.
Now close the android studio and restart it. The issue will be gone.
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
For completeness these are the cmap choices I encountered so far:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
Maybe map the share as a network drive and then do
git clone Z:\
Mostly just a guess; I always do this stuff using ssh. Following that suggstion of course will mean that you'll need to have that drive mapped every time you push/pull to/from the laptop. I'm not sure how you rig up ssh to work under windows but if you're going to be doing this a lot it might be worth investigating.
I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.
[src=''] {
visibility: hidden;
}
I had same Issue and i solve it following way:
The xml file which is using for create a Row inside createViewholder, just add below line:
android:clickable="true"
android:focusableInTouchMode="true"
android:background="?attr/selectableItemBackgroundBorderless"
OR If you using frameLayout as a parent of row item then:
android:clickable="true"
android:focusableInTouchMode="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
In java code inside view holder where you added on click listener:
@Override
public void onClick(View v) {
//ur other code here
v.setPressed(true);
}
In droupDown list there are two item add property.
1) Text 2) value
If you want to get text property then u use selecteditem.text
and If you want to select value property then use selectedvalue property
In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text
If both are different then they give us different results
None of the solutions posted here worked for me. It was devenv.exe (Visual Studio) locking the file, but if I restarted it, it would re-lock it.
Bizarrely, Windows wouldn't let me Delete the files (to Recycle Bin), but Shift+Delete (permanent delete) worked.
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
SELECT
DATENAME(mm, article.Created) AS Month,
DATENAME(yyyy, article.Created) AS Year,
COUNT(*) AS Total
FROM Articles AS article
GROUP BY
DATENAME(mm, article.Created),
DATENAME(yyyy, article.Created)
ORDER BY Month, Year DESC
It produces the following ouput (example).
Month | Year | Total
January | 2009 | 2
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
I had the same issue and managed to resolve it eventually. In my case, the port that the client sends the request to did not have a SSL cert binding to it. So I fixed the issue by binding a SSL cert to the port on the server side. Once that was done, this exception went away.
The problem is, that the text actually has full opacity in your example. It has full opacity inside the p
tag, but the p
tag is just semi-transparent.
You could add an semi-transparent PNG background image instead of realizing it in CSS, or separate text and div into two elements and move the text over the box (for example, negative margin).
Otherwise it won't be possible.
Just like Chris mentioned: if you use a PNG file with transparency, you have to use a JavaScript workaround to make it work in the pesky Internet Explorer...
Swift 3+
button.setImage(UIImage(named: "selected_image"), for: [.selected, .highlighted])
OR
button.setImage(UIImage(named: "selected_image"), for: UIControlState.selected.union(.highlighted))
It means that the button current in selected
state, then you touch it, show the highlight
state.
<asp:GridView ID="grd_item_list" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-bordered table-hover" OnRowCommand="grd_item_list_RowCommand">
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="remove_itemIndex" OnClientClick="if(confirm('Are You Sure to delete?')==true){ return true;} else{ return false;}" runat="server" class="btn btn-primary" Text="REMOVE" CommandName="REMOVE_ITEM" CommandArgument='<%# Container.DataItemIndex+1 %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**This is the row binding event**
protected void grd_item_list_RowCommand(object sender, GridViewCommandEventArgs e) {
item_list_bind_structure();
if (ViewState["item_list"] != null)
dt = (DataTable)ViewState["item_list"];
if (e.CommandName == "REMOVE_ITEM") {
var RowNum = Convert.ToInt32(e.CommandArgument.ToString()) - 1;
DataRow dr = dt.Rows[RowNum];
dr.Delete();
}
grd_item_list.DataSource = dt;
grd_item_list.DataBind();
}
There are a few less than perfect solutions:
1. Link to a fake anchor
<a href="#">
Problem: clicking the link jumps back to the top of the page
2. Using a tag other than 'a'
Use a span tag and use the jquery to handle the click
Problem: breaks keyboard navigation, have to manually change the hover cursor
3. Link to a javascript void function
<a href="javascript:void(0);">
<a href="javascript:;">
Problem: breaks when linking images in IE
Solution
Since these all have their problems, the solution I've settled on is to link to a fake anchor, and then return false from the onClick method:
<a href="#" onClick="return false;">
Not the most concise of solutions, but it solves all the problems with the above methods.
/**
* @Route("/category/{id}", name="_category")
* @Route("/category/{id}/{active}", name="_be_activatecategory")
* @Template()
*/
public function categoryAction($id, $active = null)
{ .. }
May works.
This will give you are simple print within a sql script:
select 'This is a comment' AS '';
Alternatively, this will add some dynamic data to your status update if used directly after an update
, delete
, or insert
command:
select concat ("Updated ", row_count(), " rows") as '';
Simple & Best way:
onclick="parentNode.remove()"
Deletes the complete parent from html
Thanks for the input. Tried the stuff that has been mentioned here and these are the 2 I got to work:
(
select 'OK', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND (BoolField05=1)
)
UNION
(
select 'DEL', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
)
AND
select
case
when
(BoolField05=1)
then 'OK'
else 'DEL'
end,
*
from WorkItems t1
Where
exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
Which would be the most efficient of these (edit: the second as it only scans the table once), and is it possible to make it even more efficient? (The BoolField=1) is really a variable (dyn sql) that can contain any where statement on the table.
I am running on MS SQL 2005. Tried Quassnoi examples but did not work as expected.
@( condition ? "true" : "false" )
A line feed means moving one line forward. The code is \n
.
A carriage return means moving the cursor to the beginning of the line. The code is \r
.
Windows editors often still use the combination of both as \r\n
in text files. Unix uses mostly only the \n
.
The separation comes from typewriter times, when you turned the wheel to move the paper to change the line and moved the carriage to restart typing on the beginning of a line. This was two steps.
var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
for (;i<l;i++) {
if (elems[i].type.toLowerCase() === "text") {
ret.push(elems[i]);
}
}
return ret;
}());
This SQL query gives output similar to \dx
:
SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description"
FROM pg_catalog.pg_extension e
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass
ORDER BY 1;
Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/
Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)
for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {
document.getElementsByTagName('iframe')[i].setAttribute('sandbox','allow-modals');
}
Here is a codepen demo working with an alert() after this fix as well: http://codepen.io/nicholasabrams/pen/vNpoBr?editors=001
replace
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3
with
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3
e.g. installing into /usr/local/bin
instead of /usr/bin
.
and ensure the /usr/local/bin
is before /usr/bin
in PATH.
i.e.
[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin
Ensure this always is the case by adding
export PATH=/usr/local/bin:$PATH
to the end of your ~/.bashrc
file. Prefixing the PATH
environment variable with custom bin folder such as /usr/local/bin
or /opt/<some install>/bin
is generally recommended to ensure that customizations are found before the default system ones.
XSLT supports JSON as seen at http://www.w3.org/TR/xslt-30/#json
XML uses angular brackets for delimiter tokens, JSON uses braces, square brackets, ... I. e. XML's fewer token recognition comparisons means it's optimized for declarative transformation, whereas more comparisons, being like switch statement, for speed reasons assume speculative branch prediction that imperative code in scripting languages is useful for. As direct consequence, for different mixes of semi-structured data, you may want to benchmark XSLT and javascript engines' performance as part of responsive pages. For negligible data payload, transformations might work just as well with JSON without XML serialization. W3's decision ought to be based on better analysis.
Here is another way you can change the selected option of a <select>
element in javascript. You can use
document.getElementById('salesperson').selectedIndex=1;
Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.
Here is a sample code. Check if you can use this type of approach:
<html>
<head>
<script language="javascript">
function changeSelected() {
document.getElementById('salesperson').selectedIndex=1;
}
</script>
</head>
<body>
<form name="f1">
<select id="salesperson" >
<option value"">james</option>
<option value"">john</option>
</select>
<input type="button" value="Change Selected" onClick="changeSelected();">
</form>
</body>
</html>
use the request()
helper instead. You don't have to worry about use
statements and thus this sort of problem wont happen again.
$input = request()->all();
simple