text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```objective-c
//
// UIImage+EXtension.h
// BigShow1949
//
// Created by zhht01 on 16/4/1.
//
#import <UIKit/UIKit.h>
@interface UIImage (EXtension)
/**
*
*/
+ (UIImage*)imageWithColor:(UIColor*)color;
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size; //
/**
*
*
* :
*/
+ (UIImage *)stretchImageWithName:(NSString *)name;
/**
*
*
* @param left :
* @param top :
*
* :
*/
+ (UIImage *)stretchImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top;
/**
*
*
* @param scaleLeft : 0-1
* @param scaleTop : 0-1
*
* :
*/
+ (UIImage *)stretchImageWithName:(NSString *)name scaleLeft:(CGFloat)scaleLeft scaleTop:(CGFloat)scaleTop;
+ (UIImage *)createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(NSInteger)r;
+ (UIImage *)circleImageWithName:(NSString *)name;
+ (UIImage *)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;
/**
*
*
* @param scaleLeft : 0-1
* @param scaleTop : 0-1
*
* :
*/
+ (UIImage*)circleImage:(UIImage*)image withInset:(CGFloat)inset;
/*-------- ----*/
/**
* ,
*
* @param img
* @param size
*
* @return
*/
+(UIImage *)image:(UIImage *)img scaleToSize:(CGSize)size;
/**
* ,
*
* @param img
* @param scale
*
* @return
*/
+(UIImage *)image:(UIImage *)img scale:(CGFloat)scale;
/**
* imge imge img
*
* @param image
* @param maskImage
*
* @return
*/
+ (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Image/UIImage+EXtension.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 456 |
```objective-c
//
// YFImageCategoryViewController.h
// BigShow1949
//
// Created by zhht01 on 16/4/1.
//
#import <UIKit/UIKit.h>
@interface YFImageCategoryViewController : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Image/YFImageCategoryViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 52 |
```objective-c
//
// UIScrollView+EmptyDataSet.m
// DZNEmptyDataSet
// path_to_url
//
// Created by Ignacio Romero Zurbuchen on 6/20/14.
// Licence: MIT-Licence
//
#import "UIScrollView+EmptyDataSet.h"
#import <objc/runtime.h>
@interface UIView (DZNConstraintBasedLayoutExtensions)
- (NSLayoutConstraint *)equallyRelatedConstraintWithView:(UIView *)view attribute:(NSLayoutAttribute)attribute;
@end
@interface DZNEmptyDataSetView : UIView
@property (nonatomic, readonly) UIView *contentView;
@property (nonatomic, readonly) UILabel *titleLabel;
@property (nonatomic, readonly) UILabel *detailLabel;
@property (nonatomic, readonly) UIImageView *imageView;
@property (nonatomic, readonly) UIButton *button;
@property (nonatomic, strong) UIView *customView;
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic, assign) CGFloat verticalOffset;
@property (nonatomic, assign) CGFloat verticalSpace;
@property (nonatomic, assign) BOOL fadeInOnDisplay;
- (void)setupConstraints;
- (void)prepareForReuse;
@end
#pragma mark - UIScrollView+EmptyDataSet
static char const * const kEmptyDataSetSource = "emptyDataSetSource";
static char const * const kEmptyDataSetDelegate = "emptyDataSetDelegate";
static char const * const kEmptyDataSetView = "emptyDataSetView";
#define kEmptyImageViewAnimationKey @"com.dzn.emptyDataSet.imageViewAnimation"
@interface UIScrollView () <UIGestureRecognizerDelegate>
@property (nonatomic, readonly) DZNEmptyDataSetView *emptyDataSetView;
@end
@implementation UIScrollView (DZNEmptyDataSet)
#pragma mark - Getters (Public)
- (id<DZNEmptyDataSetSource>)emptyDataSetSource
{
return objc_getAssociatedObject(self, kEmptyDataSetSource);
}
- (id<DZNEmptyDataSetDelegate>)emptyDataSetDelegate
{
return objc_getAssociatedObject(self, kEmptyDataSetDelegate);
}
- (BOOL)isEmptyDataSetVisible
{
UIView *view = objc_getAssociatedObject(self, kEmptyDataSetView);
return view ? !view.hidden : NO;
}
#pragma mark - Getters (Private)
- (DZNEmptyDataSetView *)emptyDataSetView
{
DZNEmptyDataSetView *view = objc_getAssociatedObject(self, kEmptyDataSetView);
if (!view)
{
view = [DZNEmptyDataSetView new];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
view.hidden = YES;
view.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dzn_didTapContentView:)];
view.tapGesture.delegate = self;
[view addGestureRecognizer:view.tapGesture];
[self setEmptyDataSetView:view];
}
return view;
}
- (BOOL)dzn_canDisplay
{
if (self.emptyDataSetSource && [self.emptyDataSetSource conformsToProtocol:@protocol(DZNEmptyDataSetSource)]) {
if ([self isKindOfClass:[UITableView class]] || [self isKindOfClass:[UICollectionView class]] || [self isKindOfClass:[UIScrollView class]]) {
return YES;
}
}
return NO;
}
- (NSInteger)dzn_itemsCount
{
NSInteger items = 0;
// UIScollView doesn't respond to 'dataSource' so let's exit
if (![self respondsToSelector:@selector(dataSource)]) {
return items;
}
// UITableView support
if ([self isKindOfClass:[UITableView class]]) {
UITableView *tableView = (UITableView *)self;
id <UITableViewDataSource> dataSource = tableView.dataSource;
NSInteger sections = 1;
if (dataSource && [dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
sections = [dataSource numberOfSectionsInTableView:tableView];
}
if (dataSource && [dataSource respondsToSelector:@selector(tableView:numberOfRowsInSection:)]) {
for (NSInteger section = 0; section < sections; section++) {
items += [dataSource tableView:tableView numberOfRowsInSection:section];
}
}
}
// UICollectionView support
else if ([self isKindOfClass:[UICollectionView class]]) {
UICollectionView *collectionView = (UICollectionView *)self;
id <UICollectionViewDataSource> dataSource = collectionView.dataSource;
NSInteger sections = 1;
if (dataSource && [dataSource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
sections = [dataSource numberOfSectionsInCollectionView:collectionView];
}
if (dataSource && [dataSource respondsToSelector:@selector(collectionView:numberOfItemsInSection:)]) {
for (NSInteger section = 0; section < sections; section++) {
items += [dataSource collectionView:collectionView numberOfItemsInSection:section];
}
}
}
return items;
}
#pragma mark - Data Source Getters
- (NSAttributedString *)dzn_titleLabelString
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(titleForEmptyDataSet:)]) {
NSAttributedString *string = [self.emptyDataSetSource titleForEmptyDataSet:self];
if (string) NSAssert([string isKindOfClass:[NSAttributedString class]], @"You must return a valid NSAttributedString object for -titleForEmptyDataSet:");
return string;
}
return nil;
}
- (NSAttributedString *)dzn_detailLabelString
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(descriptionForEmptyDataSet:)]) {
NSAttributedString *string = [self.emptyDataSetSource descriptionForEmptyDataSet:self];
if (string) NSAssert([string isKindOfClass:[NSAttributedString class]], @"You must return a valid NSAttributedString object for -descriptionForEmptyDataSet:");
return string;
}
return nil;
}
- (UIImage *)dzn_image
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(imageForEmptyDataSet:)]) {
UIImage *image = [self.emptyDataSetSource imageForEmptyDataSet:self];
if (image) NSAssert([image isKindOfClass:[UIImage class]], @"You must return a valid UIImage object for -imageForEmptyDataSet:");
return image;
}
return nil;
}
- (CAAnimation *)dzn_imageAnimation
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(imageAnimationForEmptyDataSet:)]) {
CAAnimation *imageAnimation = [self.emptyDataSetSource imageAnimationForEmptyDataSet:self];
if (imageAnimation) NSAssert([imageAnimation isKindOfClass:[CAAnimation class]], @"You must return a valid CAAnimation object for -imageAnimationForEmptyDataSet:");
return imageAnimation;
}
return nil;
}
- (UIColor *)dzn_imageTintColor
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(imageTintColorForEmptyDataSet:)]) {
UIColor *color = [self.emptyDataSetSource imageTintColorForEmptyDataSet:self];
if (color) NSAssert([color isKindOfClass:[UIColor class]], @"You must return a valid UIColor object for -imageTintColorForEmptyDataSet:");
return color;
}
return nil;
}
- (NSAttributedString *)dzn_buttonTitleForState:(UIControlState)state
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(buttonTitleForEmptyDataSet:forState:)]) {
NSAttributedString *string = [self.emptyDataSetSource buttonTitleForEmptyDataSet:self forState:state];
if (string) NSAssert([string isKindOfClass:[NSAttributedString class]], @"You must return a valid NSAttributedString object for -buttonTitleForEmptyDataSet:forState:");
return string;
}
return nil;
}
- (UIImage *)dzn_buttonImageForState:(UIControlState)state
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(buttonImageForEmptyDataSet:forState:)]) {
UIImage *image = [self.emptyDataSetSource buttonImageForEmptyDataSet:self forState:state];
if (image) NSAssert([image isKindOfClass:[UIImage class]], @"You must return a valid UIImage object for -buttonImageForEmptyDataSet:forState:");
return image;
}
return nil;
}
- (UIImage *)dzn_buttonBackgroundImageForState:(UIControlState)state
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(buttonBackgroundImageForEmptyDataSet:forState:)]) {
UIImage *image = [self.emptyDataSetSource buttonBackgroundImageForEmptyDataSet:self forState:state];
if (image) NSAssert([image isKindOfClass:[UIImage class]], @"You must return a valid UIImage object for -buttonBackgroundImageForEmptyDataSet:forState:");
return image;
}
return nil;
}
- (UIColor *)dzn_dataSetBackgroundColor
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(backgroundColorForEmptyDataSet:)]) {
UIColor *color = [self.emptyDataSetSource backgroundColorForEmptyDataSet:self];
if (color) NSAssert([color isKindOfClass:[UIColor class]], @"You must return a valid UIColor object for -backgroundColorForEmptyDataSet:");
return color;
}
return [UIColor clearColor];
}
- (UIView *)dzn_customView
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(customViewForEmptyDataSet:)]) {
UIView *view = [self.emptyDataSetSource customViewForEmptyDataSet:self];
if (view) NSAssert([view isKindOfClass:[UIView class]], @"You must return a valid UIView object for -customViewForEmptyDataSet:");
return view;
}
return nil;
}
- (CGFloat)dzn_verticalOffset
{
CGFloat offset = 0.0;
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(verticalOffsetForEmptyDataSet:)]) {
offset = [self.emptyDataSetSource verticalOffsetForEmptyDataSet:self];
}
return offset;
}
- (CGFloat)dzn_verticalSpace
{
if (self.emptyDataSetSource && [self.emptyDataSetSource respondsToSelector:@selector(spaceHeightForEmptyDataSet:)]) {
return [self.emptyDataSetSource spaceHeightForEmptyDataSet:self];
}
return 0.0;
}
#pragma mark - Delegate Getters & Events (Private)
- (BOOL)dzn_shouldFadeIn {
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetShouldFadeIn:)]) {
return [self.emptyDataSetDelegate emptyDataSetShouldFadeIn:self];
}
return YES;
}
- (BOOL)dzn_shouldDisplay
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetShouldDisplay:)]) {
return [self.emptyDataSetDelegate emptyDataSetShouldDisplay:self];
}
return YES;
}
- (BOOL)dzn_isTouchAllowed
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetShouldAllowTouch:)]) {
return [self.emptyDataSetDelegate emptyDataSetShouldAllowTouch:self];
}
return YES;
}
- (BOOL)dzn_isScrollAllowed
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetShouldAllowScroll:)]) {
return [self.emptyDataSetDelegate emptyDataSetShouldAllowScroll:self];
}
return NO;
}
- (BOOL)dzn_isImageViewAnimateAllowed
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetShouldAnimateImageView:)]) {
return [self.emptyDataSetDelegate emptyDataSetShouldAnimateImageView:self];
}
return NO;
}
- (void)dzn_willAppear
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetWillAppear:)]) {
[self.emptyDataSetDelegate emptyDataSetWillAppear:self];
}
}
- (void)dzn_didAppear
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetDidAppear:)]) {
[self.emptyDataSetDelegate emptyDataSetDidAppear:self];
}
}
- (void)dzn_willDisappear
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetWillDisappear:)]) {
[self.emptyDataSetDelegate emptyDataSetWillDisappear:self];
}
}
- (void)dzn_didDisappear
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetDidDisappear:)]) {
[self.emptyDataSetDelegate emptyDataSetDidDisappear:self];
}
}
- (void)dzn_didTapContentView:(id)sender
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSet:didTapView:)]) {
[self.emptyDataSetDelegate emptyDataSet:self didTapView:sender];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
else if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetDidTapView:)]) {
[self.emptyDataSetDelegate emptyDataSetDidTapView:self];
}
#pragma clang diagnostic pop
}
- (void)dzn_didTapDataButton:(id)sender
{
if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSet:didTapButton:)]) {
[self.emptyDataSetDelegate emptyDataSet:self didTapButton:sender];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
else if (self.emptyDataSetDelegate && [self.emptyDataSetDelegate respondsToSelector:@selector(emptyDataSetDidTapButton:)]) {
[self.emptyDataSetDelegate emptyDataSetDidTapButton:self];
}
#pragma clang diagnostic pop
}
#pragma mark - Setters (Public)
- (void)setEmptyDataSetSource:(id<DZNEmptyDataSetSource>)datasource
{
if (!datasource || ![self dzn_canDisplay]) {
[self dzn_invalidate];
}
objc_setAssociatedObject(self, kEmptyDataSetSource, datasource, OBJC_ASSOCIATION_ASSIGN);
// We add method sizzling for injecting -dzn_reloadData implementation to the native -reloadData implementation
[self swizzleIfPossible:@selector(reloadData)];
// Exclusively for UITableView, we also inject -dzn_reloadData to -endUpdates
if ([self isKindOfClass:[UITableView class]]) {
[self swizzleIfPossible:@selector(endUpdates)];
}
}
- (void)setEmptyDataSetDelegate:(id<DZNEmptyDataSetDelegate>)delegate
{
if (!delegate) {
[self dzn_invalidate];
}
objc_setAssociatedObject(self, kEmptyDataSetDelegate, delegate, OBJC_ASSOCIATION_ASSIGN);
}
#pragma mark - Setters (Private)
- (void)setEmptyDataSetView:(DZNEmptyDataSetView *)view
{
objc_setAssociatedObject(self, kEmptyDataSetView, view, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark - Reload APIs (Public)
- (void)reloadEmptyDataSet
{
[self dzn_reloadEmptyDataSet];
}
#pragma mark - Reload APIs (Private)
- (void)dzn_reloadEmptyDataSet
{
if (![self dzn_canDisplay]) {
return;
}
if ([self dzn_shouldDisplay] && [self dzn_itemsCount] == 0)
{
// Notifies that the empty dataset view will appear
[self dzn_willAppear];
DZNEmptyDataSetView *view = self.emptyDataSetView;
if (!view.superview) {
// Send the view all the way to the back, in case a header and/or footer is present, as well as for sectionHeaders or any other content
if (([self isKindOfClass:[UITableView class]] || [self isKindOfClass:[UICollectionView class]]) && self.subviews.count > 1) {
[self insertSubview:view atIndex:0];
}
else {
[self addSubview:view];
}
}
// Removing view resetting the view and its constraints it very important to guarantee a good state
[view prepareForReuse];
UIView *customView = [self dzn_customView];
// If a non-nil custom view is available, let's configure it instead
if (customView) {
view.customView = customView;
}
else {
// Get the data from the data source
NSAttributedString *titleLabelString = [self dzn_titleLabelString];
NSAttributedString *detailLabelString = [self dzn_detailLabelString];
UIImage *buttonImage = [self dzn_buttonImageForState:UIControlStateNormal];
NSAttributedString *buttonTitle = [self dzn_buttonTitleForState:UIControlStateNormal];
UIImage *image = [self dzn_image];
UIColor *imageTintColor = [self dzn_imageTintColor];
UIImageRenderingMode renderingMode = imageTintColor ? UIImageRenderingModeAlwaysTemplate : UIImageRenderingModeAlwaysOriginal;
view.verticalSpace = [self dzn_verticalSpace];
// Configure Image
if (image) {
if ([image respondsToSelector:@selector(imageWithRenderingMode:)]) {
view.imageView.image = [image imageWithRenderingMode:renderingMode];
view.imageView.tintColor = imageTintColor;
}
else {
// iOS 6 fallback: insert code to convert imaged if needed
view.imageView.image = image;
}
}
// Configure title label
if (titleLabelString) {
view.titleLabel.attributedText = titleLabelString;
}
// Configure detail label
if (detailLabelString) {
view.detailLabel.attributedText = detailLabelString;
}
// Configure button
if (buttonImage) {
[view.button setImage:buttonImage forState:UIControlStateNormal];
[view.button setImage:[self dzn_buttonImageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
}
else if (buttonTitle) {
[view.button setAttributedTitle:buttonTitle forState:UIControlStateNormal];
[view.button setAttributedTitle:[self dzn_buttonTitleForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
[view.button setBackgroundImage:[self dzn_buttonBackgroundImageForState:UIControlStateNormal] forState:UIControlStateNormal];
[view.button setBackgroundImage:[self dzn_buttonBackgroundImageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
}
}
// Configure offset
view.verticalOffset = [self dzn_verticalOffset];
// Configure the empty dataset view
view.backgroundColor = [self dzn_dataSetBackgroundColor];
view.hidden = NO;
view.clipsToBounds = YES;
// Configure empty dataset userInteraction permission
view.userInteractionEnabled = [self dzn_isTouchAllowed];
// Configure empty dataset fade in display
view.fadeInOnDisplay = [self dzn_shouldFadeIn];
[view setupConstraints];
[UIView performWithoutAnimation:^{
[view layoutIfNeeded];
}];
// Configure scroll permission
self.scrollEnabled = [self dzn_isScrollAllowed];
// Configure image view animation
if ([self dzn_isImageViewAnimateAllowed])
{
CAAnimation *animation = [self dzn_imageAnimation];
if (animation) {
[self.emptyDataSetView.imageView.layer addAnimation:animation forKey:kEmptyImageViewAnimationKey];
}
}
else if ([self.emptyDataSetView.imageView.layer animationForKey:kEmptyImageViewAnimationKey]) {
[self.emptyDataSetView.imageView.layer removeAnimationForKey:kEmptyImageViewAnimationKey];
}
// Notifies that the empty dataset view did appear
[self dzn_didAppear];
}
else if (self.isEmptyDataSetVisible) {
[self dzn_invalidate];
}
}
- (void)dzn_invalidate
{
// Notifies that the empty dataset view will disappear
[self dzn_willDisappear];
if (self.emptyDataSetView) {
[self.emptyDataSetView prepareForReuse];
[self.emptyDataSetView removeFromSuperview];
[self setEmptyDataSetView:nil];
}
self.scrollEnabled = YES;
// Notifies that the empty dataset view did disappear
[self dzn_didDisappear];
}
#pragma mark - Method Swizzling
static NSMutableDictionary *_impLookupTable;
static NSString *const DZNSwizzleInfoPointerKey = @"pointer";
static NSString *const DZNSwizzleInfoOwnerKey = @"owner";
static NSString *const DZNSwizzleInfoSelectorKey = @"selector";
// Based on Bryce Buchanan's swizzling technique path_to_url
// And Juzzin's ideas path_to_url
void dzn_original_implementation(id self, SEL _cmd)
{
// Fetch original implementation from lookup table
NSString *key = dzn_implementationKey(self, _cmd);
NSDictionary *swizzleInfo = [_impLookupTable objectForKey:key];
NSValue *impValue = [swizzleInfo valueForKey:DZNSwizzleInfoPointerKey];
IMP impPointer = [impValue pointerValue];
// We then inject the additional implementation for reloading the empty dataset
// Doing it before calling the original implementation does update the 'isEmptyDataSetVisible' flag on time.
[self dzn_reloadEmptyDataSet];
// If found, call original implementation
if (impPointer) {
((void(*)(id,SEL))impPointer)(self,_cmd);
}
}
NSString *dzn_implementationKey(id target, SEL selector)
{
if (!target || !selector) {
return nil;
}
Class baseClass;
if ([target isKindOfClass:[UITableView class]]) baseClass = [UITableView class];
else if ([target isKindOfClass:[UICollectionView class]]) baseClass = [UICollectionView class];
else if ([target isKindOfClass:[UIScrollView class]]) baseClass = [UIScrollView class];
else return nil;
NSString *className = NSStringFromClass([baseClass class]);
NSString *selectorName = NSStringFromSelector(selector);
return [NSString stringWithFormat:@"%@_%@",className,selectorName];
}
- (void)swizzleIfPossible:(SEL)selector
{
// Check if the target responds to selector
if (![self respondsToSelector:selector]) {
return;
}
// Create the lookup table
if (!_impLookupTable) {
_impLookupTable = [[NSMutableDictionary alloc] initWithCapacity:2];
}
// We make sure that setImplementation is called once per class kind, UITableView or UICollectionView.
for (NSDictionary *info in [_impLookupTable allValues]) {
Class class = [info objectForKey:DZNSwizzleInfoOwnerKey];
NSString *selectorName = [info objectForKey:DZNSwizzleInfoSelectorKey];
if ([selectorName isEqualToString:NSStringFromSelector(selector)]) {
if ([self isKindOfClass:class]) {
return;
}
}
}
NSString *key = dzn_implementationKey(self, selector);
NSValue *impValue = [[_impLookupTable objectForKey:key] valueForKey:DZNSwizzleInfoPointerKey];
// If the implementation for this class already exist, skip!!
if (impValue || !key) {
return;
}
// Swizzle by injecting additional implementation
Method method = class_getInstanceMethod([self class], selector);
IMP dzn_newImplementation = method_setImplementation(method, (IMP)dzn_original_implementation);
// Store the new implementation in the lookup table
NSDictionary *swizzledInfo = @{DZNSwizzleInfoOwnerKey: [self class],
DZNSwizzleInfoSelectorKey: NSStringFromSelector(selector),
DZNSwizzleInfoPointerKey: [NSValue valueWithPointer:dzn_newImplementation]};
[_impLookupTable setObject:swizzledInfo forKey:key];
}
#pragma mark - UIGestureRecognizerDelegate Methods
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer.view isEqual:self.emptyDataSetView]) {
return [self dzn_isTouchAllowed];
}
return [super gestureRecognizerShouldBegin:gestureRecognizer];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
UIGestureRecognizer *tapGesture = self.emptyDataSetView.tapGesture;
if ([gestureRecognizer isEqual:tapGesture] || [otherGestureRecognizer isEqual:tapGesture]) {
return YES;
}
// defer to emptyDataSetDelegate's implementation if available
if ( (self.emptyDataSetDelegate != (id)self) && [self.emptyDataSetDelegate respondsToSelector:@selector(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:)]) {
return [(id)self.emptyDataSetDelegate gestureRecognizer:gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:otherGestureRecognizer];
}
return NO;
}
@end
#pragma mark - DZNEmptyDataSetView
@implementation DZNEmptyDataSetView
@synthesize contentView = _contentView;
@synthesize titleLabel = _titleLabel, detailLabel = _detailLabel, imageView = _imageView, button = _button;
#pragma mark - Initialization Methods
- (instancetype)init
{
self = [super init];
if (self) {
[self addSubview:self.contentView];
}
return self;
}
- (void)didMoveToSuperview
{
self.frame = self.superview.bounds;
void(^fadeInBlock)(void) = ^{_contentView.alpha = 1.0;};
if (self.fadeInOnDisplay) {
[UIView animateWithDuration:0.25
animations:fadeInBlock
completion:NULL];
}
else {
fadeInBlock();
}
}
#pragma mark - Getters
- (UIView *)contentView
{
if (!_contentView)
{
_contentView = [UIView new];
_contentView.translatesAutoresizingMaskIntoConstraints = NO;
_contentView.backgroundColor = [UIColor clearColor];
_contentView.userInteractionEnabled = YES;
_contentView.alpha = 0;
}
return _contentView;
}
- (UIImageView *)imageView
{
if (!_imageView)
{
_imageView = [UIImageView new];
_imageView.translatesAutoresizingMaskIntoConstraints = NO;
_imageView.backgroundColor = [UIColor clearColor];
_imageView.contentMode = UIViewContentModeScaleAspectFit;
_imageView.userInteractionEnabled = NO;
_imageView.accessibilityIdentifier = @"empty set background image";
[_contentView addSubview:_imageView];
}
return _imageView;
}
- (UILabel *)titleLabel
{
if (!_titleLabel)
{
_titleLabel = [UILabel new];
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.font = [UIFont systemFontOfSize:27.0];
_titleLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
_titleLabel.numberOfLines = 0;
_titleLabel.accessibilityIdentifier = @"empty set title";
[_contentView addSubview:_titleLabel];
}
return _titleLabel;
}
- (UILabel *)detailLabel
{
if (!_detailLabel)
{
_detailLabel = [UILabel new];
_detailLabel.translatesAutoresizingMaskIntoConstraints = NO;
_detailLabel.backgroundColor = [UIColor clearColor];
_detailLabel.font = [UIFont systemFontOfSize:17.0];
_detailLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0];
_detailLabel.textAlignment = NSTextAlignmentCenter;
_detailLabel.lineBreakMode = NSLineBreakByWordWrapping;
_detailLabel.numberOfLines = 0;
_detailLabel.accessibilityIdentifier = @"empty set detail label";
[_contentView addSubview:_detailLabel];
}
return _detailLabel;
}
- (UIButton *)button
{
if (!_button)
{
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.translatesAutoresizingMaskIntoConstraints = NO;
_button.backgroundColor = [UIColor clearColor];
_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
_button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
_button.accessibilityIdentifier = @"empty set button";
[_button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
[_contentView addSubview:_button];
}
return _button;
}
- (BOOL)canShowImage
{
return (_imageView.image && _imageView.superview);
}
- (BOOL)canShowTitle
{
return (_titleLabel.attributedText.string.length > 0 && _titleLabel.superview);
}
- (BOOL)canShowDetail
{
return (_detailLabel.attributedText.string.length > 0 && _detailLabel.superview);
}
- (BOOL)canShowButton
{
if ([_button attributedTitleForState:UIControlStateNormal].string.length > 0 || [_button imageForState:UIControlStateNormal]) {
return (_button.superview != nil);
}
return NO;
}
#pragma mark - Setters
- (void)setCustomView:(UIView *)view
{
if (!view) {
return;
}
if (_customView) {
[_customView removeFromSuperview];
_customView = nil;
}
_customView = view;
_customView.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:_customView];
}
#pragma mark - Action Methods
- (void)didTapButton:(id)sender
{
SEL selector = NSSelectorFromString(@"dzn_didTapDataButton:");
if ([self.superview respondsToSelector:selector]) {
[self.superview performSelector:selector withObject:sender afterDelay:0.0f];
}
}
- (void)removeAllConstraints
{
[self removeConstraints:self.constraints];
[_contentView removeConstraints:_contentView.constraints];
}
- (void)prepareForReuse
{
[self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
_titleLabel = nil;
_detailLabel = nil;
_imageView = nil;
_button = nil;
_customView = nil;
[self removeAllConstraints];
}
#pragma mark - Auto-Layout Configuration
- (void)setupConstraints
{
// First, configure the content view constaints
// The content view must alway be centered to its superview
NSLayoutConstraint *centerXConstraint = [self equallyRelatedConstraintWithView:self.contentView attribute:NSLayoutAttributeCenterX];
NSLayoutConstraint *centerYConstraint = [self equallyRelatedConstraintWithView:self.contentView attribute:NSLayoutAttributeCenterY];
[self addConstraint:centerXConstraint];
[self addConstraint:centerYConstraint];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|" options:0 metrics:nil views:@{@"contentView": self.contentView}]];
// When a custom offset is available, we adjust the vertical constraints' constants
if (self.verticalOffset != 0 && self.constraints.count > 0) {
centerYConstraint.constant = self.verticalOffset;
}
// If applicable, set the custom view's constraints
if (_customView) {
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|" options:0 metrics:nil views:@{@"contentView": self.contentView}]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[customView]|" options:0 metrics:nil views:@{@"customView":_customView}]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[customView]|" options:0 metrics:nil views:@{@"customView":_customView}]];
}
else {
CGFloat width = CGRectGetWidth(self.frame) ? : CGRectGetWidth([UIScreen mainScreen].bounds);
CGFloat padding = roundf(width/16.0);
CGFloat verticalSpace = self.verticalSpace ? : 11.0; // Default is 11 pts
NSMutableArray *subviewStrings = [NSMutableArray array];
NSMutableDictionary *views = [NSMutableDictionary dictionary];
NSDictionary *metrics = @{@"padding": @(padding)};
// Assign the image view's horizontal constraints
if (_imageView.superview) {
[subviewStrings addObject:@"imageView"];
views[[subviewStrings lastObject]] = _imageView;
[self.contentView addConstraint:[self.contentView equallyRelatedConstraintWithView:_imageView attribute:NSLayoutAttributeCenterX]];
}
// Assign the title label's horizontal constraints
if ([self canShowTitle]) {
[subviewStrings addObject:@"titleLabel"];
views[[subviewStrings lastObject]] = _titleLabel;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(padding@750)-[titleLabel(>=0)]-(padding@750)-|"
options:0 metrics:metrics views:views]];
}
// or removes from its superview
else {
[_titleLabel removeFromSuperview];
_titleLabel = nil;
}
// Assign the detail label's horizontal constraints
if ([self canShowDetail]) {
[subviewStrings addObject:@"detailLabel"];
views[[subviewStrings lastObject]] = _detailLabel;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(padding@750)-[detailLabel(>=0)]-(padding@750)-|"
options:0 metrics:metrics views:views]];
}
// or removes from its superview
else {
[_detailLabel removeFromSuperview];
_detailLabel = nil;
}
// Assign the button's horizontal constraints
if ([self canShowButton]) {
[subviewStrings addObject:@"button"];
views[[subviewStrings lastObject]] = _button;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(padding@750)-[button(>=0)]-(padding@750)-|"
options:0 metrics:metrics views:views]];
}
// or removes from its superview
else {
[_button removeFromSuperview];
_button = nil;
}
NSMutableString *verticalFormat = [NSMutableString new];
// Build a dynamic string format for the vertical constraints, adding a margin between each element. Default is 11 pts.
for (int i = 0; i < subviewStrings.count; i++) {
NSString *string = subviewStrings[i];
[verticalFormat appendFormat:@"[%@]", string];
if (i < subviewStrings.count-1) {
[verticalFormat appendFormat:@"-(%.f@750)-", verticalSpace];
}
}
// Assign the vertical constraints to the content view
if (verticalFormat.length > 0) {
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|%@|", verticalFormat]
options:0 metrics:metrics views:views]];
}
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *hitView = [super hitTest:point withEvent:event];
// Return any UIControl instance such as buttons, segmented controls, switches, etc.
if ([hitView isKindOfClass:[UIControl class]]) {
return hitView;
}
// Return either the contentView or customView
if ([hitView isEqual:_contentView] || [hitView isEqual:_customView]) {
return hitView;
}
return nil;
}
@end
#pragma mark - UIView+DZNConstraintBasedLayoutExtensions
@implementation UIView (DZNConstraintBasedLayoutExtensions)
- (NSLayoutConstraint *)equallyRelatedConstraintWithView:(UIView *)view attribute:(NSLayoutAttribute)attribute
{
return [NSLayoutConstraint constraintWithItem:view
attribute:attribute
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:attribute
multiplier:1.0
constant:0.0];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/EmptyDataSet/GzwTableViewLoading/UIScrollView+EmptyDataSet.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 7,380 |
```objective-c
//
// YFSafeObjectViewController.h
// BigShow1949
//
// Created by apple on 2018/4/25.
//
#import <UIKit/UIKit.h>
@interface YFSafeObjectViewController : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/YFSafeObjectViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 51 |
```objective-c
//
// UIImage+EXtension.m
// BigShow1949
//
// Created by zhht01 on 16/4/1.
//
#import "UIImage+EXtension.h"
@implementation UIImage (EXtension)
#pragma mark -
+ (UIImage *)stretchImageWithName:(NSString *)name scaleLeft:(CGFloat)scaleLeft scaleTop:(CGFloat)scaleTop {
UIImage *image = [UIImage imageNamed:name];
return [self stretchImageWithName:name left:image.size.width * scaleLeft top:image.size.height * scaleTop];
}
+ (UIImage *)stretchImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top {
UIImage *image = [UIImage imageNamed:name];
return [image stretchableImageWithLeftCapWidth:left topCapHeight:top];
}
+ (UIImage *)stretchImageWithName:(NSString *)name
{
return [self stretchImageWithName:name scaleLeft:0.5 scaleTop:0.5];
}
#pragma mark -
///**
// * Image
// *
// * @param color
// * @param size
// *
// */
//+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
//{
// UIGraphicsBeginImageContextWithOptions(size, 0, [UIScreen mainScreen].scale);
// [color set];
// UIRectFill(CGRectMake(0, 0, size.width, size.height));
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return image;
//}
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,color.CGColor);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
+ (UIImage*)imageWithColor:(UIColor*)color {
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
#pragma mark -
+ (UIImage *)circleImageWithName:(NSString *)name {
return [self circleImageWithName:name borderWidth:0 borderColor:[UIColor whiteColor]];
}
+ (UIImage *)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
// 1.
UIImage *oldImage = [UIImage imageNamed:name];
// 2.
CGFloat imageW = oldImage.size.width + 22 * borderWidth;
CGFloat imageH = oldImage.size.height + 22 * borderWidth;
CGSize imageSize = CGSizeMake(imageW, imageH);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
// 3.,
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 4.()
[borderColor set];
CGFloat bigRadius = imageW * 0.5; //
CGFloat centerX = bigRadius; //
CGFloat centerY = bigRadius;
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx); // As a side effect when you call this function, Quartz clears the current path.
// 5.
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
// ()
CGContextClip(ctx);
// 6.
[oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
// 7.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 8.
UIGraphicsEndImageContext();
return newImage;
}
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,
float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0)
{
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2); // Start at lower right corner
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
+ (UIImage *)createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(NSInteger)r
{
// the size of CGContextRef
int w = size.width;
int h = size.height;
UIImage *img = image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGRect rect = CGRectMake(0, 0, w, h);
CGContextBeginPath(context);
addRoundedRectToPath(context, rect, r, r);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
img = [UIImage imageWithCGImage:imageMasked];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageMasked);
return img;
}
+ (UIImage*)circleImage:(UIImage*)image withInset:(CGFloat)inset {
UIGraphicsBeginImageContext(image.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);
[image drawInRect:rect];
CGContextAddEllipseInRect(context, rect);
CGContextStrokePath(context);
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
//+ (UIImage *)circleImageWithName:(NSString *)name {
//
// UIImage *image = [UIImage imageNamed:name];
//
// //layerlayer
// image.layer.masksToBounds = YES;
//
// //layer,
// self.imageView2.layer.cornerRadius = self.imageView2.bounds.size.width * 0.5;
//
// //20
// self.imageView2.layer.borderWidth = 5.0;
//
// //
// self.imageView2.layer.borderColor = [UIColor whiteColor].CGColor;
//}
/**
*
*/
+ (UIImage *)colorizeImage:(UIImage *)baseImage withColor:(UIColor *)theColor {
UIGraphicsBeginImageContext(CGSizeMake(baseImage.size.width*2, baseImage.size.height*2));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width * 2, baseImage.size.height * 2);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, area, baseImage.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
/**
*
*
* @param blur
*
* @return
*/
/*
- (UIImage *)boxblurImageWithBlur:(CGFloat)blur {
NSData *imageData = UIImageJPEGRepresentation(self, 1); // convert to jpeg
UIImage* destImage = [UIImage imageWithData:imageData];
if (blur < 0.f || blur > 1.f) {
blur = 0.5f;
}
int boxSize = (int)(blur * 40);
boxSize = boxSize - (boxSize % 2) + 1;
CGImageRef img = destImage.CGImage;
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
void *pixelBuffer;
//create vImage_Buffer with data from CGImageRef
CGDataProviderRef inProvider = CGImageGetDataProvider(img);
CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
//create vImage_Buffer for output
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
if(pixelBuffer == NULL)
NSLog(@"No pixelbuffer");
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
// Create a third buffer for intermediate processing
void *pixelBuffer2 = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
vImage_Buffer outBuffer2;
outBuffer2.data = pixelBuffer2;
outBuffer2.width = CGImageGetWidth(img);
outBuffer2.height = CGImageGetHeight(img);
outBuffer2.rowBytes = CGImageGetBytesPerRow(img);
//perform convolution
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer2, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"error from convolution %ld", error);
}
error = vImageBoxConvolve_ARGB8888(&outBuffer2, &inBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"error from convolution %ld", error);
}
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"error from convolution %ld", error);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(outBuffer.data,
outBuffer.width,
outBuffer.height,
8,
outBuffer.rowBytes,
colorSpace,
(CGBitmapInfo)kCGImageAlphaNoneSkipLast);
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
//clean up
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
free(pixelBuffer2);
CFRelease(inBitmapData);
CGImageRelease(imageRef);
return returnImage;
}
*/
/**
* Image
*
* @param size
*
* @return Image
*/
- (UIImage *)cropImageWithSize:(CGSize)size {
float scale = self.size.width/self.size.height;
CGRect rect = CGRectMake(0, 0, 0, 0);
if (scale > size.width/size.height) {
rect.origin.x = (self.size.width - self.size.height * size.width/size.height)/2;
rect.size.width = self.size.height * size.width/size.height;
rect.size.height = self.size.height;
}else {
rect.origin.y = (self.size.height - self.size.width/size.width * size.height)/2;
rect.size.width = self.size.width;
rect.size.height = self.size.width/size.width * size.height;
}
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
/*----------- ------------*/
+(UIImage *)image:(UIImage *)img scaleToSize:(CGSize)size
{
// bitmapcontext
// context
UIGraphicsBeginImageContext(size);
//
[img drawInRect:CGRectMake(0, 0, size.width, size.height)];
// context
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// context
UIGraphicsEndImageContext();
//
return scaledImage;
}
+(UIImage *)image:(UIImage *)img scale:(CGFloat)scale{
CGSize size=CGSizeMake(img.size.width*scale, img.size.height*scale);
return [self image:img scaleToSize:size];
}
#pragma mark -
/**
* imge imge img
* path_to_url
* @param image
* @param maskImage
*
* @return
*/
+ (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Image/UIImage+EXtension.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 3,166 |
```objective-c
//
// YFSafeObjectViewController.m
// BigShow1949
//
// Created by apple on 2018/4/25.
//
#import "YFSafeObjectViewController.h"
@interface YFSafeObjectViewController ()
@end
@implementation YFSafeObjectViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//
NSArray *arr = @[@"1",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2"];
NSMutableArray *tableArray = [[NSMutableArray alloc] initWithArray:arr];
NSLog(@"arr====%@ tableArray====%@",arr[100],tableArray[100]);
NSLog(@"arr====%@ tableArray====%@",[arr objectAtIndex:100],tableArray[100]);
//
NSDictionary *dict = @{@"name":@"",@"age":@"20"};
NSMutableDictionary *tableDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
NSLog(@"dict---name====%@ tableDict---age====%@",[dict objectForKey:@"name"],[tableDict objectForKey:@"age"]);
NSLog(@"dict---name====%@ tableDict---age====%@",[dict objectForKey:@"name"],[tableDict objectForKey:@"age"]);
//
NSMutableString *tableString = [[NSMutableString alloc] initWithFormat:@""];
NSLog(@"%@",[tableString substringFromIndex:100]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/YFSafeObjectViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 374 |
```objective-c
//
// NSObject+ImpChangeTool.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import "NSObject+ImpChangeTool.h"
#import <objc/runtime.h>
@implementation NSObject (ImpChangeTool)
+ (void)SwizzlingMethod:(NSString *)systemMethodString systemClassString:(NSString *)systemClassString toSafeMethodString:(NSString *)safeMethodString targetClassString:(NSString *)targetClassString{
//IMP
Method sysMethod = class_getInstanceMethod(NSClassFromString(systemClassString), NSSelectorFromString(systemMethodString));
//IMP
Method safeMethod = class_getInstanceMethod(NSClassFromString(targetClassString), NSSelectorFromString(safeMethodString));
//IMP
method_exchangeImplementations(safeMethod,sysMethod);
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSObject+ImpChangeTool.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 176 |
```objective-c
//
// NSObject+Swizzling.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSObject (Swizzling)
+ (void)exchangeInstanceMethodWithSelfClass:(Class)selfClass
originalSelector:(SEL)originalSelector
swizzledSelector:(SEL)swizzledSelector;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSObject+Swizzling.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 87 |
```objective-c
//
// NSObject+ImpChangeTool.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSObject (ImpChangeTool)
/**
* NSString
*
* @param systemMethodString string
* @param systemClassString string
* @param safeMethodString hookstring
* @param targetClassString string
*/
+ (void)SwizzlingMethod:(NSString *)systemMethodString systemClassString:(NSString *)systemClassString toSafeMethodString:(NSString *)safeMethodString targetClassString:(NSString *)targetClassString;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSObject+ImpChangeTool.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 140 |
```objective-c
//
// NSMutableString+Safe.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import "NSMutableString+Safe.h"
#import <objc/runtime.h>
#import "NSObject+Swizzling.h"
#import "NSMutableString+Safe.h"
@implementation NSMutableString (Safe)
#pragma mark --- init method
+ (void)load {
//
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// substringFromIndex:
NSString *tmpSubFromStr = @"substringFromIndex:";
NSString *tmpSafeSubFromStr = @"safeMutable_substringFromIndex:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSCFString")
originalSelector:NSSelectorFromString(tmpSubFromStr) swizzledSelector:NSSelectorFromString(tmpSafeSubFromStr)];
// substringToIndex:
NSString *tmpSubToStr = @"substringToIndex:";
NSString *tmpSafeSubToStr = @"safeMutable_substringToIndex:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSCFString")
originalSelector:NSSelectorFromString(tmpSubToStr) swizzledSelector:NSSelectorFromString(tmpSafeSubToStr)];
// substringWithRange:
NSString *tmpSubRangeStr = @"substringWithRange:";
NSString *tmpSafeSubRangeStr = @"safeMutable_substringWithRange:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSCFString")
originalSelector:NSSelectorFromString(tmpSubRangeStr) swizzledSelector:NSSelectorFromString(tmpSafeSubRangeStr)];
// rangeOfString:options:range:locale:
NSString *tmpRangeOfStr = @"rangeOfString:options:range:locale:";
NSString *tmpSafeRangeOfStr = @"safeMutable_rangeOfString:options:range:locale:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSCFString")
originalSelector:NSSelectorFromString(tmpRangeOfStr) swizzledSelector:NSSelectorFromString(tmpSafeRangeOfStr)];
// appendString
NSString *tmpAppendStr = @"appendString:";
NSString *tmpSafeAppendStr = @"safeMutable_appendString:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSCFString")
originalSelector:NSSelectorFromString(tmpAppendStr) swizzledSelector:NSSelectorFromString(tmpSafeAppendStr)];
});
}
#pragma mark --- implement method
/**************************************** substringFromIndex: ***********************************/
/**
from __NSCFString
@param from
@return
*/
- (NSString *)safeMutable_substringFromIndex:(NSUInteger)from {
if (from > self.length ) {
return nil;
}
return [self safeMutable_substringFromIndex:from];
}
/**************************************** substringFromIndex: ***********************************/
/**
to __NSCFString
@param to
@return
*/
- (NSString *)safeMutable_substringToIndex:(NSUInteger)to {
if (to > self.length ) {
return nil;
}
return [self safeMutable_substringToIndex:to];
}
/*********************************** rangeOfString:options:range:locale: ***************************/
/**
__NSCFString
@param searchString
@param mask
@param rangeOfReceiverToSearch
@param locale
@return
*/
- (NSRange)safeMutable_rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale {
if (!searchString) {
searchString = self;
}
if (rangeOfReceiverToSearch.location > self.length) {
rangeOfReceiverToSearch = NSMakeRange(0, self.length);
}
if (rangeOfReceiverToSearch.length > self.length) {
rangeOfReceiverToSearch = NSMakeRange(0, self.length);
}
if ((rangeOfReceiverToSearch.location + rangeOfReceiverToSearch.length) > self.length) {
rangeOfReceiverToSearch = NSMakeRange(0, self.length);
}
return [self safeMutable_rangeOfString:searchString options:mask range:rangeOfReceiverToSearch locale:locale];
}
/*********************************** substringWithRange: ***************************/
/**
__NSCFString
@param range
@return
*/
- (NSString *)safeMutable_substringWithRange:(NSRange)range {
if (range.location > self.length) {
return nil;
}
if (range.length > self.length) {
return nil;
}
if ((range.location + range.length) > self.length) {
return nil;
}
return [self safeMutable_substringWithRange:range];
}
/*********************************** safeMutable_appendString: ***************************/
/**
__NSCFString
@param aString
*/
- (void)safeMutable_appendString:(NSString *)aString {
if (!aString) {
return;
}
return [self safeMutable_appendString:aString];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableString+Safe.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 1,081 |
```objective-c
//
// NSMutableDictionary+Safe.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <objc/runtime.h>
#import "NSObject+Swizzling.h"
#import "NSMutableDictionary+Safe.h"
@implementation NSMutableDictionary (Safe)
#pragma mark --- init method
+ (void)load {
//
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// removeObjectForKey:
NSString *tmpRemoveStr = @"removeObjectForKey:";
NSString *tmpSafeRemoveStr = @"safeMutable_removeObjectForKey:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSDictionaryM")
originalSelector:NSSelectorFromString(tmpRemoveStr) swizzledSelector:NSSelectorFromString(tmpSafeRemoveStr)];
// setObject:forKey:
NSString *tmpSetStr = @"setObject:forKey:";
NSString *tmpSafeSetRemoveStr = @"safeMutable_setObject:forKey:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSDictionaryM")
originalSelector:NSSelectorFromString(tmpSetStr) swizzledSelector:NSSelectorFromString(tmpSafeSetRemoveStr)];
});
}
#pragma mark --- implement method
/**
akey
@param aKey key
*/
- (void)safeMutable_removeObjectForKey:(id<NSCopying>)aKey {
if (!aKey) {
return;
}
[self safeMutable_removeObjectForKey:aKey];
}
/**
NSMutableDictionary
@param anObject
@param aKey
*/
- (void)safeMutable_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
if (!anObject) {
return;
}
if (!aKey) {
return;
}
return [self safeMutable_setObject:anObject forKey:aKey];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableDictionary+Safe.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 401 |
```objective-c
//
// NSDictionary+Safe.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import "NSDictionary+Safe.h"
#import <objc/runtime.h>
#import "NSObject+ImpChangeTool.h"
@implementation NSDictionary (Safe)
+ (void)load{
[self SwizzlingMethod:@"initWithObjects:forKeys:count:" systemClassString:@"__NSPlaceholderDictionary" toSafeMethodString:@"initWithObjects_st:forKeys:count:" targetClassString:@"NSDictionary"];
}
-(instancetype)initWithObjects_st:(id *)objects forKeys:(id<NSCopying> *)keys count:(NSUInteger)count {
NSUInteger rightCount = 0;
for (NSUInteger i = 0; i < count; i++) {
if (!(keys[i] && objects[i])) {
break;
}else{
rightCount++;
}
}
self = [self initWithObjects_st:objects forKeys:keys count:rightCount];
return self;
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSDictionary+Safe.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 212 |
```objective-c
//
// SafeObject.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#ifndef SafeObject_h
#define SafeObject_h
#import "NSArray+Safe.h"
#import "NSDictionary+Safe.h"
#import "NSMutableArray+Safe.h"
#import "NSMutableDictionary+Safe.h"
#import "NSMutableString+Safe.h"
#import "NSObject+ImpChangeTool.h"
#import "NSObject+Swizzling.h"
#endif /* SafeObject_h */
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/SafeObject.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 102 |
```objective-c
//
// NSDictionary+Safe.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (Safe)
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSDictionary+Safe.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 47 |
```objective-c
//
// NSObject+Swizzling.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <objc/runtime.h>
#import "NSObject+Swizzling.h"
@implementation NSObject (Swizzling)
+ (void)exchangeInstanceMethodWithSelfClass:(Class)selfClass
originalSelector:(SEL)originalSelector
swizzledSelector:(SEL)swizzledSelector {
Method originalMethod = class_getInstanceMethod(selfClass, originalSelector);
Method swizzledMethod = class_getInstanceMethod(selfClass, swizzledSelector);
BOOL didAddMethod = class_addMethod(selfClass,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(selfClass,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSObject+Swizzling.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 221 |
```objective-c
//
// NSMutableDictionary+Safe.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSMutableDictionary (Safe)
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableDictionary+Safe.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 47 |
```objective-c
//
// NSMutableString+Safe.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSMutableString (Safe)
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableString+Safe.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 49 |
```objective-c
//
// NSArray+Safe.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <objc/runtime.h>
#import "NSArray+Safe.h"
#import "NSObject+Swizzling.h"
@implementation NSArray (Safe)
#pragma mark --- init method
+ (void)load {
//
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// objectAtIndex
NSString *tmpStr = @"objectAtIndex:";
NSString *tmpFirstStr = @"safe_ZeroObjectAtIndex:";
NSString *tmpThreeStr = @"safe_objectAtIndex:";
NSString *tmpSecondStr = @"safe_singleObjectAtIndex:";
// objectAtIndexedSubscript
NSString *tmpSubscriptStr = @"objectAtIndexedSubscript:";
NSString *tmpSecondSubscriptStr = @"safe_objectAtIndexedSubscript:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArray0")
originalSelector:NSSelectorFromString(tmpStr) swizzledSelector:NSSelectorFromString(tmpFirstStr)];
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSSingleObjectArrayI")
originalSelector:NSSelectorFromString(tmpStr) swizzledSelector:NSSelectorFromString(tmpSecondStr)];
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayI")
originalSelector:NSSelectorFromString(tmpStr) swizzledSelector:NSSelectorFromString(tmpThreeStr)];
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayI")
originalSelector:NSSelectorFromString(tmpSubscriptStr) swizzledSelector:NSSelectorFromString(tmpSecondSubscriptStr)];
});
}
#pragma mark --- implement method
/**
NSArray index __NSArrayI
@param index index
@return
*/
- (id)safe_objectAtIndex:(NSUInteger)index {
if (index >= self.count){
return nil;
}
return [self safe_objectAtIndex:index];
}
/**
NSArray index __NSSingleObjectArrayI
@param index index
@return
*/
- (id)safe_singleObjectAtIndex:(NSUInteger)index {
if (index >= self.count){
return nil;
}
return [self safe_singleObjectAtIndex:index];
}
/**
NSArray index __NSArray0
@param index index
@return
*/
- (id)safe_ZeroObjectAtIndex:(NSUInteger)index {
if (index >= self.count){
return nil;
}
return [self safe_ZeroObjectAtIndex:index];
}
/**
NSArray index __NSArrayI
@param idx idx
@return
*/
- (id)safe_objectAtIndexedSubscript:(NSUInteger)idx {
if (idx >= self.count){
return nil;
}
return [self safe_objectAtIndexedSubscript:idx];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSArray+Safe.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 603 |
```objective-c
//
// NSMutableArray+Safe.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSMutableArray (Safe)
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableArray+Safe.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 47 |
```objective-c
//
// NSArray+Safe.h
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <Foundation/Foundation.h>
@interface NSArray (Safe)
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSArray+Safe.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 47 |
```objective-c
//
// UIButton+TitlePosition.h
// test
//
// Created by apple on 2018/4/4.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger,YFTitleStyle) {
YFTitleStyleTitleOnly = 1, //
YFTitleStyleImgOnly, //
YFTitleStyleLeft, //
YFTitleStyleRight, //
YFTitleStyleTop, //
YFTitleStyleBottom //
};
@interface UIButton (TitlePosition)
//buttonimagetitle/attributedtitle
- (void)layoutTitleWithStyle:(YFTitleStyle)style imageTitleSpace:(CGFloat)space;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/UIButton/UIButton+TitlePosition.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 146 |
```objective-c
//
// NSMutableArray+Safe.m
// SafeObjectCrash
//
// Created by lujh on 2018/4/18.
//
#import <objc/runtime.h>
#import "NSObject+Swizzling.h"
#import "NSMutableArray+Safe.h"
@implementation NSMutableArray (Safe)
#pragma mark --- init method
+ (void)load {
//
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// objectAtIndex:
NSString *tmpGetStr = @"objectAtIndex:";
NSString *tmpSafeGetStr = @"safeMutable_objectAtIndex:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpGetStr) swizzledSelector:NSSelectorFromString(tmpSafeGetStr)];
// removeObjectsInRange:
NSString *tmpRemoveStr = @"removeObjectsInRange:";
NSString *tmpSafeRemoveStr = @"safeMutable_removeObjectsInRange:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpRemoveStr) swizzledSelector:NSSelectorFromString(tmpSafeRemoveStr)];
// insertObject:atIndex:
NSString *tmpInsertStr = @"insertObject:atIndex:";
NSString *tmpSafeInsertStr = @"safeMutable_insertObject:atIndex:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpInsertStr) swizzledSelector:NSSelectorFromString(tmpSafeInsertStr)];
// removeObject:inRange:
NSString *tmpRemoveRangeStr = @"removeObject:inRange:";
NSString *tmpSafeRemoveRangeStr = @"safeMutable_removeObject:inRange:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpRemoveRangeStr) swizzledSelector:NSSelectorFromString(tmpSafeRemoveRangeStr)];
// objectAtIndexedSubscript
NSString *tmpSubscriptStr = @"objectAtIndexedSubscript:";
NSString *tmpSecondSubscriptStr = @"safeMutable_objectAtIndexedSubscript:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpSubscriptStr) swizzledSelector:NSSelectorFromString(tmpSecondSubscriptStr)];
// replaceObjectAtIndex:withObject:
NSString *tmpReplaceStr = @"replaceObjectAtIndex:withObject:";
NSString *tmpSafeReplaceStr = @"safeMutable_replaceObjectAtIndex:withObject:";
[NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSArrayM")
originalSelector:NSSelectorFromString(tmpReplaceStr) swizzledSelector:NSSelectorFromString(tmpSafeReplaceStr)];
});
}
#pragma mark --- implement method
/**
NSArray index
@param index index
@return
*/
- (id)safeMutable_objectAtIndex:(NSUInteger)index {
if (index >= self.count){
return nil;
}
return [self safeMutable_objectAtIndex:index];
}
/**
NSMutableArray index
@param range
*/
- (void)safeMutable_removeObjectsInRange:(NSRange)range {
if (range.location > self.count) {
return;
}
if (range.length > self.count) {
return;
}
if ((range.location + range.length) > self.count) {
return;
}
return [self safeMutable_removeObjectsInRange:range];
}
/**
range anObject
@param anObject anObject
@param range
*/
- (void)safeMutable_removeObject:(id)anObject inRange:(NSRange)range {
if (range.location > self.count) {
return;
}
if (range.length > self.count) {
return;
}
if ((range.location + range.length) > self.count) {
return;
}
if (!anObject){
return;
}
return [self safeMutable_removeObject:anObject inRange:range];
}
/**
NSMutableArray index
@param anObject
@param index index
*/
- (void)safeMutable_insertObject:(id)anObject atIndex:(NSUInteger)index {
if (index > self.count) {
return;
}
if (!anObject){
return;
}
[self safeMutable_insertObject:anObject atIndex:index];
}
/**
NSArray index __NSArrayI
@param idx idx
@return
*/
- (id)safeMutable_objectAtIndexedSubscript:(NSUInteger)idx {
if (idx >= self.count){
return nil;
}
return [self safeMutable_objectAtIndexedSubscript:idx];
}
/**
index anObject
@param index index
@param anObject
*/
- (void)safeMutable_replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
if (index >= self.count) {
return;
}
[self safeMutable_replaceObjectAtIndex:index withObject:anObject];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/SafeTool/SafeObject/NSMutableArray+Safe.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 1,074 |
```objective-c
//
// YFButtonCategoryViewController.h
// BigShow1949
//
// Created by apple on 2018/4/4.
//
#import <UIKit/UIKit.h>
@interface YFButtonCategoryViewController : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/UIButton/YFButtonCategoryViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 51 |
```objective-c
//
// YFButtonCategoryViewController.m
// BigShow1949
//
// Created by apple on 2018/4/4.
//
#import "YFButtonCategoryViewController.h"
#import "UIButton+TitlePosition.h"
@interface YFButtonCategoryViewController ()
@end
@implementation YFButtonCategoryViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
{
UIButton *btn = [[UIButton alloc] init];
btn.frame = CGRectMake(20, 100, 100, 100);
[btn setTitle:@"title" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"placeholder30"] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:btn];
[btn layoutTitleWithStyle:YFTitleStyleBottom imageTitleSpace:10];
}
{
UIButton *btn = [[UIButton alloc] init];
btn.frame = CGRectMake(150, 100, 100, 100);
[btn setTitle:@"title" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"placeholder30"] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:btn];
[btn layoutTitleWithStyle:YFTitleStyleTop imageTitleSpace:10];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/UIButton/YFButtonCategoryViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 364 |
```objective-c
//
// YFColorViewController.h
// BigShow1949
//
// Created by zhht01 on 16/3/31.
//
#import <UIKit/UIKit.h>
@interface YFColorViewController : UIViewController
// rgb
@property (weak, nonatomic) IBOutlet UITextField *r;
@property (weak, nonatomic) IBOutlet UITextField *g;
@property (weak, nonatomic) IBOutlet UITextField *b;
- (IBAction)rgbToHexBtn:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *rgbToHexLabel;
@property (weak, nonatomic) IBOutlet UIView *rgbToHexView;
// hex
@property (weak, nonatomic) IBOutlet UITextField *hexField;
@property (weak, nonatomic) IBOutlet UILabel *hexToRgbLabel;
- (IBAction)hexToRgbBtn:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *hexToRgbView;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Color/YFColorViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 181 |
```objective-c
//
// UIButton+TitlePosition.m
// test
//
// Created by apple on 2018/4/4.
//
#import "UIButton+TitlePosition.h"
@implementation UIButton (TitlePosition)
- (void)layoutTitleWithStyle:(YFTitleStyle)style imageTitleSpace:(CGFloat)space {
// self.backgroundColor = [UIColor cyanColor];
/**
* titleEdgeInsetstitleinsettableViewcontentInset
* titlebuttonimage
* imagelabelimagebuttonlabeltitlebuttonimage
*/
// 1. imageViewtitleLabel
CGFloat imageWith = self.imageView.frame.size.width;
CGFloat imageHeight = self.imageView.frame.size.height;
CGFloat labelWidth = 0.0;
CGFloat labelHeight = 0.0;
if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
// iOS8titleLabelsize0
labelWidth = self.titleLabel.intrinsicContentSize.width;
labelHeight = self.titleLabel.intrinsicContentSize.height;
} else {
labelWidth = self.titleLabel.frame.size.width;
labelHeight = self.titleLabel.frame.size.height;
}
// 2. imageEdgeInsetslabelEdgeInsets
UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
// 3. stylespaceimageEdgeInsetslabelEdgeInsets
switch (style) {
case YFTitleStyleBottom:
{
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);
}
break;
case YFTitleStyleRight:
{
imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);
}
break;
case YFTitleStyleTop:
{
imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);
}
break;
case YFTitleStyleLeft:
{
imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0);
}
break;
default:
break;
}
// 4.
self.titleEdgeInsets = labelEdgeInsets;
self.imageEdgeInsets = imageEdgeInsets;
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/UIButton/UIButton+TitlePosition.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 595 |
```objective-c
//
// YFColorViewController.m
// BigShow1949
//
// Created by zhht01 on 16/3/31.
//
#import "YFColorViewController.h"
#import "UIColor+Extension.h"
@interface YFColorViewController ()
@property (nonatomic, strong) UIScrollView *scrollView;
@end
@implementation YFColorViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTap)];
[self.view addGestureRecognizer:tap];
// self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, YFScreen.width, YFScreen.height)];
// [];
// // color2
// UIColor *color1 = YFColor(223, 1, 144);
// UIColor *color2 = [UIColor colorWithHexString:@"#DF0190" alpha:1];
//
//
// NSString *str1 = [UIColor colorToHexStringWithColor:color1];
// NSLog(@"str1 = %@", str1);
//
// NSString *str2 = [UIColor colorToRGBStringWithColor:color2];
//
// NSLog(@"str2 = %@", str2);
//
// UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
// btn.backgroundColor = color1;
// [self.view addSubview:btn];
//
//
// UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(100, 220, 100, 100)];
// btn2.backgroundColor = color2;
// [self.view addSubview:btn2];
//
//
// NSString *rgbStr = [UIColor colorToRGBStringWithHexString:@"#DF0190"];
// NSLog(@"rgbStr = %@", rgbStr);
//
// NSString *hexStr = [UIColor colorToHexStringWithRGBRed:223 green:1 blue:144];
// NSLog(@"hexStr = %@", hexStr);
}
- (void)backgroundTap {
[self.view endEditing:YES];
}
- (IBAction)rgbToHexBtn:(id)sender {
UIColor *color = [UIColor colorWithRGBRed:self.r.text.floatValue green:self.g.text.floatValue blue:self.b.text.floatValue];
self.rgbToHexView.backgroundColor = color;
//
self.rgbToHexLabel.text = [UIColor colorToHexStringWithColor:color];
}
- (IBAction)hexToRgbBtn:(id)sender {
UIColor *color = [UIColor colorWithHexString:self.hexField.text];
self.hexToRgbView.backgroundColor = color;
//
//[UIColor colorToRGBStringWithColor:color];
self.hexToRgbLabel.text = [UIColor colorToRGBStringWithHexString:self.hexField.text];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Color/YFColorViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 595 |
```objective-c
//
// UIColor+Extension.h
// AiPark
//
// Created by zhht01 on 16/3/31.
//
#import <UIKit/UIKit.h>
@interface UIColor (Extension)
#define RGBA_COLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define RGB_COLOR(R, G, B) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:1.0f]
/**
*
*
* @param color : @#123456 @0X123456@0x123456 @123456
* @param alpha : 1
*/
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;
+ (UIColor *)colorWithHexString:(NSString *)hexString;
/**
* RGB
*
* :255
*/
+ (UIColor *)colorWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;
+ (UIColor *)colorWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue;
/**
* 16
*
* : #123456
*/
+ (NSString *)colorToHexStringWithColor:(UIColor *)color;
/**
* RGB
*
* : 192,192,222
*/
+ (NSString *)colorToRGBStringWithColor:(UIColor *)color;
/**
* 16 RGB
*
* @param hexString : @#123456 @0X123456@0x123456 @123456
*
* : RGB:192,192,222
*/
+ (NSString *)colorToRGBStringWithHexString:(NSString *)hexString;
/**
* RGB 16
*
* : #123456
*/
+ (NSString *)colorToHexStringWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue;;
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Color/UIColor+Extension.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 452 |
```objective-c
//
// UIColor+Extension.m
// AiPark
//
// Created by zhht01 on 16/3/31.
//
#import "UIColor+Extension.h"
@implementation UIColor (Extension)
#pragma mark -
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha
{
NSArray *array = [self rgbArrayWithHexString:hexString];
return [self colorWithRGBRed:[array[0] floatValue] green:[array[1] floatValue] blue:[array[2] floatValue] alpha:alpha];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
return [self colorWithHexString:hexString alpha:1.0f];
}
+ (UIColor *)colorWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha {
return [UIColor colorWithRed:((CGFloat)red / 255.0f) green:((CGFloat)green / 255.0f) blue:((float)blue / 255.0f) alpha:alpha];
}
+ (UIColor *)colorWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
return [self colorWithRGBRed:red green:green blue:blue alpha:1];
}
#pragma mark - /
+ (NSString *)colorToHexStringWithColor:(UIColor *)color
{
const CGFloat *cs=CGColorGetComponents(color.CGColor);
NSString *r = [self toHex:cs[0]*255];
NSString *g = [self toHex:cs[1]*255];
NSString *b = [self toHex:cs[2]*255];
return [NSString stringWithFormat:@"#%@%@%@",r,g,b];
}
+ (NSString *)colorToRGBStringWithColor:(UIColor *)color { // rgb
const CGFloat *cs=CGColorGetComponents(color.CGColor);
int r = cs[0]*255;
int g = cs[1]*255;
int b = cs[2]*255;
return [NSString stringWithFormat:@"RGB:%d,%d,%d",r,g,b];
}
+ (NSString *)colorToRGBStringWithHexString:(NSString *)hexString {
NSArray *array = [self rgbArrayWithHexString:hexString];
return [NSString stringWithFormat:@"RGB:%d,%d,%d", [array[0] integerValue], [array[1] integerValue], [array[2] integerValue]];
}
+ (NSString *)colorToHexStringWithRGBRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
NSString *rStr = [self toHex:red];
NSString *gStr = [self toHex:green];
NSString *bStr = [self toHex:blue];
return [NSString stringWithFormat:@"#%@%@%@", rStr, gStr, bStr];
}
#pragma mark - private method
// 16 10 :
+ (NSString *)toRGB:(NSString *)tmpid{ //
//
NSString *firstStr = [tmpid substringToIndex:1];
int first;
if ([firstStr isEqualToString:@"A"]) {
first = 10;
}else if ([firstStr isEqualToString:@"B"]) {
first = 11;
}else if ([firstStr isEqualToString:@"C"]) {
first = 12;
}else if ([firstStr isEqualToString:@"D"]) {
first = 13;
}else if ([firstStr isEqualToString:@"E"]) {
first = 14;
}else if ([firstStr isEqualToString:@"F"]) {
first = 15;
}else {
first = firstStr.intValue;
}
//
NSString *secondStr = [tmpid substringFromIndex:1];
int second;
if ([secondStr isEqualToString:@"A"]) {
second = 10;
}else if ([secondStr isEqualToString:@"B"]) {
second = 11;
}else if ([secondStr isEqualToString:@"C"]) {
second = 12;
}else if ([secondStr isEqualToString:@"D"]) {
second = 13;
}else if ([secondStr isEqualToString:@"E"]) {
second = 14;
}else if ([secondStr isEqualToString:@"F"]) {
second = 15;
}else {
second = secondStr.intValue;
}
// NSLog(@"first = %d, second = %d", first, second);
int result = first * 16 + second;
return [NSString stringWithFormat:@"%d", result];
}
// int 16 (16) :0
+ (NSString *)toHex:(int)tmpid
{
NSString *endtmp=@"";
NSString *nLetterValue;
NSString *nStrat;
int ttmpig=tmpid%16;
int tmp=tmpid/16;
switch (ttmpig)
{
case 10:
nLetterValue =@"A";break;
case 11:
nLetterValue =@"B";break;
case 12:
nLetterValue =@"C";break;
case 13:
nLetterValue =@"D";break;
case 14:
nLetterValue =@"E";break;
case 15:
nLetterValue =@"F";break;
default:nLetterValue=[[NSString alloc]initWithFormat:@"%i",ttmpig];
}
switch (tmp)
{
case 10:
nStrat =@"A";break;
case 11:
nStrat =@"B";break;
case 12:
nStrat =@"C";break;
case 13:
nStrat =@"D";break;
case 14:
nStrat =@"E";break;
case 15:
nStrat =@"F";break;
default:nStrat=[[NSString alloc]initWithFormat:@"%i",tmp];
}
endtmp=[[NSString alloc]initWithFormat:@"%@%@",nStrat,nLetterValue];
return endtmp;
}
+ (NSString *)filterHexString:(NSString *)hexString { // hexString, nil
if ([hexString length] < 6)
{
return nil;
}
// strip 0X if it appears
//0X2
if ([hexString hasPrefix:@"0X"])
{
hexString = [hexString substringFromIndex:2];
}
//0x2
if ([hexString hasPrefix:@"0x"])
{
hexString = [hexString substringFromIndex:2];
}
//#1
if ([hexString hasPrefix:@"#"])
{
hexString = [hexString substringFromIndex:1];
}
if ([hexString length] != 6)
{
return nil;
}
return hexString;
}
/**
* 16(), RGB,
*
* @param hexString : @#123456 @0X123456@0x123456 @123456
*
*/
+ (NSArray<NSString *> *)rgbArrayWithHexString:(NSString *)hexString {
//
NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
cString = [self filterHexString:cString];
if (!cString) { // cString
return nil;
}
// 16
NSRange range;
range.location = 0;
range.length = 2;
// r @"DF" --> @"223"
NSString *rString = [self toRGB:[cString substringWithRange:range]];
//g
range.location = 2;
NSString *gString = [self toRGB:[cString substringWithRange:range]];
//b
range.location = 4;
NSString *bString = [self toRGB:[cString substringWithRange:range]];
//
// // Scan values // @"DF" --> 223
// unsigned int r, g, b;
// [[NSScanner scannerWithString:rString] scanHexInt:&r];
// [[NSScanner scannerWithString:gString] scanHexInt:&g];
// [[NSScanner scannerWithString:bString] scanHexInt:&b];
NSArray *array = @[rString, gString, bString];
return array;
}
/**
* : color
*
*/
- (void)componentsWithColor:(UIColor *)color {
NSUInteger num = CGColorGetNumberOfComponents(color.CGColor);
const CGFloat *colorComponents = CGColorGetComponents(color.CGColor);
for (int i = 0; i < num; ++i) {
NSLog(@"color components %d: %f", i, colorComponents[i]);
}
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/11 - Tools(常用工具)/Color/UIColor+Extension.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 1,870 |
```objective-c
//
// YFButtonViewController.m
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import "YFButtonViewController.h"
@interface YFButtonViewController ()
@end
@implementation YFButtonViewController
- (void)viewDidLoad {
[super viewDidLoad];
//
[self setupDataArr:@[@[@"",@"YFMultipleClicksViewController"],
@[@"",@"YFAnimationCircleButtonVC"],
@[@"ape",@"YFBubbleMenuButtonViewController"],
@[@"",@"YFAllRoundButtonVC_UIStoryboard"],]];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/YFButtonViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 126 |
```objective-c
//
// YFButtonViewController.h
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import "BaseTableViewController.h"
@interface YFButtonViewController : BaseTableViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/YFButtonViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 53 |
```objective-c
//
// UIButton+touch.h
// LiqForDoctors
//
// Created by StriEver on 16/3/10.
//
#import <UIKit/UIKit.h>
#define defaultInterval .5 //
@interface UIButton (touch)
/***/
@property (nonatomic, assign) NSTimeInterval timeInterval;
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/MultipleClicks/UIButton+touch.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 66 |
```objective-c
//
// YFMultipleClicksViewController.h
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import <UIKit/UIKit.h>
@interface YFMultipleClicksViewController : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/MultipleClicks/YFMultipleClicksViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 54 |
```objective-c
//
// UIButton+touch.m
// LiqForDoctors
//
// Created by StriEver on 16/3/10.
//
#import "UIButton+touch.h"
#import <objc/runtime.h>
@interface UIButton()
/**bool UI*/
@property (nonatomic, assign) BOOL isIgnoreEvent;
@end
@implementation UIButton (touch)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL selA = @selector(sendAction:to:forEvent:);
SEL selB = @selector(mySendAction:to:forEvent:); // B
Method methodA = class_getInstanceMethod(self, selA);
Method methodB = class_getInstanceMethod(self, selB);
BOOL isAdd = class_addMethod(self, selA, method_getImplementation(methodB), method_getTypeEncoding(methodB));
if (isAdd) {
class_replaceMethod(self, selB, method_getImplementation(methodA), method_getTypeEncoding(methodA));
}else{
method_exchangeImplementations(methodA, methodB);
}
});
}
- (NSTimeInterval)timeInterval
{
return [objc_getAssociatedObject(self, _cmd) doubleValue];
}
- (void)setTimeInterval:(NSTimeInterval)timeInterval
{
objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
if ([NSStringFromClass(self.class) isEqualToString:@"UIButton"]) {
if (self.isIgnoreEvent) {
return;
}else {
self.timeInterval = self.timeInterval ==0 ?defaultInterval:self.timeInterval;
}
self.isIgnoreEvent = YES;
[self performSelector:@selector(setIsIgnoreEvent:) withObject:NO afterDelay:self.timeInterval];
}
[self mySendAction:action to:target forEvent:event];
}
- (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent{
NSLog(@"isIgnoreEvent = %d", isIgnoreEvent);
objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isIgnoreEvent{
return [objc_getAssociatedObject(self, _cmd) boolValue];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/MultipleClicks/UIButton+touch.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 507 |
```objective-c
//
// YFMultipleClicksViewController.m
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import "YFMultipleClicksViewController.h"
#import "UIButton+touch.h"
//#import "UIControl+ButtonClick.h"
@interface YFMultipleClicksViewController () {
NSInteger count;
}
@property (nonatomic, strong) UILabel *label;
@end
@implementation YFMultipleClicksViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
count = 0;
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
// btn.timeInterval = 2;
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//
self.label = [[UILabel alloc] initWithFrame:CGRectMake(50, 300, 200, 30)];
self.label.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:self.label];
}
- (void)btnClick:(UIButton *)button {
count++;
NSLog(@"%@", [NSString stringWithFormat:@"--- count = %zd", count]);
self.label.text = [NSString stringWithFormat:@"--- count = %zd", count];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/MultipleClicks/YFMultipleClicksViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 281 |
```objective-c
//
// YFBubbleMenuButtonViewController.m
// BigShow1949
//
// Created by zhht01 on 16/3/30.
//
#import "YFBubbleMenuButtonViewController.h"
#import "DWBubbleMenuButton.h"
@interface YFBubbleMenuButtonViewController ()
@end
@implementation YFBubbleMenuButtonViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// Create down menu button
UILabel *homeLabel = [self createHomeButtonView];
DWBubbleMenuButton *downMenuButton = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(100.f,
100.f,
homeLabel.frame.size.width,
homeLabel.frame.size.height)
expansionDirection:DirectionDown];
downMenuButton.homeButtonView = homeLabel;
// downMenuButton.backgroundColor = [UIColor blueColor];
[downMenuButton addButtons:[self createDemoButtonArray]];
[self.view addSubview:downMenuButton];
}
- (void)viewDidAppear:(BOOL)animated {
// // Create up menu button
// homeLabel = [self createHomeButtonView];
//
// DWBubbleMenuButton *upMenuView = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - homeLabel.frame.size.width - 20.f,
// self.view.frame.size.height - homeLabel.frame.size.height - 20.f,
// homeLabel.frame.size.width,
// homeLabel.frame.size.height)
// expansionDirection:DirectionUp];
// upMenuView.homeButtonView = homeLabel;
//
// [upMenuView addButtons:[self createDemoButtonArray]];
//
// [self.view addSubview:upMenuView];
}
- (UILabel *)createHomeButtonView {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, 40.f, 40.f)];
label.text = @"Tap";
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
label.layer.cornerRadius = label.frame.size.height / 2.f;
label.backgroundColor =[UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.5f];
label.clipsToBounds = YES;
return label;
}
- (NSArray *)createDemoButtonArray {
NSMutableArray *buttonsMutable = [[NSMutableArray alloc] init];
int i = 0;
for (NSString *title in @[@"A", @"B", @"C", @"D", @"E", @"F"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
button.frame = CGRectMake(0.f, 0.f, 30.f, 30.f);
button.layer.cornerRadius = button.frame.size.height / 2.f;
button.backgroundColor = [UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.5f];
button.clipsToBounds = YES;
button.tag = i++;
[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
[buttonsMutable addObject:button];
}
return [buttonsMutable copy];
}
- (void)test:(UIButton *)sender {
NSLog(@"Button tapped, tag: %ld", (long)sender.tag);
}
- (UIButton *)createButtonWithName:(NSString *)imageName {
UIButton *button = [[UIButton alloc] init];
[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[button sizeToFit];
[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/BubbleMenuButton/YFBubbleMenuButtonViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 766 |
```objective-c
//
// YFBubbleMenuButtonViewController.h
// BigShow1949
//
// Created by zhht01 on 16/3/30.
//
#import <UIKit/UIKit.h>
@interface YFBubbleMenuButtonViewController : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/BubbleMenuButton/YFBubbleMenuButtonViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 54 |
```objective-c
//
// DWBubbleMenuButton.h
// DWBubbleMenuButtonExample
//
// Created by Derrick Walker on 10/8/14.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, ExpansionDirection) {
DirectionLeft = 0,
DirectionRight,
DirectionUp,
DirectionDown
};
@class DWBubbleMenuButton;
@protocol DWBubbleMenuViewDelegate <NSObject>
@optional
- (void)bubbleMenuButtonWillExpand:(DWBubbleMenuButton *)expandableView;
- (void)bubbleMenuButtonDidExpand:(DWBubbleMenuButton *)expandableView;
- (void)bubbleMenuButtonWillCollapse:(DWBubbleMenuButton *)expandableView;
- (void)bubbleMenuButtonDidCollapse:(DWBubbleMenuButton *)expandableView;
@end
@interface DWBubbleMenuButton : UIView <UIGestureRecognizerDelegate>
@property (nonatomic, weak, readonly) NSArray *buttons;
@property (nonatomic, strong) UIView *homeButtonView;
@property (nonatomic, readonly) BOOL isCollapsed;
@property (nonatomic, weak) id <DWBubbleMenuViewDelegate> delegate;
// The direction in which the menu expands
@property (nonatomic) enum ExpansionDirection direction;
// Indicates whether the home button will animate it's touch highlighting, this is enabled by default
@property (nonatomic) BOOL animatedHighlighting;
// Indicates whether menu should collapse after a button selection, this is enabled by default
@property (nonatomic) BOOL collapseAfterSelection;
// The duration of the expand/collapse animation
@property (nonatomic) float animationDuration;
// The default alpha of the homeButtonView when not tapped
@property (nonatomic) float standbyAlpha;
// The highlighted alpha of the homeButtonView when tapped
@property (nonatomic) float highlightAlpha;
// The spacing between menu buttons when expanded
@property (nonatomic) float buttonSpacing;
// Initializers
- (id)initWithFrame:(CGRect)frame expansionDirection:(ExpansionDirection)direction;
// Public Methods
- (void)addButtons:(NSArray *)buttons;
- (void)addButton:(UIButton *)button;
- (void)showButtons;
- (void)dismissButtons;
@end
//
// path_to_url (cn) path_to_url (en)
// : Code4App.com
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/BubbleMenuButton/DWBubbleMenuButton.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 461 |
```objective-c
//
// YFAnimationCircleButtonVC.m
// BigShow1949
//
// Created by zhht01 on 16/1/22.
//
#import "YFAnimationCircleButtonVC.h"
#import "DeformationButton.h"
@interface YFAnimationCircleButtonVC (){
DeformationButton *deformationBtn;
}
@end
@implementation YFAnimationCircleButtonVC
- (UIColor *)getColor:(NSString *)hexColor
{
unsigned int red,green,blue;
NSRange range;
range.length = 2;
range.location = 0;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
range.location = 2;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
range.location = 4;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
deformationBtn = [[DeformationButton alloc]initWithFrame:CGRectMake(100, 100, 140, 36)];
deformationBtn.contentColor = [self getColor:@"52c332"];
deformationBtn.progressColor = [UIColor whiteColor];
[self.view addSubview:deformationBtn];
[deformationBtn.forDisplayButton setTitle:@"" forState:UIControlStateNormal];
[deformationBtn.forDisplayButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
[deformationBtn.forDisplayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[deformationBtn.forDisplayButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
[deformationBtn.forDisplayButton setImage:[UIImage imageNamed:@"logo_.png"] forState:UIControlStateNormal];
UIImage *bgImage = [UIImage imageNamed:@"button_bg.png"];
[deformationBtn.forDisplayButton setBackgroundImage:[bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)] forState:UIControlStateNormal];
[deformationBtn addTarget:self action:@selector(btnEvent) forControlEvents:UIControlEventTouchUpInside];
}
- (void)btnEvent{
NSLog(@"btnEvent");
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/YFAnimationCircleButtonVC.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 504 |
```objective-c
//
// MMMaterialDesignSpinner.m
// Pods
//
// Created by Michael Maxwell on 12/28/14.
//
//
#import "MMMaterialDesignSpinner.h"
static NSString *kMMRingStrokeAnimationKey = @"mmmaterialdesignspinner.stroke";
static NSString *kMMRingRotationAnimationKey = @"mmmaterialdesignspinner.rotation";
@interface MMMaterialDesignSpinner ()
@property (nonatomic, readonly) CAShapeLayer *progressLayer;
@property (nonatomic, readwrite) BOOL isAnimating;
@end
@implementation MMMaterialDesignSpinner
@synthesize progressLayer=_progressLayer;
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self initialize];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self initialize];
}
return self;
}
- (void)initialize {
_timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.layer addSublayer:self.progressLayer];
// See comment in resetAnimations on why this notification is used.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetAnimations) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)layoutSubviews {
[super layoutSubviews];
self.progressLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
[self updatePath];
}
- (void)tintColorDidChange {
[super tintColorDidChange];
self.progressLayer.strokeColor = self.tintColor.CGColor;
}
- (void)resetAnimations {
// If the app goes to the background, returning it to the foreground causes the animation to stop (even though it's not explicitly stopped by our code). Resetting the animation seems to kick it back into gear.
if (self.isAnimating) {
[self stopAnimating];
[self startAnimating];
}
}
- (void)setAnimating:(BOOL)animate {
(animate ? [self startAnimating] : [self stopAnimating]);
}
- (void)startAnimating {
if (self.isAnimating)
return;
CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"transform.rotation";
animation.duration = 4.f;
animation.fromValue = @(0.f);
animation.toValue = @(2 * M_PI);
animation.repeatCount = INFINITY;
[self.progressLayer addAnimation:animation forKey:kMMRingRotationAnimationKey];
CABasicAnimation *headAnimation = [CABasicAnimation animation];
headAnimation.keyPath = @"strokeStart";
headAnimation.duration = 1.f;
headAnimation.fromValue = @(0.f);
headAnimation.toValue = @(0.25f);
headAnimation.timingFunction = self.timingFunction;
CABasicAnimation *tailAnimation = [CABasicAnimation animation];
tailAnimation.keyPath = @"strokeEnd";
tailAnimation.duration = 1.f;
tailAnimation.fromValue = @(0.f);
tailAnimation.toValue = @(1.f);
tailAnimation.timingFunction = self.timingFunction;
CABasicAnimation *endHeadAnimation = [CABasicAnimation animation];
endHeadAnimation.keyPath = @"strokeStart";
endHeadAnimation.beginTime = 1.f;
endHeadAnimation.duration = 0.5f;
endHeadAnimation.fromValue = @(0.25f);
endHeadAnimation.toValue = @(1.f);
endHeadAnimation.timingFunction = self.timingFunction;
CABasicAnimation *endTailAnimation = [CABasicAnimation animation];
endTailAnimation.keyPath = @"strokeEnd";
endTailAnimation.beginTime = 1.f;
endTailAnimation.duration = 0.5f;
endTailAnimation.fromValue = @(1.f);
endTailAnimation.toValue = @(1.f);
endTailAnimation.timingFunction = self.timingFunction;
CAAnimationGroup *animations = [CAAnimationGroup animation];
[animations setDuration:1.5f];
[animations setAnimations:@[headAnimation, tailAnimation, endHeadAnimation, endTailAnimation]];
animations.repeatCount = INFINITY;
[self.progressLayer addAnimation:animations forKey:kMMRingStrokeAnimationKey];
self.isAnimating = true;
if (self.hidesWhenStopped) {
self.hidden = NO;
}
}
- (void)stopAnimating {
if (!self.isAnimating)
return;
[self.progressLayer removeAnimationForKey:kMMRingRotationAnimationKey];
[self.progressLayer removeAnimationForKey:kMMRingStrokeAnimationKey];
self.isAnimating = false;
if (self.hidesWhenStopped) {
self.hidden = YES;
}
}
#pragma mark - Private
- (void)updatePath {
CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
CGFloat radius = MIN(CGRectGetWidth(self.bounds) / 2, CGRectGetHeight(self.bounds) / 2) - self.progressLayer.lineWidth / 2;
CGFloat startAngle = (CGFloat)(0);
CGFloat endAngle = (CGFloat)(2*M_PI);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
self.progressLayer.path = path.CGPath;
self.progressLayer.strokeStart = 0.f;
self.progressLayer.strokeEnd = 0.f;
}
#pragma mark - Properties
- (CAShapeLayer *)progressLayer {
if (!_progressLayer) {
_progressLayer = [CAShapeLayer layer];
_progressLayer.strokeColor = self.tintColor.CGColor;
_progressLayer.fillColor = nil;
_progressLayer.lineWidth = 1.5f;
}
return _progressLayer;
}
- (BOOL)isAnimating {
return _isAnimating;
}
- (CGFloat)lineWidth {
return self.progressLayer.lineWidth;
}
- (void)setLineWidth:(CGFloat)lineWidth {
self.progressLayer.lineWidth = lineWidth;
[self updatePath];
}
- (void)setHidesWhenStopped:(BOOL)hidesWhenStopped {
_hidesWhenStopped = hidesWhenStopped;
self.hidden = !self.isAnimating && hidesWhenStopped;
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/MMMaterialDesignSpinner.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 1,356 |
```objective-c
//
// DeformationButton.h
// DeformationButton
//
// Created by LuciusLu on 15/3/16.
//
#import <UIKit/UIKit.h>
#import "MMMaterialDesignSpinner.h"
@interface DeformationButton : UIControl
@property(nonatomic, assign)BOOL isLoading;
@property(nonatomic, retain)MMMaterialDesignSpinner *spinnerView;
@property(nonatomic, retain)UIColor *contentColor;
@property(nonatomic, retain)UIColor *progressColor;
@property(nonatomic, retain)UIButton *forDisplayButton;
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/DeformationButton.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 107 |
```objective-c
//
// YFAnimationCircleButtonVC.h
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import <UIKit/UIKit.h>
@interface YFAnimationCircleButtonVC : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/YFAnimationCircleButtonVC.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 54 |
```objective-c
//
// DWBubbleMenuButton.m
// DWBubbleMenuButtonExample
//
// Created by Derrick Walker on 10/8/14.
//
#import "DWBubbleMenuButton.h"
#define kDefaultAnimationDuration 0.25f
@interface DWBubbleMenuButton ()
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;
@property (nonatomic, strong) NSMutableArray *buttonContainer;
@property (nonatomic, assign) CGRect originFrame;
@end
@implementation DWBubbleMenuButton
#pragma mark -
#pragma mark Public Methods
- (void)addButtons:(NSArray *)buttons {
assert(buttons != nil);
for (UIButton *button in buttons) {
[self addButton:button];
}
if (self.homeButtonView != nil) {
[self bringSubviewToFront:self.homeButtonView];
}
}
- (void)addButton:(UIButton *)button {
assert(button != nil);
if (_buttonContainer == nil) {
self.buttonContainer = [[NSMutableArray alloc] init];
}
if ([_buttonContainer containsObject:button] == false) {
[_buttonContainer addObject:button];
[self addSubview:button];
button.hidden = YES;
}
}
- (void)showButtons {
if ([self.delegate respondsToSelector:@selector(bubbleMenuButtonWillExpand:)]) {
[self.delegate bubbleMenuButtonWillExpand:self];
}
[self _prepareForButtonExpansion];
self.userInteractionEnabled = NO;
[CATransaction begin];
[CATransaction setAnimationDuration:_animationDuration];
[CATransaction setCompletionBlock:^{
for (UIButton *button in _buttonContainer) {
button.transform = CGAffineTransformIdentity;
}
if (self.delegate != nil) {
if ([self.delegate respondsToSelector:@selector(bubbleMenuButtonDidExpand:)]) {
[self.delegate bubbleMenuButtonDidExpand:self];
}
}
self.userInteractionEnabled = YES;
}];
NSArray *buttonContainer = _buttonContainer;
if (self.direction == DirectionUp || self.direction == DirectionLeft) {
buttonContainer = [self _reverseOrderFromArray:_buttonContainer];
}
for (int i = 0; i < buttonContainer.count; i++) {
int index = (int)buttonContainer.count - (i + 1);
UIButton *button = [buttonContainer objectAtIndex:index];
button.hidden = NO;
// position animation
CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
CGPoint originPosition = CGPointZero;
CGPoint finalPosition = CGPointZero;
switch (self.direction) {
case DirectionLeft:
originPosition = CGPointMake(self.frame.size.width - self.homeButtonView.frame.size.width, self.frame.size.height/2.f);
finalPosition = CGPointMake(self.frame.size.width - self.homeButtonView.frame.size.width - button.frame.size.width/2.f - self.buttonSpacing
- ((button.frame.size.width + self.buttonSpacing) * index),
self.frame.size.height/2.f);
break;
case DirectionRight:
originPosition = CGPointMake(self.homeButtonView.frame.size.width, self.frame.size.height/2.f);
finalPosition = CGPointMake(self.homeButtonView.frame.size.width + self.buttonSpacing + button.frame.size.width/2.f
+ ((button.frame.size.width + self.buttonSpacing) * index),
self.frame.size.height/2.f);
break;
case DirectionUp:
originPosition = CGPointMake(self.frame.size.width/2.f, self.frame.size.height - self.homeButtonView.frame.size.height);
finalPosition = CGPointMake(self.frame.size.width/2.f,
self.frame.size.height - self.homeButtonView.frame.size.height - self.buttonSpacing - button.frame.size.height/2.f
- ((button.frame.size.height + self.buttonSpacing) * index));
break;
case DirectionDown:
originPosition = CGPointMake(self.frame.size.width/2.f, self.homeButtonView.frame.size.height);
NSLog(@"originPosition = %@", NSStringFromCGPoint(originPosition));
finalPosition = CGPointMake(self.frame.size.width/2.f,
self.homeButtonView.frame.size.height + self.buttonSpacing + button.frame.size.height/2.f
+ ((button.frame.size.height + self.buttonSpacing) * index));
NSLog(@"finalPosition = %@", NSStringFromCGPoint(finalPosition));
NSLog(@"index = %zd, button.height = %f", index, button.frame.size.height);
break;
default:
break;
}
positionAnimation.duration = _animationDuration;
positionAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
positionAnimation.fromValue = [NSValue valueWithCGPoint:originPosition];
positionAnimation.toValue = [NSValue valueWithCGPoint:finalPosition];
positionAnimation.beginTime = CACurrentMediaTime() + (_animationDuration/(float)_buttonContainer.count * (float)i);
positionAnimation.fillMode = kCAFillModeForwards;
positionAnimation.removedOnCompletion = NO;
[button.layer addAnimation:positionAnimation forKey:@"positionAnimation"];
button.layer.position = finalPosition;
// scale animation
CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.duration = _animationDuration;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
scaleAnimation.fromValue = [NSNumber numberWithFloat:0.01f];
scaleAnimation.toValue = [NSNumber numberWithFloat:1.f];
scaleAnimation.beginTime = CACurrentMediaTime() + (_animationDuration/(float)_buttonContainer.count * (float)i) + 0.03f;
scaleAnimation.fillMode = kCAFillModeForwards;
scaleAnimation.removedOnCompletion = NO;
[button.layer addAnimation:scaleAnimation forKey:@"scaleAnimation"];
button.transform = CGAffineTransformMakeScale(0.01f, 0.01f);
}
[CATransaction commit];
_isCollapsed = NO;
}
- (void)dismissButtons {
if ([self.delegate respondsToSelector:@selector(bubbleMenuButtonWillCollapse:)]) {
[self.delegate bubbleMenuButtonWillCollapse:self];
}
self.userInteractionEnabled = NO;
[CATransaction begin];
[CATransaction setAnimationDuration:_animationDuration];
[CATransaction setCompletionBlock:^{
[self _finishCollapse];
for (UIButton *button in _buttonContainer) {
button.transform = CGAffineTransformIdentity;
button.hidden = YES;
}
if (self.delegate != nil) {
if ([self.delegate respondsToSelector:@selector(bubbleMenuButtonDidCollapse:)]) {
[self.delegate bubbleMenuButtonDidCollapse:self];
}
}
self.userInteractionEnabled = YES;
}];
int index = 0;
for (int i = (int)_buttonContainer.count - 1; i >= 0; i--) {
UIButton *button = [_buttonContainer objectAtIndex:i];
if (self.direction == DirectionDown || self.direction == DirectionRight) {
button = [_buttonContainer objectAtIndex:index];
}
// scale animation
CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.duration = _animationDuration;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
scaleAnimation.fromValue = [NSNumber numberWithFloat:1.f];
scaleAnimation.toValue = [NSNumber numberWithFloat:0.01f];
scaleAnimation.beginTime = CACurrentMediaTime() + (_animationDuration/(float)_buttonContainer.count * (float)index) + 0.03;
scaleAnimation.fillMode = kCAFillModeForwards;
scaleAnimation.removedOnCompletion = NO;
[button.layer addAnimation:scaleAnimation forKey:@"scaleAnimation"];
button.transform = CGAffineTransformMakeScale(1.f, 1.f);
// position animation
CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
CGPoint originPosition = button.layer.position;
CGPoint finalPosition = CGPointZero;
switch (self.direction) {
case DirectionLeft:
finalPosition = CGPointMake(self.frame.size.width - self.homeButtonView.frame.size.width, self.frame.size.height/2.f);
break;
case DirectionRight:
finalPosition = CGPointMake(self.homeButtonView.frame.size.width, self.frame.size.height/2.f);
break;
case DirectionUp:
finalPosition = CGPointMake(self.frame.size.width/2.f, self.frame.size.height - self.homeButtonView.frame.size.height);
break;
case DirectionDown:
finalPosition = CGPointMake(self.frame.size.width/2.f, self.homeButtonView.frame.size.height);
break;
default:
break;
}
positionAnimation.duration = _animationDuration;
positionAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
positionAnimation.fromValue = [NSValue valueWithCGPoint:originPosition];
positionAnimation.toValue = [NSValue valueWithCGPoint:finalPosition];
positionAnimation.beginTime = CACurrentMediaTime() + (_animationDuration/(float)_buttonContainer.count * (float)index);
positionAnimation.fillMode = kCAFillModeForwards;
positionAnimation.removedOnCompletion = NO;
[button.layer addAnimation:positionAnimation forKey:@"positionAnimation"];
button.layer.position = originPosition;
index++;
}
[CATransaction commit];
_isCollapsed = YES;
}
#pragma mark -
#pragma mark Private Methods
- (void)_defaultInit {
self.clipsToBounds = YES;
self.layer.masksToBounds = YES;
self.direction = DirectionUp;
self.animatedHighlighting = YES;
self.collapseAfterSelection = YES;
self.animationDuration = kDefaultAnimationDuration;
self.standbyAlpha = 1.f;
self.highlightAlpha = 0.45f;
self.originFrame = self.frame;
self.buttonSpacing = 20.f;
_isCollapsed = YES;
self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_handleTapGesture:)];
self.tapGestureRecognizer.cancelsTouchesInView = NO;
self.tapGestureRecognizer.delegate = self;
[self addGestureRecognizer:self.tapGestureRecognizer];
NSLog(@"frame = %@", NSStringFromCGRect(self.frame));
}
- (void)_handleTapGesture:(id)sender {
if (self.tapGestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint touchLocation = [self.tapGestureRecognizer locationOfTouch:0 inView:self];
if (_collapseAfterSelection && _isCollapsed == NO && CGRectContainsPoint(self.homeButtonView.frame, touchLocation) == false) {
[self dismissButtons];
}
}
}
- (void)_animateWithBlock:(void (^)(void))animationBlock {
[UIView transitionWithView:self
duration:kDefaultAnimationDuration
options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut
animations:animationBlock
completion:NULL];
}
- (void)_setTouchHighlighted:(BOOL)highlighted {
float alphaValue = highlighted ? _highlightAlpha : _standbyAlpha;
if (self.homeButtonView.alpha == alphaValue)
return;
if (_animatedHighlighting) {
[self _animateWithBlock:^{
if (self.homeButtonView != nil) {
self.homeButtonView.alpha = alphaValue;
}
}];
} else {
if (self.homeButtonView != nil) {
self.homeButtonView.alpha = alphaValue;
}
}
}
- (float)_combinedButtonHeight {
float height = 0;
for (UIButton *button in _buttonContainer) {
height += button.frame.size.height + self.buttonSpacing;
}
return height;
}
- (float)_combinedButtonWidth {
float width = 0;
for (UIButton *button in _buttonContainer) {
width += button.frame.size.width + self.buttonSpacing;
}
return width;
}
- (void)_prepareForButtonExpansion {
float buttonHeight = [self _combinedButtonHeight];
float buttonWidth = [self _combinedButtonWidth];
switch (self.direction) {
case DirectionUp:
{
self.homeButtonView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
CGRect frame = self.frame;
frame.origin.y -= buttonHeight;
frame.size.height += buttonHeight;
self.frame = frame;
}
break;
case DirectionDown:
{
self.homeButtonView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
CGRect frame = self.frame;
frame.size.height += buttonHeight;
self.frame = frame;
}
break;
case DirectionLeft:
{
self.homeButtonView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
CGRect frame = self.frame;
frame.origin.x -= buttonWidth;
frame.size.width += buttonWidth;
self.frame = frame;
}
break;
case DirectionRight:
{
self.homeButtonView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
CGRect frame = self.frame;
frame.size.width += buttonWidth;
self.frame = frame;
}
break;
default:
break;
}
}
- (void)_finishCollapse {
self.frame = _originFrame;
}
- (UIView *)_subviewForPoint:(CGPoint)point {
for (UIView *subview in self.subviews) {
if (CGRectContainsPoint(subview.frame, point)) {
return subview;
}
}
return self;
}
- (NSArray *)_reverseOrderFromArray:(NSArray *)array {
NSMutableArray *reverseArray = [NSMutableArray array];
for (int i = (int)array.count - 1; i >= 0; i--) {
[reverseArray addObject:[array objectAtIndex:i]];
}
return reverseArray;
}
#pragma mark -
#pragma mark Setters/Getters
- (void)setHomeButtonView:(UIView *)homeButtonView {
if (_homeButtonView != homeButtonView) {
_homeButtonView = homeButtonView;
}
if ([_homeButtonView isDescendantOfView:self] == NO) {
[self addSubview:_homeButtonView];
}
}
- (NSArray *)buttons {
return [_buttonContainer copy];
}
#pragma mark -
#pragma mark Touch Handling Methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
if (CGRectContainsPoint(self.homeButtonView.frame, [touch locationInView:self])) {
[self _setTouchHighlighted:YES];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
UITouch *touch = [touches anyObject];
[self _setTouchHighlighted:NO];
if (CGRectContainsPoint(self.homeButtonView.frame, [touch locationInView:self])) {
if (_isCollapsed) {
[self showButtons];
} else {
[self dismissButtons];
}
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self _setTouchHighlighted:NO];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
[self _setTouchHighlighted:CGRectContainsPoint(self.homeButtonView.frame, [touch locationInView:self])];
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView == self) {
if (_isCollapsed) {
return self;
} else {
return [self _subviewForPoint:point];
}
}
return hitView;
}
#pragma mark -
#pragma mark UIGestureRecognizer Delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldReceiveTouch:(UITouch *)touch {
CGPoint touchLocation = [touch locationInView:self];
if ([self _subviewForPoint:touchLocation] != self && _collapseAfterSelection) {
return YES;
}
return NO;
}
#pragma mark -
#pragma mark Lifecycle
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self _defaultInit];
}
return self;
}
- (id)initWithFrame:(CGRect)frame expansionDirection:(ExpansionDirection)direction {
self = [super initWithFrame:frame];
if (self) {
[self _defaultInit];
_direction = direction;
}
return self;
}
@end
//
// path_to_url (cn) path_to_url (en)
// : Code4App.com
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/BubbleMenuButton/DWBubbleMenuButton.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 3,631 |
```objective-c
//
// DeformationButton.m
// DeformationButton
//
// Created by LuciusLu on 15/3/16.
//
#import "DeformationButton.h"
@implementation DeformationButton{
CGFloat defaultW;
CGFloat defaultH;
CGFloat defaultR;
CGFloat scale;
UIView *bgView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initSetting];
}
return self;
}
- (void)initBtn{
self.forDisplayButton = [[UIButton alloc]initWithFrame:self.bounds];
self.forDisplayButton.userInteractionEnabled = NO;
[self addSubview:self.forDisplayButton];
}
-(CGRect)frame{
CGRect frame = [super frame];
// CGRectMake((SELF_WIDTH-286)/2+146, SELF_HEIGHT-84, 140, 36)
self.forDisplayButton.frame = frame;
return frame;
}
- (void)initSetting{
scale = 1.2;
bgView = [[UIView alloc]initWithFrame:self.bounds];
bgView.backgroundColor = [UIColor blueColor];
bgView.userInteractionEnabled = NO;
bgView.hidden = YES;
[self addSubview:bgView];
defaultW = bgView.frame.size.width;
defaultH = bgView.frame.size.height;
defaultR = bgView.layer.cornerRadius;
MMMaterialDesignSpinner *spinnerView = [[MMMaterialDesignSpinner alloc] initWithFrame:CGRectZero];
self.spinnerView = spinnerView;
self.spinnerView.bounds = CGRectMake(0, 0, defaultH*0.8, defaultH*0.8);
self.spinnerView.tintColor = [UIColor whiteColor];
self.spinnerView.lineWidth = 2;
self.spinnerView.center = CGPointMake(CGRectGetMidX(self.layer.bounds), CGRectGetMidY(self.layer.bounds));
self.spinnerView.translatesAutoresizingMaskIntoConstraints = NO;
self.spinnerView.userInteractionEnabled = NO;
[self addSubview:self.spinnerView];
[self addTarget:self action:@selector(loadingAction) forControlEvents:UIControlEventTouchUpInside];
[self initBtn];
}
-(void)setContentColor:(UIColor *)contentColor{
_contentColor = contentColor;
bgView.backgroundColor = contentColor;
}
-(void)setProgressColor:(UIColor *)progressColor{
_progressColor = progressColor;
self.spinnerView.tintColor = progressColor;
}
-(void)setIsLoading:(BOOL)isLoading{
_isLoading = isLoading;
if (_isLoading) {
[self startLoading];
}else{
[self stopLoading];
}
}
- (void)loadingAction{
if (self.isLoading) {
[self stopLoading];
}else{
[self startLoading];
}
}
- (void)startLoading{
_isLoading = YES;
bgView.hidden = NO;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = [NSNumber numberWithFloat:defaultR];
animation.toValue = [NSNumber numberWithFloat:defaultH*scale*0.5];
animation.duration = 0.2;
[bgView.layer setCornerRadius:defaultH*scale*0.5];
[bgView.layer addAnimation:animation forKey:@"cornerRadius"];
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
bgView.layer.bounds = CGRectMake(0, 0, defaultW*scale, defaultH*scale);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
bgView.layer.bounds = CGRectMake(0, 0, defaultH*scale, defaultH*scale);
self.forDisplayButton.transform = CGAffineTransformMakeScale(0, 0);
self.forDisplayButton.alpha = 0;
} completion:^(BOOL finished) {
self.forDisplayButton.hidden = YES;
[self.spinnerView startAnimating];
}];
}];
}
- (void)stopLoading{
[self.spinnerView stopAnimating];
self.forDisplayButton.hidden = NO;
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0 options:
UIViewAnimationOptionCurveLinear animations:^{
self.forDisplayButton.transform = CGAffineTransformMakeScale(1, 1);
self.forDisplayButton.alpha = 1;
} completion:^(BOOL finished) {
}];
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
bgView.layer.bounds = CGRectMake(0, 0, defaultW*scale, defaultH*scale);
} completion:^(BOOL finished) {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = [NSNumber numberWithFloat:bgView.layer.cornerRadius];
animation.toValue = [NSNumber numberWithFloat:defaultR];
animation.duration = 0.2;
[bgView.layer setCornerRadius:defaultR];
[bgView.layer addAnimation:animation forKey:@"cornerRadius"];
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
bgView.layer.bounds = CGRectMake(0, 0, defaultW, defaultH);
} completion:^(BOOL finished) {
bgView.hidden = YES;
_isLoading = NO;
}];
}];
}
-(void)setSelected:(BOOL)selected{
[super setSelected:selected];
[self.forDisplayButton setSelected:selected];
}
- (void)setHighlighted:(BOOL)highlighted{
[super setHighlighted:highlighted];
[self.forDisplayButton setHighlighted:highlighted];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/DeformationButton.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 1,305 |
```objective-c
//
// MMMaterialDesignSpinner.h
// Pods
//
// Created by Michael Maxwell on 12/28/14.
//
//
#import <UIKit/UIKit.h>
/**
* A control similar to iOS' UIActivityIndicatorView modeled after Google's Material Design Activity spinner.
*/
@interface MMMaterialDesignSpinner : UIView
/** Sets the line width of the spinner's circle. */
@property (nonatomic) CGFloat lineWidth;
/** Sets whether the view is hidden when not animating. */
@property (nonatomic) BOOL hidesWhenStopped;
/** Specifies the timing function to use for the control's animation. Defaults to kCAMediaTimingFunctionEaseInEaseOut */
@property (nonatomic, strong) CAMediaTimingFunction *timingFunction;
/** Property indicating whether the view is currently animating. */
@property (nonatomic, readonly) BOOL isAnimating;
/**
* Convenience function for starting & stopping animation with a boolean variable instead of explicit
* method calls.
*
* @param animate true to start animating, false to stop animating.
@note This method simply calls the startAnimating or stopAnimating methods based on the value of the animate parameter.
*/
- (void)setAnimating:(BOOL)animate;
/**
* Starts animation of the spinner.
*/
- (void)startAnimating;
/**
* Stops animation of the spinnner.
*/
- (void)stopAnimating;
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AnimationCircleButton/MMMaterialDesignSpinner.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 281 |
```objective-c
//
// Created by Alberto Pasca on 27/02/14.
//
#import "APRoundedButton.h"
#import <QuartzCore/QuartzCore.h>
@implementation APRoundedButton
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self makeCorner];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self makeCorner];
}
- (void)makeCorner {
UIRectCorner corners;
switch ( self.style )
{
case 0:
corners = UIRectCornerBottomLeft;
break;
case 1:
corners = UIRectCornerBottomRight;
break;
case 2:
corners = UIRectCornerTopLeft;
break;
case 3:
corners = UIRectCornerTopRight;
break;
case 4:
corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;
break;
case 5:
corners = UIRectCornerTopLeft | UIRectCornerTopRight;
break;
case 6:
corners = UIRectCornerBottomLeft | UIRectCornerTopLeft;
break;
case 7:
corners = UIRectCornerBottomRight | UIRectCornerTopRight;
break;
case 8:
corners = UIRectCornerBottomRight | UIRectCornerTopRight | UIRectCornerTopLeft;
break;
case 9:
corners = UIRectCornerBottomRight | UIRectCornerTopRight | UIRectCornerBottomLeft;
break;
default:
corners = UIRectCornerAllCorners;
break;
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:corners
cornerRadii:CGSizeMake(20.0, 30.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AllRoundButton/APRoundedButton.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 476 |
```objective-c
//
// Created by Alberto Pasca on 27/02/14.
//
#import <UIKit/UIKit.h>
@interface APRoundedButton : UIButton
@property (nonatomic, assign) int style;
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AllRoundButton/APRoundedButton.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 42 |
```objective-c
//
// YFAllRoundButtonVC.h
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import <UIKit/UIKit.h>
@interface YFAllRoundButtonVC : UIViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AllRoundButton/YFAllRoundButtonVC.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 54 |
```objective-c
//
// YFAllRoundButtonVC.m
// BigShow1949
//
// Created by zhht01 on 16/3/16.
//
#import "YFAllRoundButtonVC.h"
#import "APRoundedButton.h"
@interface YFAllRoundButtonVC ()
@end
@implementation YFAllRoundButtonVC
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
APRoundedButton *button = [[APRoundedButton alloc] init];
button.style = 1;
button.backgroundColor = [UIColor redColor];
button.frame = CGRectMake(50, 100, 100, 100);
[self.view addSubview:button];
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/01 - Button(按钮)/AllRoundButton/YFAllRoundButtonVC.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 160 |
```objective-c
//
// YFAuthorBlogViewController.m
// BigShow1949
//
// Created by WangMengqi on 15/9/2.
//
#import "YFBlogViewController.h"
@interface YFBlogViewController () {
NSIndexPath *_indexPath;
NSArray *_dataArr;
}
@end
@implementation YFBlogViewController
- (void)viewDidLoad {
[super viewDidLoad];
_dataArr = @[@[@"",@"path_to_url"],
@[@"",@"path_to_url"],
@[@"",@"path_to_url"],
@[@"",@"path_to_url"],
@[@"CocoaChina",@"path_to_url"],
@[@"Code4App",@"path_to_url"],
@[@"Git@OSC",@"path_to_url"],
@[@"",@"path_to_url"],
@[@"GitHub",@"path_to_url"],
@[@"Library",@"path_to_url"],];
[self setupDataArr:_dataArr];
//
UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
longPressGR.minimumPressDuration = 0.5;
[self.tableView addGestureRecognizer:longPressGR];
}
-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateBegan) {
CGPoint point = [gesture locationInView:self.tableView];
_indexPath = [self.tableView indexPathForRowAtPoint:point];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSArray *itemArr = _dataArr[_indexPath.row];
pasteboard.string = itemArr[1];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
message:pasteboard.string
delegate:nil
cancelButtonTitle:@""
otherButtonTitles:nil];
[alert show];
}
}
@end
``` | /content/code_sandbox/BigShow1949/Classes/14 - Blog(博客)/YFBlogViewController.m | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 382 |
```objective-c
//
// YFAuthorBlogViewController.h
// BigShow1949
//
// Created by WangMengqi on 15/9/2.
//
#import <UIKit/UIKit.h>
@interface YFBlogViewController : BaseTableViewController
@end
``` | /content/code_sandbox/BigShow1949/Classes/14 - Blog(博客)/YFBlogViewController.h | objective-c | 2016-05-05T08:19:43 | 2024-08-07T09:29:21 | BigShow1949 | BigShow1949/BigShow1949 | 1,121 | 54 |
```python
import re
NUM_CHARS = 30
with open('words_input.txt', 'r', encoding='ISO-8859-1') as fi_i, open('words_output.txt', 'r', encoding='ISO-8859-1') as fi_o, open('input_sentences.txt', 'w') as fo_i, open('output_sentences.txt', 'w') as fo_o:
fi_i_fixed = fi_i.read().encode('ascii', 'ignore').decode('UTF-8').lower()
fi_i_alpha = re.sub('[^a-z\n]+', ' ', fi_i_fixed)
fi_o_fixed = fi_o.read().encode('ascii', 'ignore').decode('UTF-8').lower()
fi_o_alpha = re.sub('[^a-z\n]+', ' ', fi_o_fixed)
for line in fi_i_alpha.split('\n'):
fo_i.write(line[:NUM_CHARS] + '\n')
for line in fi_o_alpha.split('\n'):
fo_o.write(line[:NUM_CHARS] + '\n')
``` | /content/code_sandbox/ch11_seq2seq/data/process_input.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 217 |
```python
import csv
import time
#
# crime14_freq = data_reader.read('crimes_2014.csv', 1, '%d-%b-%y %H:%M:%S', 2014)
# freq = read('311.csv', 0, '%m/%d/%Y', 2014)
def read(filename, date_idx, date_parse, year, bucket=7):
days_in_year = 365
# Create initial frequency map
freq = {}
for period in range(0, int(days_in_year/bucket)):
freq[period] = 0
# Read data and aggregate crimes per day
with open(filename, 'rb') as csvfile:
csvreader = csv.reader(csvfile)
csvreader.next()
for row in csvreader:
if row[date_idx] == '':
continue
t = time.strptime(row[date_idx], date_parse)
if t.tm_year == year and t.tm_yday < (days_in_year-1):
freq[int(t.tm_yday / bucket)] += 1
return freq
if __name__ == '__main__':
freq = read('311.csv', 0, '%m/%d/%Y', 2014)
print freq
``` | /content/code_sandbox/ch03_regression/data_reader.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 262 |
```python
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.01
training_epochs = 1000
num_labels = 3
batch_size = 100
x1_label0 = np.random.normal(1, 1, (100, 1))
x2_label0 = np.random.normal(1, 1, (100, 1))
x1_label1 = np.random.normal(5, 1, (100, 1))
x2_label1 = np.random.normal(4, 1, (100, 1))
x1_label2 = np.random.normal(8, 1, (100, 1))
x2_label2 = np.random.normal(0, 1, (100, 1))
plt.scatter(x1_label0, x2_label0, c='r', marker='o', s=60)
plt.scatter(x1_label1, x2_label1, c='g', marker='x', s=60)
plt.scatter(x1_label2, x2_label2, c='b', marker='_', s=60)
plt.show()
xs_label0 = np.hstack((x1_label0, x2_label0))
xs_label1 = np.hstack((x1_label1, x2_label1))
xs_label2 = np.hstack((x1_label2, x2_label2))
xs = np.vstack((xs_label0, xs_label1, xs_label2))
labels = np.matrix([[1., 0., 0.]] * len(x1_label0) + [[0., 1., 0.]] * len(x1_label1) + [[0., 0., 1.]] * len(x1_label2))
arr = np.arange(xs.shape[0])
np.random.shuffle(arr)
xs = xs[arr, :]
labels = labels[arr, :]
test_x1_label0 = np.random.normal(1, 1, (10, 1))
test_x2_label0 = np.random.normal(1, 1, (10, 1))
test_x1_label1 = np.random.normal(5, 1, (10, 1))
test_x2_label1 = np.random.normal(4, 1, (10, 1))
test_x1_label2 = np.random.normal(8, 1, (10, 1))
test_x2_label2 = np.random.normal(0, 1, (10, 1))
test_xs_label0 = np.hstack((test_x1_label0, test_x2_label0))
test_xs_label1 = np.hstack((test_x1_label1, test_x2_label1))
test_xs_label2 = np.hstack((test_x1_label2, test_x2_label2))
test_xs = np.vstack((test_xs_label0, test_xs_label1, test_xs_label2))
test_labels = np.matrix([[1., 0., 0.]] * 10 + [[0., 1., 0.]] * 10 + [[0., 0., 1.]] * 10)
train_size, num_features = xs.shape
X = tf.placeholder("float", shape=[None, num_features])
Y = tf.placeholder("float", shape=[None, num_labels])
W = tf.Variable(tf.zeros([num_features, num_labels]))
b = tf.Variable(tf.zeros([num_labels]))
y_model = tf.nn.softmax(tf.matmul(X, W) + b)
cost = -tf.reduce_sum(Y * tf.log(y_model))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(y_model, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
with tf.Session() as sess:
tf.initialize_all_variables().run()
for step in xrange(training_epochs * train_size // batch_size):
offset = (step * batch_size) % train_size
batch_xs = xs[offset:(offset + batch_size), :]
batch_labels = labels[offset:(offset + batch_size)]
err, _ = sess.run([cost, train_op], feed_dict={X: batch_xs, Y: batch_labels})
print (step, err)
W_val = sess.run(W)
print('w', W_val)
b_val = sess.run(b)
print('b', b_val)
print "accuracy", accuracy.eval(feed_dict={X: test_xs, Y: test_labels})
``` | /content/code_sandbox/ch04_classification/softmax.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 934 |
```python
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.1
training_epochs = 2000
def sigmoid(x):
return 1. / (1. + np.exp(-x))
x1_label1 = np.random.normal(3, 1, 1000)
x2_label1 = np.random.normal(2, 1, 1000)
x1_label2 = np.random.normal(7, 1, 1000)
x2_label2 = np.random.normal(6, 1, 1000)
x1s = np.append(x1_label1, x1_label2)
x2s = np.append(x2_label1, x2_label2)
ys = np.asarray([0.] * len(x1_label1) + [1.] * len(x1_label2))
X1 = tf.placeholder(tf.float32, shape=(None,), name="x1")
X2 = tf.placeholder(tf.float32, shape=(None,), name="x2")
Y = tf.placeholder(tf.float32, shape=(None,), name="y")
w = tf.Variable([0., 0., 0.], name="w", trainable=True)
y_model = tf.sigmoid(-(w[2] * X2 + w[1] * X1 + w[0]))
cost = tf.reduce_mean(-tf.log(y_model) * Y -tf.log(1 - y_model) * (1 - Y))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
prev_err = 0
for epoch in range(training_epochs):
err, _ = sess.run([cost, train_op], {X1: x1s, X2: x2s, Y: ys})
print(epoch, err)
if abs(prev_err - err) < 0.0001:
break
prev_err = err
w_val = sess.run(w)
x1_boundary, x2_boundary = [], []
for x1_test in np.linspace(0, 10, 100):
for x2_test in np.linspace(0, 10, 100):
z = sigmoid(-x2_test*w_val[2] - x1_test*w_val[1] - w_val[0])
if abs(z - 0.5) < 0.01:
x1_boundary.append(x1_test)
x2_boundary.append(x2_test)
plt.scatter(x1_boundary, x2_boundary, c='b', marker='o', s=20)
plt.scatter(x1_label1, x2_label1, c='r', marker='x', s=20)
plt.scatter(x1_label2, x2_label2, c='g', marker='1', s=20)
plt.show()
``` | /content/code_sandbox/ch04_classification/logistic_2d.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 602 |
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_label0 = np.random.normal(5, 1, 10)
x_label1 = np.random.normal(2, 1, 10)
xs = np.append(x_label0, x_label1)
labels = [0.] * len(x_label0) + [1.] * len(x_label1)
plt.scatter(xs, labels)
learning_rate = 0.001
training_epochs = 1000
X = tf.placeholder("float")
Y = tf.placeholder("float")
def model(X, w):
return tf.add(tf.mul(w[1], tf.pow(X, 1)),
tf.mul(w[0], tf.pow(X, 0)))
w = tf.Variable([0., 0.], name="parameters")
y_model = model(X, w)
cost = tf.reduce_sum(tf.square(Y-y_model))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
correct_prediction = tf.equal(Y, tf.to_float(tf.greater(y_model, 0.5)))
accuracy = tf.reduce_mean(tf.to_float(correct_prediction))
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
for epoch in range(training_epochs):
sess.run(train_op, feed_dict={X: xs, Y: labels})
current_cost = sess.run(cost, feed_dict={X: xs, Y: labels})
print(epoch, current_cost)
w_val = sess.run(w)
print('learned parameters', w_val)
print('accuracy', sess.run(accuracy, feed_dict={X: xs, Y: labels}))
sess.close()
all_xs = np.linspace(0, 10, 100)
plt.plot(all_xs, all_xs*w_val[1] + w_val[0])
plt.show()
``` | /content/code_sandbox/ch04_classification/linear_1d.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 377 |
```python
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.01
training_epochs = 1000
def sigmoid(x):
return 1. / (1. + np.exp(-x))
x1 = np.random.normal(-4, 2, 1000)
x2 = np.random.normal(4, 2, 1000)
xs = np.append(x1, x2)
ys = np.asarray([0.] * len(x1) + [1.] * len(x2))
plt.scatter(xs, ys)
X = tf.placeholder(tf.float32, shape=(None,), name="x")
Y = tf.placeholder(tf.float32, shape=(None,), name="y")
w = tf.Variable([0., 0.], name="parameter", trainable=True)
y_model = tf.sigmoid(-(w[1] * X + w[0]))
cost = tf.reduce_mean(-tf.log(y_model * Y + (1 - y_model) * (1 - Y)))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
prev_err = 0
for epoch in range(training_epochs):
err, _ = sess.run([cost, train_op], {X: xs, Y: ys})
print(epoch, err)
if abs(prev_err - err) < 0.0001:
break
prev_err = err
w_val = sess.run(w, {X: xs, Y: ys})
all_xs = np.linspace(-10, 10, 100)
plt.plot(all_xs, sigmoid(all_xs * w_val[1] + w_val[0]))
plt.show()
``` | /content/code_sandbox/ch04_classification/logistic_1d.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 365 |
```python
import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf
learning_rate = 0.001
names, data, labels = \
cifar_tools.read_data('/home/binroot/res/cifar-10-batches-py')
x = tf.placeholder(tf.float32, [None, 24 * 24])
y = tf.placeholder(tf.float32, [None, len(names)])
W1 = tf.Variable(tf.random_normal([5, 5, 1, 64]))
b1 = tf.Variable(tf.random_normal([64]))
W2 = tf.Variable(tf.random_normal([5, 5, 64, 64]))
b2 = tf.Variable(tf.random_normal([64]))
W3 = tf.Variable(tf.random_normal([6*6*64, 1024]))
b3 = tf.Variable(tf.random_normal([1024]))
W_out = tf.Variable(tf.random_normal([1024, len(names)]))
b_out = tf.Variable(tf.random_normal([len(names)]))
def conv_layer(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
conv_with_b = tf.nn.bias_add(conv, b)
conv_out = tf.nn.relu(conv_with_b)
return conv_out
def maxpool_layer(conv, k=2):
return tf.nn.max_pool(conv, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
def model():
x_reshaped = tf.reshape(x, shape=[-1, 24, 24, 1])
conv_out1 = conv_layer(x_reshaped, W1, b1)
maxpool_out1 = maxpool_layer(conv_out1)
norm1 = tf.nn.lrn(maxpool_out1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
conv_out2 = conv_layer(norm1, W2, b2)
norm2 = tf.nn.lrn(conv_out2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
maxpool_out2 = maxpool_layer(norm2)
maxpool_reshaped = tf.reshape(maxpool_out2, [-1, W3.get_shape().as_list()[0]])
local = tf.add(tf.matmul(maxpool_reshaped, W3), b3)
local_out = tf.nn.relu(local)
out = tf.add(tf.matmul(local_out, W_out), b_out)
return out
model_op = model()
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model_op, y))
train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(model_op, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
onehot_labels = tf.one_hot(labels, len(names), on_value=1., off_value=0., axis=-1)
onehot_vals = sess.run(onehot_labels)
batch_size = len(data) / 200
print('batch size', batch_size)
for j in range(0, 1000):
print('EPOCH', j)
for i in range(0, len(data), batch_size):
batch_data = data[i:i+batch_size, :]
batch_onehot_vals = onehot_vals[i:i+batch_size, :]
_, accuracy_val = sess.run([train_op, accuracy], feed_dict={x: batch_data, y: batch_onehot_vals})
if i % 1000 == 0:
print(i, accuracy_val)
print('DONE WITH EPOCH')
``` | /content/code_sandbox/ch09_cnn/cnn.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 825 |
```python
import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf
learning_rate = 0.001
names, data, labels = \
cifar_tools.read_data('/home/binroot/res/cifar-10-batches-py')
x = tf.placeholder(tf.float32, [None, 24 * 24], name='input')
y = tf.placeholder(tf.float32, [None, len(names)], name='prediction')
W1 = tf.Variable(tf.random_normal([5, 5, 1, 64]), name='W1')
b1 = tf.Variable(tf.random_normal([64]), name='b1')
W2 = tf.Variable(tf.random_normal([5, 5, 64, 64]), name='W2')
b2 = tf.Variable(tf.random_normal([64]), name='b2')
W3 = tf.Variable(tf.random_normal([6*6*64, 1024]), name='W3')
b3 = tf.Variable(tf.random_normal([1024]), name='b3')
W_out = tf.Variable(tf.random_normal([1024, len(names)]), name='W_out')
b_out = tf.Variable(tf.random_normal([len(names)]), name='b_out')
W1_summary = tf.image_summary('W1_img', W1)
def conv_layer(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
conv_with_b = tf.nn.bias_add(conv, b)
conv_out = tf.nn.relu(conv_with_b)
return conv_out
def maxpool_layer(conv, k=2):
return tf.nn.max_pool(conv, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
def model():
x_reshaped = tf.reshape(x, shape=[-1, 24, 24, 1])
conv_out1 = conv_layer(x_reshaped, W1, b1)
maxpool_out1 = maxpool_layer(conv_out1)
norm1 = tf.nn.lrn(maxpool_out1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
conv_out2 = conv_layer(norm1, W2, b2)
norm2 = tf.nn.lrn(conv_out2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
maxpool_out2 = maxpool_layer(norm2)
maxpool_reshaped = tf.reshape(maxpool_out2, [-1, W3.get_shape().as_list()[0]])
local = tf.add(tf.matmul(maxpool_reshaped, W3), b3)
local_out = tf.nn.relu(local)
out = tf.add(tf.matmul(local_out, W_out), b_out)
return out
model_op = model()
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model_op, y))
tf.scalar_summary('cost', cost)
train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(model_op, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
merged = tf.merge_all_summaries()
with tf.Session() as sess:
summary_writer = tf.train.SummaryWriter('summaries/train', sess.graph)
sess.run(tf.initialize_all_variables())
onehot_labels = tf.one_hot(labels, len(names), on_value=1., off_value=0., axis=-1)
onehot_vals = sess.run(onehot_labels)
batch_size = len(data) / 200
print('batch size', batch_size)
for j in range(0, 1000):
print('EPOCH', j)
for i in range(0, len(data), batch_size):
batch_data = data[i:i+batch_size, :]
batch_onehot_vals = onehot_vals[i:i+batch_size, :]
_, accuracy_val, summary = sess.run([train_op, accuracy, merged], feed_dict={x: batch_data, y: batch_onehot_vals})
summary_writer.add_summary(summary, i)
if i % 1000 == 0:
print(i, accuracy_val)
print('DONE WITH EPOCH')
``` | /content/code_sandbox/ch09_cnn/cnn_viz.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 933 |
```python
import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf
names, data, labels = \
cifar_tools.read_data('/home/binroot/res/cifar-10-batches-py')
def show_conv_results(data, filename=None):
plt.figure()
rows, cols = 4, 8
for i in range(np.shape(data)[3]):
img = data[0, :, :, i]
plt.subplot(rows, cols, i + 1)
plt.imshow(img, cmap='Greys_r', interpolation='none')
plt.axis('off')
if filename:
plt.savefig(filename)
else:
plt.show()
def show_weights(W, filename=None):
plt.figure()
rows, cols = 4, 8
for i in range(np.shape(W)[3]):
img = W[:, :, 0, i]
plt.subplot(rows, cols, i + 1)
plt.imshow(img, cmap='Greys_r', interpolation='none')
plt.axis('off')
if filename:
plt.savefig(filename)
else:
plt.show()
raw_data = data[4, :]
raw_img = np.reshape(raw_data, (24, 24))
plt.figure()
plt.imshow(raw_img, cmap='Greys_r')
plt.savefig('input_image.png')
x = tf.reshape(raw_data, shape=[-1, 24, 24, 1])
W = tf.Variable(tf.random_normal([5, 5, 1, 32]))
b = tf.Variable(tf.random_normal([32]))
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
conv_with_b = tf.nn.bias_add(conv, b)
conv_out = tf.nn.relu(conv_with_b)
k = 2
maxpool = tf.nn.max_pool(conv_out, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
W_val = sess.run(W)
show_weights(W_val, 'step0_weights.png')
conv_val = sess.run(conv)
show_conv_results(conv_val, 'step1_convs.png')
print(np.shape(conv_val))
conv_out_val = sess.run(conv_out)
show_conv_results(conv_out_val, 'step2_conv_outs.png')
print(np.shape(conv_out_val))
maxpool_val = sess.run(maxpool)
show_conv_results(maxpool_val, 'step3_maxpool.png')
print(np.shape(maxpool_val))
``` | /content/code_sandbox/ch09_cnn/conv_visuals.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 555 |
```python
import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import random
names, data, labels = \
cifar_tools.read_data('/home/binroot/res/cifar-10-batches-py')
random.seed(1)
def show_some_examples(names, data, labels):
plt.figure()
rows, cols = 4, 4
random_idxs = random.sample(range(len(data)), rows * cols)
for i in range(rows * cols):
plt.subplot(rows, cols, i + 1)
j = random_idxs[i]
plt.title(names[labels[j]])
img = np.reshape(data[j, :], (24, 24))
plt.imshow(img, cmap='Greys_r')
plt.axis('off')
plt.tight_layout()
plt.savefig('cifar_examples.png')
show_some_examples(names, data, labels)
``` | /content/code_sandbox/ch09_cnn/using_cifar.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 182 |
```python
import pickle
import numpy as np
def unpickle(file):
fo = open(file, 'rb')
dict = pickle.load(fo, encoding='latin1')
fo.close()
return dict
def clean(data):
imgs = data.reshape(data.shape[0], 3, 32, 32)
grayscale_imgs = imgs.mean(1)
cropped_imgs = grayscale_imgs[:, 4:28, 4:28]
img_data = cropped_imgs.reshape(data.shape[0], -1)
img_size = np.shape(img_data)[1]
means = np.mean(img_data, axis=1)
meansT = means.reshape(len(means), 1)
stds = np.std(img_data, axis=1)
stdsT = stds.reshape(len(stds), 1)
adj_stds = np.maximum(stdsT, 1.0 / np.sqrt(img_size))
normalized = (img_data - meansT) / adj_stds
return normalized
def read_data(directory):
names = unpickle('{}/batches.meta'.format(directory))['label_names']
print('names', names)
data, labels = [], []
for i in range(1, 6):
filename = '{}/data_batch_{}'.format(directory, i)
batch_data = unpickle(filename)
if len(data) > 0:
data = np.vstack((data, batch_data['data']))
labels = np.hstack((labels, batch_data['labels']))
else:
data = batch_data['data']
labels = batch_data['labels']
print(np.shape(data), np.shape(labels))
data = clean(data)
data = data.astype(np.float32)
return names, data, labels
``` | /content/code_sandbox/ch09_cnn/cifar_tools.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 369 |
```python
## Using TensorBoard
# mkdir logs
import tensorflow as tf
import numpy as np
raw_data = np.random.normal(10, 1, 100)
alpha = tf.constant(0.05)
curr_value = tf.placeholder(tf.float32)
prev_avg = tf.Variable(0.)
update_avg = alpha * curr_value + (1 - alpha) * prev_avg
avg_hist = tf.summary.scalar("running_avg", update_avg)
value_hist = tf.summary.scalar("incoming_values", curr_value)
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('./logs')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(len(raw_data)):
summary_str, curr_avg = sess.run([merged, update_avg], feed_dict={curr_value: raw_data[i]})
sess.run(tf.assign(prev_avg, curr_avg))
print(raw_data[i], curr_avg)
writer.add_summary(summary_str, i)
writer.close()
``` | /content/code_sandbox/ch02_basics/moving_avg.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 204 |
```python
# # Using Variables in TensorFlow
import tensorflow as tf
sess = tf.InteractiveSession()
# Create a boolean variable called `spike` to detect sudden a sudden increase in a series of numbers.
#
# Since all variables must be initialized, initialize the variable by calling `run()` on its `initializer`.
raw_data = [1., 2., 8., -1., 0., 5.5, 6., 13]
spike = tf.Variable(False)
spike.initializer.run()
# Loop through the data and update the spike variable when there is a significant increase
for i in range(1, len(raw_data)):
if raw_data[i] - raw_data[i-1] > 5:
updater = tf.assign(spike, tf.constant(True))
updater.eval()
else:
tf.assign(spike, False).eval()
print("Spike", spike.eval())
sess.close()
``` | /content/code_sandbox/ch02_basics/spikes.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 193 |
```python
# # Tensor Types
import tensorflow as tf
import numpy as np
# Define a 2x2 matrix in 3 different ways
m1 = [[1.0, 2.0], [3.0, 4.0]]
m2 = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)
m3 = tf.constant([[1.0, 2.0], [3.0, 4.0]])
print(type(m1))
print(type(m2))
print(type(m3))
# Create tensor objects out of various types
t1 = tf.convert_to_tensor(m1, dtype=tf.float32)
t2 = tf.convert_to_tensor(m2, dtype=tf.float32)
t3 = tf.convert_to_tensor(m3, dtype=tf.float32)
print(type(t1))
print(type(t2))
print(type(t3))
``` | /content/code_sandbox/ch02_basics/types.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 193 |
```python
import tensorflow as tf
import numpy as np
x = tf.constant([[1, 2]])
neg_x = tf.neg(x)
print(neg_x)
with tf.Session() as sess:
result = sess.run(neg_x)
print(result)
``` | /content/code_sandbox/ch02_basics/main.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 52 |
```python
import tensorflow as tf
sess = tf.InteractiveSession()
matrix = tf.constant([[1., 2.]])
negMatrix = tf.neg(matrix)
result = negMatrix.eval()
print(result)
sess.close()
``` | /content/code_sandbox/ch02_basics/interactive_session.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 43 |
```python
import tensorflow as tf
matrix = tf.constant([[1., 2.]])
negMatrix = tf.neg(matrix)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
result = sess.run(negMatrix)
print(result)
``` | /content/code_sandbox/ch02_basics/log_example.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 51 |
```python
import tensorflow as tf
def my_loss_function(var, data):
return tf.abs(tf.subtract(var, data))
def my_other_loss_function(var, data):
return tf.square(tf.subtract(var, data))
data = tf.placeholder(tf.float32)
var = tf.Variable(1.)
loss = my_loss_function(var, data)
var_grad = tf.gradients(loss, [var])[0]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
var_grad_val = sess.run(var_grad, feed_dict={data: 4})
print(var_grad_val)
``` | /content/code_sandbox/ch02_basics/gradient.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 119 |
```python
import tensorflow as tf
matrix = tf.constant([[1, 2]])
neg_matrix = tf.neg(matrix)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
result = sess.run(neg_matrix)
print result
``` | /content/code_sandbox/ch02_basics/logging_example.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 50 |
```python
# # Loading Variables in TensorFlow
import tensorflow as tf
sess = tf.InteractiveSession()
# Create a boolean vector called `spike` to locate a sudden spike in data.
#
# Since all variables must be initialized, initialize the variable by calling `run()` on its `initializer`.
spikes = tf.Variable([False]*8, name='spikes')
saver = tf.train.Saver()
saver.restore(sess, "spikes.ckpt")
print(spikes.eval())
sess.close()
``` | /content/code_sandbox/ch02_basics/loading_vars.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 103 |
```python
# # Saving Variables in TensorFlow
import tensorflow as tf
sess = tf.InteractiveSession()
# Create a boolean vector called `spike` to locate a sudden spike in data.
#
# Since all variables must be initialized, initialize the variable by calling `run()` on its `initializer`.
raw_data = [1., 2., 8., -1., 0., 5.5, 6., 13]
spikes = tf.Variable([False] * len(raw_data), name='spikes')
spikes.initializer.run()
# The saver op will enable saving and restoring
saver = tf.train.Saver()
# Loop through the data and update the spike variable when there is a significant increase
for i in range(1, len(raw_data)):
if raw_data[i] - raw_data[i-1] > 5:
spikes_val = spikes.eval()
spikes_val[i] = True
updater = tf.assign(spikes, spikes_val)
updater.eval()
save_path = saver.save(sess, "spikes.ckpt")
print("spikes data saved in file: %s" % save_path)
sess.close()
``` | /content/code_sandbox/ch02_basics/saving_vars.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 239 |
```python
import tensorflow as tf
import numpy as np
class SOM:
def __init__(self, width, height, dim):
self.num_iters = 100
self.width = width
self.height = height
self.dim = dim
self.node_locs = self.get_locs()
# Each node is a vector of dimension `dim`
# For a 2D grid, there are `width * height` nodes
nodes = tf.Variable(tf.random_normal([width*height, dim]))
self.nodes = nodes
# These two ops are inputs at each iteration
x = tf.placeholder(tf.float32, [dim])
iter = tf.placeholder(tf.float32)
self.x = x
self.iter = iter
# Find the node that matches closest to the input
bmu_loc = self.get_bmu_loc(x)
self.propagate_nodes = self.get_propagation(bmu_loc, x, iter)
def get_propagation(self, bmu_loc, x, iter):
num_nodes = self.width * self.height
rate = 1.0 - tf.div(iter, self.num_iters)
alpha = rate * 0.5
sigma = rate * tf.to_float(tf.maximum(self.width, self.height)) / 2.
expanded_bmu_loc = tf.expand_dims(tf.to_float(bmu_loc), 0)
sqr_dists_from_bmu = tf.reduce_sum(tf.square(tf.sub(expanded_bmu_loc, self.node_locs)), 1)
neigh_factor = tf.exp(-tf.div(sqr_dists_from_bmu, 2 * tf.square(sigma)))
rate = tf.mul(alpha, neigh_factor)
rate_factor = tf.pack([tf.tile(tf.slice(rate, [i], [1]), [self.dim]) for i in range(num_nodes)])
nodes_diff = tf.mul(rate_factor, tf.sub(tf.pack([x for i in range(num_nodes)]), self.nodes))
update_nodes = tf.add(self.nodes, nodes_diff)
return tf.assign(self.nodes, update_nodes)
def get_bmu_loc(self, x):
expanded_x = tf.expand_dims(x, 0)
sqr_diff = tf.square(tf.sub(expanded_x, self.nodes))
dists = tf.reduce_sum(sqr_diff, 1)
bmu_idx = tf.argmin(dists, 0)
bmu_loc = tf.pack([tf.mod(bmu_idx, self.width), tf.div(bmu_idx, self.width)])
return bmu_loc
def get_locs(self):
locs = [[x, y]
for y in range(self.height)
for x in range(self.width)]
return tf.to_float(locs)
def train(self, data):
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(self.num_iters):
for data_x in data:
sess.run(self.propagate_nodes, feed_dict={self.x: data_x, self.iter: i})
centroid_grid = [[] for i in range(self.width)]
self.nodes_val = list(sess.run(self.nodes))
self.locs_val = list(sess.run(self.node_locs))
for i, l in enumerate(self.locs_val):
centroid_grid[int(l[0])].append(self.nodes_val[i])
self.centroid_grid = centroid_grid
``` | /content/code_sandbox/ch05_clustering/som.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 697 |
```python
#For plotting the images
from matplotlib import pyplot as plt
import numpy as np
from som import SOM
colors = np.array(
[[0., 0., 1.],
[0., 0., 0.95],
[0., 0.05, 1.],
[0., 1., 0.],
[0., 0.95, 0.],
[0., 1, 0.05],
[1., 0., 0.],
[1., 0.05, 0.],
[1., 0., 0.05],
[1., 1., 0.]])
som = SOM(4, 4, 3)
som.train(colors)
plt.imshow(som.centroid_grid)
plt.show()
``` | /content/code_sandbox/ch05_clustering/som_test.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 175 |
```python
import tensorflow as tf
import numpy as np
from bregman.suite import *
k = 2
max_iterations = 100
filenames = tf.train.match_filenames_once('./audio_dataset/*.wav')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
filename, file_contents = reader.read(filename_queue)
chromo = tf.placeholder(tf.float32)
max_freqs = tf.argmax(chromo, 0)
def get_next_chromogram(sess):
audio_file = sess.run(filename)
F = Chromagram(audio_file, nfft=16384, wfft=8192, nhop=2205)
return F.X, audio_file
def extract_feature_vector(sess, chromo_data):
num_features, num_samples = np.shape(chromo_data)
freq_vals = sess.run(max_freqs, feed_dict={chromo: chromo_data})
hist, bins = np.histogram(freq_vals, bins=range(num_features + 1))
normalized_hist = hist.astype(float) / num_samples
return normalized_hist
def get_dataset(sess):
num_files = sess.run(count_num_files)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
xs = list()
names = list()
plt.figure()
for _ in range(num_files):
chromo_data, filename = get_next_chromogram(sess)
plt.subplot(1, 2, 1)
plt.imshow(chromo_data, cmap='Greys', interpolation='nearest')
plt.title('Visualization of Sound Spectrum')
plt.subplot(1, 2, 2)
freq_vals = sess.run(max_freqs, feed_dict={chromo: chromo_data})
plt.hist(freq_vals)
plt.title('Histogram of Notes')
plt.xlabel('Musical Note')
plt.ylabel('Count')
plt.savefig('{}.png'.format(filename))
plt.clf()
plt.clf()
names.append(filename)
x = extract_feature_vector(sess, chromo_data)
xs.append(x)
xs = np.asmatrix(xs)
return xs, names
def initial_cluster_centroids(X, k):
return X[0:k, :]
def assign_cluster(X, centroids):
expanded_vectors = tf.expand_dims(X, 0)
expanded_centroids = tf.expand_dims(centroids, 1)
distances = tf.reduce_sum(tf.square(tf.sub(expanded_vectors, expanded_centroids)), 2)
mins = tf.argmin(distances, 0)
return mins
def recompute_centroids(X, Y):
sums = tf.unsorted_segment_sum(X, Y, k)
counts = tf.unsorted_segment_sum(tf.ones_like(X), Y, k)
return sums / counts
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
X, names = get_dataset(sess)
centroids = initial_cluster_centroids(X, k)
i, converged = 0, False
while not converged and i < max_iterations:
i += 1
Y = assign_cluster(X, centroids)
centroids = sess.run(recompute_centroids(X, Y))
print(zip(sess.run(Y), names))
``` | /content/code_sandbox/ch05_clustering/audio_clustering.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 683 |
```python
import tensorflow as tf
import numpy as np
from bregman.suite import *
k = 4
segment_size = 50 # out of 24,526
max_iterations = 100
chromo = tf.placeholder(tf.float32)
max_freqs = tf.argmax(chromo, 0)
def get_chromogram(audio_file):
F = Chromagram(audio_file, nfft=16384, wfft=8192, nhop=2205)
return F.X
def get_dataset(sess, audio_file):
chromo_data = get_chromogram(audio_file)
print('chromo_data', np.shape(chromo_data))
chromo_length = np.shape(chromo_data)[1]
xs = []
for i in range(chromo_length/segment_size):
chromo_segment = chromo_data[:, i*segment_size:(i+1)*segment_size]
x = extract_feature_vector(sess, chromo_segment)
if len(xs) == 0:
xs = x
else:
xs = np.vstack((xs, x))
return xs
def initial_cluster_centroids(X, k):
return X[0:k, :]
# op
def assign_cluster(X, centroids):
expanded_vectors = tf.expand_dims(X, 0)
expanded_centroids = tf.expand_dims(centroids, 1)
distances = tf.reduce_sum(tf.square(tf.sub(expanded_vectors, expanded_centroids)), 2)
mins = tf.argmin(distances, 0)
return mins
# op
def recompute_centroids(X, Y):
sums = tf.unsorted_segment_sum(X, Y, k)
counts = tf.unsorted_segment_sum(tf.ones_like(X), Y, k)
return sums / counts
def extract_feature_vector(sess, chromo_data):
num_features, num_samples = np.shape(chromo_data)
freq_vals = sess.run(max_freqs, feed_dict={chromo: chromo_data})
hist, bins = np.histogram(freq_vals, bins=range(num_features + 1))
return hist.astype(float) / num_samples
with tf.Session() as sess:
X = get_dataset(sess, 'sysk.wav')
print(np.shape(X))
centroids = initial_cluster_centroids(X, k)
i, converged = 0, False
# prev_Y = None
while not converged and i < max_iterations:
i += 1
Y = assign_cluster(X, centroids)
# if prev_Y == Y:
# converged = True
# break
# prev_Y = Y
centroids = sess.run(recompute_centroids(X, Y))
if i % 50 == 0:
print('iteration', i)
segments = sess.run(Y)
for i in range(len(segments)):
seconds = (i * segment_size) / float(10)
min, sec = divmod(seconds, 60)
time_str = str(min) + 'm ' + str(sec) + 's'
print(time_str, segments[i])
``` | /content/code_sandbox/ch05_clustering/audio_segmentation.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 647 |
```python
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
import data_loader
import matplotlib.pyplot as plt
class SeriesPredictor:
def __init__(self, input_dim, seq_size, hidden_dim):
# Hyperparameters
self.input_dim = input_dim
self.seq_size = seq_size
self.hidden_dim = hidden_dim
# Weight variables and input placeholders
self.W_out = tf.Variable(tf.random_normal([hidden_dim, 1]), name='W_out')
self.b_out = tf.Variable(tf.random_normal([1]), name='b_out')
self.x = tf.placeholder(tf.float32, [None, seq_size, input_dim])
self.y = tf.placeholder(tf.float32, [None, seq_size])
# Cost optimizer
self.cost = tf.reduce_mean(tf.square(self.model() - self.y))
self.train_op = tf.train.AdamOptimizer(learning_rate=0.003).minimize(self.cost)
# Auxiliary ops
self.saver = tf.train.Saver()
def model(self):
"""
:param x: inputs of size [T, batch_size, input_size]
:param W: matrix of fully-connected output layer weights
:param b: vector of fully-connected output layer biases
"""
cell = rnn_cell.BasicLSTMCell(self.hidden_dim)
outputs, states = rnn.dynamic_rnn(cell, self.x, dtype=tf.float32)
num_examples = tf.shape(self.x)[0]
W_repeated = tf.tile(tf.expand_dims(self.W_out, 0), [num_examples, 1, 1])
out = tf.batch_matmul(outputs, W_repeated) + self.b_out
out = tf.squeeze(out)
return out
def train(self, train_x, train_y, test_x, test_y):
with tf.Session() as sess:
tf.get_variable_scope().reuse_variables()
sess.run(tf.initialize_all_variables())
max_patience = 3
patience = max_patience
min_test_err = float('inf')
step = 0
while patience > 0:
_, train_err = sess.run([self.train_op, self.cost], feed_dict={self.x: train_x, self.y: train_y})
if step % 100 == 0:
test_err = sess.run(self.cost, feed_dict={self.x: test_x, self.y: test_y})
print('step: {}\t\ttrain err: {}\t\ttest err: {}'.format(step, train_err, test_err))
if test_err < min_test_err:
min_test_err = test_err
patience = max_patience
else:
patience -= 1
step += 1
save_path = self.saver.save(sess, 'model.ckpt')
print('Model saved to {}'.format(save_path))
def test(self, sess, test_x):
tf.get_variable_scope().reuse_variables()
self.saver.restore(sess, 'model.ckpt')
output = sess.run(self.model(), feed_dict={self.x: test_x})
return output
def plot_results(train_x, predictions, actual, filename):
plt.figure()
num_train = len(train_x)
plt.plot(list(range(num_train)), train_x, color='b', label='training data')
plt.plot(list(range(num_train, num_train + len(predictions))), predictions, color='r', label='predicted')
plt.plot(list(range(num_train, num_train + len(actual))), actual, color='g', label='test data')
plt.legend()
if filename is not None:
plt.savefig(filename)
else:
plt.show()
if __name__ == '__main__':
seq_size = 5
predictor = SeriesPredictor(input_dim=1, seq_size=seq_size, hidden_dim=5)
data = data_loader.load_series('international-airline-passengers.csv')
train_data, actual_vals = data_loader.split_data(data)
train_x, train_y = [], []
for i in range(len(train_data) - seq_size - 1):
train_x.append(np.expand_dims(train_data[i:i+seq_size], axis=1).tolist())
train_y.append(train_data[i+1:i+seq_size+1])
test_x, test_y = [], []
for i in range(len(actual_vals) - seq_size - 1):
test_x.append(np.expand_dims(actual_vals[i:i+seq_size], axis=1).tolist())
test_y.append(actual_vals[i+1:i+seq_size+1])
predictor.train(train_x, train_y, test_x, test_y)
with tf.Session() as sess:
predicted_vals = predictor.test(sess, test_x)[:,0]
print('predicted_vals', np.shape(predicted_vals))
plot_results(train_data, predicted_vals, actual_vals, 'predictions.png')
prev_seq = train_x[-1]
predicted_vals = []
for i in range(20):
next_seq = predictor.test(sess, [prev_seq])
predicted_vals.append(next_seq[-1])
prev_seq = np.vstack((prev_seq[1:], next_seq[-1]))
plot_results(train_data, predicted_vals, actual_vals, 'hallucinations.png')
``` | /content/code_sandbox/ch10_rnn/regression.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 1,107 |
```python
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
class SeriesPredictor:
def __init__(self, input_dim, seq_size, hidden_dim=10):
# Hyperparameters
self.input_dim = input_dim
self.seq_size = seq_size
self.hidden_dim = hidden_dim
# Weight variables and input placeholders
self.W_out = tf.Variable(tf.random_normal([hidden_dim, 1]), name='W_out')
self.b_out = tf.Variable(tf.random_normal([1]), name='b_out')
self.x = tf.placeholder(tf.float32, [None, seq_size, input_dim])
self.y = tf.placeholder(tf.float32, [None, seq_size])
# Cost optimizer
self.cost = tf.reduce_mean(tf.square(self.model() - self.y))
self.train_op = tf.train.AdamOptimizer().minimize(self.cost)
# Auxiliary ops
self.saver = tf.train.Saver()
def model(self):
"""
:param x: inputs of size [T, batch_size, input_size]
:param W: matrix of fully-connected output layer weights
:param b: vector of fully-connected output layer biases
"""
cell = rnn_cell.BasicLSTMCell(self.hidden_dim, reuse=tf.get_variable_scope().reuse)
outputs, states = rnn.dynamic_rnn(cell, self.x, dtype=tf.float32)
num_examples = tf.shape(self.x)[0]
W_repeated = tf.tile(tf.expand_dims(self.W_out, 0), [num_examples, 1, 1])
out = tf.batch_matmul(outputs, W_repeated) + self.b_out
out = tf.squeeze(out)
return out
def train(self, train_x, train_y):
with tf.Session() as sess:
tf.get_variable_scope().reuse_variables()
sess.run(tf.initialize_all_variables())
for i in range(1000):
_, mse = sess.run([self.train_op, self.cost], feed_dict={self.x: train_x, self.y: train_y})
if i % 100 == 0:
print(i, mse)
save_path = self.saver.save(sess, 'model.ckpt')
print('Model saved to {}'.format(save_path))
def test(self, test_x):
with tf.Session() as sess:
tf.get_variable_scope().reuse_variables()
self.saver.restore(sess, 'model.ckpt')
output = sess.run(self.model(), feed_dict={self.x: test_x})
print(output)
if __name__ == '__main__':
predictor = SeriesPredictor(input_dim=1, seq_size=4, hidden_dim=10)
train_x = [[[1], [2], [5], [6]],
[[5], [7], [7], [8]],
[[3], [4], [5], [7]]]
train_y = [[1, 3, 7, 11],
[5, 12, 14, 15],
[3, 7, 9, 12]]
predictor.train(train_x, train_y)
test_x = [[[1], [2], [3], [4]], # 1, 3, 5, 7
[[4], [5], [6], [7]]] # 4, 9, 11, 13
predictor.test(test_x)
``` | /content/code_sandbox/ch10_rnn/simple_regression.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 726 |
```python
import csv
import numpy as np
import matplotlib.pyplot as plt
def load_series(filename, series_idx=1):
try:
with open(filename) as csvfile:
csvreader = csv.reader(csvfile)
data = [float(row[series_idx]) for row in csvreader if len(row) > 0]
normalized_data = (data - np.mean(data)) / np.std(data)
return normalized_data
except IOError:
return None
def split_data(data, percent_train=0.80):
num_rows = len(data)
train_data, test_data = [], []
for idx, row in enumerate(data):
if idx < num_rows * percent_train:
train_data.append(row)
else:
test_data.append(row)
return train_data, test_data
if __name__=='__main__':
# path_to_url#!ds=22u3&display=line
timeseries = load_series('international-airline-passengers.csv')
print(np.shape(timeseries))
plt.figure()
plt.plot(timeseries)
plt.show()
``` | /content/code_sandbox/ch10_rnn/data_loader.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 224 |
```python
########################################################################################
# Davi Frossard, 2016 #
# VGG16 implementation in TensorFlow #
# Details: #
# path_to_url~frossard/post/vgg16/ #
# #
# Model from path_to_url#file-readme-md #
# Weights from Caffe converted using path_to_url #
########################################################################################
import tensorflow as tf
import numpy as np
from scipy.misc import imread, imresize
from imagenet_classes import class_names
class vgg16:
def __init__(self, imgs, weights=None, sess=None):
self.imgs = imgs
tf.summary.image("imgs", self.imgs)
self.convlayers()
self.fc_layers()
self.probs = tf.nn.softmax(self.fc3l)
if weights is not None and sess is not None:
self.load_weights(weights, sess)
self.my_summaries = tf.summary.merge_all()
self.my_writer = tf.summary.FileWriter('tb_files', sess.graph)
def convlayers(self):
self.parameters = []
# zero-mean input
with tf.name_scope('preprocess') as scope:
mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[1, 1, 1, 3], name='img_mean')
images = self.imgs-mean
# conv1_1
with tf.name_scope('conv1_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv1_1 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv1_2
with tf.name_scope('conv1_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 64], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv1_1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv1_2 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# pool1
self.pool1 = tf.nn.max_pool(self.conv1_2,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME',
name='pool1')
# conv2_1
with tf.name_scope('conv2_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.pool1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv2_1 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv2_2
with tf.name_scope('conv2_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 128], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv2_1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv2_2 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# pool2
self.pool2 = tf.nn.max_pool(self.conv2_2,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME',
name='pool2')
# conv3_1
with tf.name_scope('conv3_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 256], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.pool2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv3_1 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv3_2
with tf.name_scope('conv3_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv3_1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv3_2 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv3_3
with tf.name_scope('conv3_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv3_2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv3_3 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# pool3
self.pool3 = tf.nn.max_pool(self.conv3_3,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME',
name='pool3')
# conv4_1
with tf.name_scope('conv4_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.pool3, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv4_1 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv4_2
with tf.name_scope('conv4_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv4_1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv4_2 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv4_3
with tf.name_scope('conv4_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv4_2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv4_3 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# pool4
self.pool4 = tf.nn.max_pool(self.conv4_3,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME',
name='pool4')
# conv5_1
with tf.name_scope('conv5_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.pool4, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv5_1 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv5_2
with tf.name_scope('conv5_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv5_1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv5_2 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# conv5_3
with tf.name_scope('conv5_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(self.conv5_2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32),
trainable=True, name='biases')
out = tf.nn.bias_add(conv, biases)
self.conv5_3 = tf.nn.relu(out, name=scope)
self.parameters += [kernel, biases]
# pool5
self.pool5 = tf.nn.max_pool(self.conv5_3,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME',
name='pool4')
def fc_layers(self):
# fc1
with tf.name_scope('fc1') as scope:
shape = int(np.prod(self.pool5.get_shape()[1:]))
fc1w = tf.Variable(tf.truncated_normal([shape, 4096],
dtype=tf.float32,
stddev=1e-1), name='weights')
fc1b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32),
trainable=True, name='biases')
pool5_flat = tf.reshape(self.pool5, [-1, shape])
fc1l = tf.nn.bias_add(tf.matmul(pool5_flat, fc1w), fc1b)
self.fc1 = tf.nn.relu(fc1l)
self.parameters += [fc1w, fc1b]
# fc2
with tf.name_scope('fc2') as scope:
fc2w = tf.Variable(tf.truncated_normal([4096, 4096],
dtype=tf.float32,
stddev=1e-1), name='weights')
fc2b = tf.Variable(tf.constant(1.0, shape=[4096], dtype=tf.float32),
trainable=True, name='biases')
fc2l = tf.nn.bias_add(tf.matmul(self.fc1, fc2w), fc2b)
self.fc2 = tf.nn.relu(fc2l)
self.parameters += [fc2w, fc2b]
# fc3
with tf.name_scope('fc3') as scope:
fc3w = tf.Variable(tf.truncated_normal([4096, 1000],
dtype=tf.float32,
stddev=1e-1), name='weights')
fc3b = tf.Variable(tf.constant(1.0, shape=[1000], dtype=tf.float32),
trainable=True, name='biases')
self.fc3l = tf.nn.bias_add(tf.matmul(self.fc2, fc3w), fc3b)
self.parameters += [fc3w, fc3b]
def load_weights(self, weight_file, sess):
weights = np.load(weight_file)
keys = sorted(weights.keys())
for i, k in enumerate(keys):
print(i, k, np.shape(weights[k]))
sess.run(self.parameters[i].assign(weights[k]))
``` | /content/code_sandbox/ch12_rank/vgg16.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 3,109 |
```python
class_names = '''tench, Tinca tinca
goldfish, Carassius auratus
great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias
tiger shark, Galeocerdo cuvieri
hammerhead, hammerhead shark
electric ray, crampfish, numbfish, torpedo
stingray
cock
hen
ostrich, Struthio camelus
brambling, Fringilla montifringilla
goldfinch, Carduelis carduelis
house finch, linnet, Carpodacus mexicanus
junco, snowbird
indigo bunting, indigo finch, indigo bird, Passerina cyanea
robin, American robin, Turdus migratorius
bulbul
jay
magpie
chickadee
water ouzel, dipper
kite
bald eagle, American eagle, Haliaeetus leucocephalus
vulture
great grey owl, great gray owl, Strix nebulosa
European fire salamander, Salamandra salamandra
common newt, Triturus vulgaris
eft
spotted salamander, Ambystoma maculatum
axolotl, mud puppy, Ambystoma mexicanum
bullfrog, Rana catesbeiana
tree frog, tree-frog
tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui
loggerhead, loggerhead turtle, Caretta caretta
leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea
mud turtle
terrapin
box turtle, box tortoise
banded gecko
common iguana, iguana, Iguana iguana
American chameleon, anole, Anolis carolinensis
whiptail, whiptail lizard
agama
frilled lizard, Chlamydosaurus kingi
alligator lizard
Gila monster, Heloderma suspectum
green lizard, Lacerta viridis
African chameleon, Chamaeleo chamaeleon
Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis
African crocodile, Nile crocodile, Crocodylus niloticus
American alligator, Alligator mississipiensis
triceratops
thunder snake, worm snake, Carphophis amoenus
ringneck snake, ring-necked snake, ring snake
hognose snake, puff adder, sand viper
green snake, grass snake
king snake, kingsnake
garter snake, grass snake
water snake
vine snake
night snake, Hypsiglena torquata
boa constrictor, Constrictor constrictor
rock python, rock snake, Python sebae
Indian cobra, Naja naja
green mamba
sea snake
horned viper, cerastes, sand viper, horned asp, Cerastes cornutus
diamondback, diamondback rattlesnake, Crotalus adamanteus
sidewinder, horned rattlesnake, Crotalus cerastes
trilobite
harvestman, daddy longlegs, Phalangium opilio
scorpion
black and gold garden spider, Argiope aurantia
barn spider, Araneus cavaticus
garden spider, Aranea diademata
black widow, Latrodectus mactans
tarantula
wolf spider, hunting spider
tick
centipede
black grouse
ptarmigan
ruffed grouse, partridge, Bonasa umbellus
prairie chicken, prairie grouse, prairie fowl
peacock
quail
partridge
African grey, African gray, Psittacus erithacus
macaw
sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita
lorikeet
coucal
bee eater
hornbill
hummingbird
jacamar
toucan
drake
red-breasted merganser, Mergus serrator
goose
black swan, Cygnus atratus
tusker
echidna, spiny anteater, anteater
platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus
wallaby, brush kangaroo
koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus
wombat
jellyfish
sea anemone, anemone
brain coral
flatworm, platyhelminth
nematode, nematode worm, roundworm
conch
snail
slug
sea slug, nudibranch
chiton, coat-of-mail shell, sea cradle, polyplacophore
chambered nautilus, pearly nautilus, nautilus
Dungeness crab, Cancer magister
rock crab, Cancer irroratus
fiddler crab
king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica
American lobster, Northern lobster, Maine lobster, Homarus americanus
spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish
crayfish, crawfish, crawdad, crawdaddy
hermit crab
isopod
white stork, Ciconia ciconia
black stork, Ciconia nigra
spoonbill
flamingo
little blue heron, Egretta caerulea
American egret, great white heron, Egretta albus
bittern
crane
limpkin, Aramus pictus
European gallinule, Porphyrio porphyrio
American coot, marsh hen, mud hen, water hen, Fulica americana
bustard
ruddy turnstone, Arenaria interpres
red-backed sandpiper, dunlin, Erolia alpina
redshank, Tringa totanus
dowitcher
oystercatcher, oyster catcher
pelican
king penguin, Aptenodytes patagonica
albatross, mollymawk
grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus
killer whale, killer, orca, grampus, sea wolf, Orcinus orca
dugong, Dugong dugon
sea lion
Chihuahua
Japanese spaniel
Maltese dog, Maltese terrier, Maltese
Pekinese, Pekingese, Peke
Shih-Tzu
Blenheim spaniel
papillon
toy terrier
Rhodesian ridgeback
Afghan hound, Afghan
basset, basset hound
beagle
bloodhound, sleuthhound
bluetick
black-and-tan coonhound
Walker hound, Walker foxhound
English foxhound
redbone
borzoi, Russian wolfhound
Irish wolfhound
Italian greyhound
whippet
Ibizan hound, Ibizan Podenco
Norwegian elkhound, elkhound
otterhound, otter hound
Saluki, gazelle hound
Scottish deerhound, deerhound
Weimaraner
Staffordshire bullterrier, Staffordshire bull terrier
American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier
Bedlington terrier
Border terrier
Kerry blue terrier
Irish terrier
Norfolk terrier
Norwich terrier
Yorkshire terrier
wire-haired fox terrier
Lakeland terrier
Sealyham terrier, Sealyham
Airedale, Airedale terrier
cairn, cairn terrier
Australian terrier
Dandie Dinmont, Dandie Dinmont terrier
Boston bull, Boston terrier
miniature schnauzer
giant schnauzer
standard schnauzer
Scotch terrier, Scottish terrier, Scottie
Tibetan terrier, chrysanthemum dog
silky terrier, Sydney silky
soft-coated wheaten terrier
West Highland white terrier
Lhasa, Lhasa apso
flat-coated retriever
curly-coated retriever
golden retriever
Labrador retriever
Chesapeake Bay retriever
German short-haired pointer
vizsla, Hungarian pointer
English setter
Irish setter, red setter
Gordon setter
Brittany spaniel
clumber, clumber spaniel
English springer, English springer spaniel
Welsh springer spaniel
cocker spaniel, English cocker spaniel, cocker
Sussex spaniel
Irish water spaniel
kuvasz
schipperke
groenendael
malinois
briard
kelpie
komondor
Old English sheepdog, bobtail
Shetland sheepdog, Shetland sheep dog, Shetland
collie
Border collie
Bouvier des Flandres, Bouviers des Flandres
Rottweiler
German shepherd, German shepherd dog, German police dog, alsatian
Doberman, Doberman pinscher
miniature pinscher
Greater Swiss Mountain dog
Bernese mountain dog
Appenzeller
EntleBucher
boxer
bull mastiff
Tibetan mastiff
French bulldog
Great Dane
Saint Bernard, St Bernard
Eskimo dog, husky
malamute, malemute, Alaskan malamute
Siberian husky
dalmatian, coach dog, carriage dog
affenpinscher, monkey pinscher, monkey dog
basenji
pug, pug-dog
Leonberg
Newfoundland, Newfoundland dog
Great Pyrenees
Samoyed, Samoyede
Pomeranian
chow, chow chow
keeshond
Brabancon griffon
Pembroke, Pembroke Welsh corgi
Cardigan, Cardigan Welsh corgi
toy poodle
miniature poodle
standard poodle
Mexican hairless
timber wolf, grey wolf, gray wolf, Canis lupus
white wolf, Arctic wolf, Canis lupus tundrarum
red wolf, maned wolf, Canis rufus, Canis niger
coyote, prairie wolf, brush wolf, Canis latrans
dingo, warrigal, warragal, Canis dingo
dhole, Cuon alpinus
African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus
hyena, hyaena
red fox, Vulpes vulpes
kit fox, Vulpes macrotis
Arctic fox, white fox, Alopex lagopus
grey fox, gray fox, Urocyon cinereoargenteus
tabby, tabby cat
tiger cat
Persian cat
Siamese cat, Siamese
Egyptian cat
cougar, puma, catamount, mountain lion, painter, panther, Felis concolor
lynx, catamount
leopard, Panthera pardus
snow leopard, ounce, Panthera uncia
jaguar, panther, Panthera onca, Felis onca
lion, king of beasts, Panthera leo
tiger, Panthera tigris
cheetah, chetah, Acinonyx jubatus
brown bear, bruin, Ursus arctos
American black bear, black bear, Ursus americanus, Euarctos americanus
ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus
sloth bear, Melursus ursinus, Ursus ursinus
mongoose
meerkat, mierkat
tiger beetle
ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle
ground beetle, carabid beetle
long-horned beetle, longicorn, longicorn beetle
leaf beetle, chrysomelid
dung beetle
rhinoceros beetle
weevil
fly
bee
ant, emmet, pismire
grasshopper, hopper
cricket
walking stick, walkingstick, stick insect
cockroach, roach
mantis, mantid
cicada, cicala
leafhopper
lacewing, lacewing fly
dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk
damselfly
admiral
ringlet, ringlet butterfly
monarch, monarch butterfly, milkweed butterfly, Danaus plexippus
cabbage butterfly
sulphur butterfly, sulfur butterfly
lycaenid, lycaenid butterfly
starfish, sea star
sea urchin
sea cucumber, holothurian
wood rabbit, cottontail, cottontail rabbit
hare
Angora, Angora rabbit
hamster
porcupine, hedgehog
fox squirrel, eastern fox squirrel, Sciurus niger
marmot
beaver
guinea pig, Cavia cobaya
sorrel
zebra
hog, pig, grunter, squealer, Sus scrofa
wild boar, boar, Sus scrofa
warthog
hippopotamus, hippo, river horse, Hippopotamus amphibius
ox
water buffalo, water ox, Asiatic buffalo, Bubalus bubalis
bison
ram, tup
bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis
ibex, Capra ibex
hartebeest
impala, Aepyceros melampus
gazelle
Arabian camel, dromedary, Camelus dromedarius
llama
weasel
mink
polecat, fitch, foulmart, foumart, Mustela putorius
black-footed ferret, ferret, Mustela nigripes
otter
skunk, polecat, wood pussy
badger
armadillo
three-toed sloth, ai, Bradypus tridactylus
orangutan, orang, orangutang, Pongo pygmaeus
gorilla, Gorilla gorilla
chimpanzee, chimp, Pan troglodytes
gibbon, Hylobates lar
siamang, Hylobates syndactylus, Symphalangus syndactylus
guenon, guenon monkey
patas, hussar monkey, Erythrocebus patas
baboon
macaque
langur
colobus, colobus monkey
proboscis monkey, Nasalis larvatus
marmoset
capuchin, ringtail, Cebus capucinus
howler monkey, howler
titi, titi monkey
spider monkey, Ateles geoffroyi
squirrel monkey, Saimiri sciureus
Madagascar cat, ring-tailed lemur, Lemur catta
indri, indris, Indri indri, Indri brevicaudatus
Indian elephant, Elephas maximus
African elephant, Loxodonta africana
lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens
giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca
barracouta, snoek
eel
coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch
rock beauty, Holocanthus tricolor
anemone fish
sturgeon
gar, garfish, garpike, billfish, Lepisosteus osseus
lionfish
puffer, pufferfish, blowfish, globefish
abacus
abaya
academic gown, academic robe, judge's robe
accordion, piano accordion, squeeze box
acoustic guitar
aircraft carrier, carrier, flattop, attack aircraft carrier
airliner
airship, dirigible
altar
ambulance
amphibian, amphibious vehicle
analog clock
apiary, bee house
apron
ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin
assault rifle, assault gun
backpack, back pack, knapsack, packsack, rucksack, haversack
bakery, bakeshop, bakehouse
balance beam, beam
balloon
ballpoint, ballpoint pen, ballpen, Biro
Band Aid
banjo
bannister, banister, balustrade, balusters, handrail
barbell
barber chair
barbershop
barn
barometer
barrel, cask
barrow, garden cart, lawn cart, wheelbarrow
baseball
basketball
bassinet
bassoon
bathing cap, swimming cap
bath towel
bathtub, bathing tub, bath, tub
beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon
beacon, lighthouse, beacon light, pharos
beaker
bearskin, busby, shako
beer bottle
beer glass
bell cote, bell cot
bib
bicycle-built-for-two, tandem bicycle, tandem
bikini, two-piece
binder, ring-binder
binoculars, field glasses, opera glasses
birdhouse
boathouse
bobsled, bobsleigh, bob
bolo tie, bolo, bola tie, bola
bonnet, poke bonnet
bookcase
bookshop, bookstore, bookstall
bottlecap
bow
bow tie, bow-tie, bowtie
brass, memorial tablet, plaque
brassiere, bra, bandeau
breakwater, groin, groyne, mole, bulwark, seawall, jetty
breastplate, aegis, egis
broom
bucket, pail
buckle
bulletproof vest
bullet train, bullet
butcher shop, meat market
cab, hack, taxi, taxicab
caldron, cauldron
candle, taper, wax light
cannon
canoe
can opener, tin opener
cardigan
car mirror
carousel, carrousel, merry-go-round, roundabout, whirligig
carpenter's kit, tool kit
carton
car wheel
cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM
cassette
cassette player
castle
catamaran
CD player
cello, violoncello
cellular telephone, cellular phone, cellphone, cell, mobile phone
chain
chainlink fence
chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour
chain saw, chainsaw
chest
chiffonier, commode
chime, bell, gong
china cabinet, china closet
Christmas stocking
church, church building
cinema, movie theater, movie theatre, movie house, picture palace
cleaver, meat cleaver, chopper
cliff dwelling
cloak
clog, geta, patten, sabot
cocktail shaker
coffee mug
coffeepot
coil, spiral, volute, whorl, helix
combination lock
computer keyboard, keypad
confectionery, confectionary, candy store
container ship, containership, container vessel
convertible
corkscrew, bottle screw
cornet, horn, trumpet, trump
cowboy boot
cowboy hat, ten-gallon hat
cradle
crane
crash helmet
crate
crib, cot
Crock Pot
croquet ball
crutch
cuirass
dam, dike, dyke
desk
desktop computer
dial telephone, dial phone
diaper, nappy, napkin
digital clock
digital watch
dining table, board
dishrag, dishcloth
dishwasher, dish washer, dishwashing machine
disk brake, disc brake
dock, dockage, docking facility
dogsled, dog sled, dog sleigh
dome
doormat, welcome mat
drilling platform, offshore rig
drum, membranophone, tympan
drumstick
dumbbell
Dutch oven
electric fan, blower
electric guitar
electric locomotive
entertainment center
envelope
espresso maker
face powder
feather boa, boa
file, file cabinet, filing cabinet
fireboat
fire engine, fire truck
fire screen, fireguard
flagpole, flagstaff
flute, transverse flute
folding chair
football helmet
forklift
fountain
fountain pen
four-poster
freight car
French horn, horn
frying pan, frypan, skillet
fur coat
garbage truck, dustcart
gasmask, respirator, gas helmet
gas pump, gasoline pump, petrol pump, island dispenser
goblet
go-kart
golf ball
golfcart, golf cart
gondola
gong, tam-tam
gown
grand piano, grand
greenhouse, nursery, glasshouse
grille, radiator grille
grocery store, grocery, food market, market
guillotine
hair slide
hair spray
half track
hammer
hamper
hand blower, blow dryer, blow drier, hair dryer, hair drier
hand-held computer, hand-held microcomputer
handkerchief, hankie, hanky, hankey
hard disc, hard disk, fixed disk
harmonica, mouth organ, harp, mouth harp
harp
harvester, reaper
hatchet
holster
home theater, home theatre
honeycomb
hook, claw
hoopskirt, crinoline
horizontal bar, high bar
horse cart, horse-cart
hourglass
iPod
iron, smoothing iron
jack-o'-lantern
jean, blue jean, denim
jeep, landrover
jersey, T-shirt, tee shirt
jigsaw puzzle
jinrikisha, ricksha, rickshaw
joystick
kimono
knee pad
knot
lab coat, laboratory coat
ladle
lampshade, lamp shade
laptop, laptop computer
lawn mower, mower
lens cap, lens cover
letter opener, paper knife, paperknife
library
lifeboat
lighter, light, igniter, ignitor
limousine, limo
liner, ocean liner
lipstick, lip rouge
Loafer
lotion
loudspeaker, speaker, speaker unit, loudspeaker system, speaker system
loupe, jeweler's loupe
lumbermill, sawmill
magnetic compass
mailbag, postbag
mailbox, letter box
maillot
maillot, tank suit
manhole cover
maraca
marimba, xylophone
mask
matchstick
maypole
maze, labyrinth
measuring cup
medicine chest, medicine cabinet
megalith, megalithic structure
microphone, mike
microwave, microwave oven
military uniform
milk can
minibus
miniskirt, mini
minivan
missile
mitten
mixing bowl
mobile home, manufactured home
Model T
modem
monastery
monitor
moped
mortar
mortarboard
mosque
mosquito net
motor scooter, scooter
mountain bike, all-terrain bike, off-roader
mountain tent
mouse, computer mouse
mousetrap
moving van
muzzle
nail
neck brace
necklace
nipple
notebook, notebook computer
obelisk
oboe, hautboy, hautbois
ocarina, sweet potato
odometer, hodometer, mileometer, milometer
oil filter
organ, pipe organ
oscilloscope, scope, cathode-ray oscilloscope, CRO
overskirt
oxcart
oxygen mask
packet
paddle, boat paddle
paddlewheel, paddle wheel
padlock
paintbrush
pajama, pyjama, pj's, jammies
palace
panpipe, pandean pipe, syrinx
paper towel
parachute, chute
parallel bars, bars
park bench
parking meter
passenger car, coach, carriage
patio, terrace
pay-phone, pay-station
pedestal, plinth, footstall
pencil box, pencil case
pencil sharpener
perfume, essence
Petri dish
photocopier
pick, plectrum, plectron
pickelhaube
picket fence, paling
pickup, pickup truck
pier
piggy bank, penny bank
pill bottle
pillow
ping-pong ball
pinwheel
pirate, pirate ship
pitcher, ewer
plane, carpenter's plane, woodworking plane
planetarium
plastic bag
plate rack
plow, plough
plunger, plumber's helper
Polaroid camera, Polaroid Land camera
pole
police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria
poncho
pool table, billiard table, snooker table
pop bottle, soda bottle
pot, flowerpot
potter's wheel
power drill
prayer rug, prayer mat
printer
prison, prison house
projectile, missile
projector
puck, hockey puck
punching bag, punch bag, punching ball, punchball
purse
quill, quill pen
quilt, comforter, comfort, puff
racer, race car, racing car
racket, racquet
radiator
radio, wireless
radio telescope, radio reflector
rain barrel
recreational vehicle, RV, R.V.
reel
reflex camera
refrigerator, icebox
remote control, remote
restaurant, eating house, eating place, eatery
revolver, six-gun, six-shooter
rifle
rocking chair, rocker
rotisserie
rubber eraser, rubber, pencil eraser
rugby ball
rule, ruler
running shoe
safe
safety pin
saltshaker, salt shaker
sandal
sarong
sax, saxophone
scabbard
scale, weighing machine
school bus
schooner
scoreboard
screen, CRT screen
screw
screwdriver
seat belt, seatbelt
sewing machine
shield, buckler
shoe shop, shoe-shop, shoe store
shoji
shopping basket
shopping cart
shovel
shower cap
shower curtain
ski
ski mask
sleeping bag
slide rule, slipstick
sliding door
slot, one-armed bandit
snorkel
snowmobile
snowplow, snowplough
soap dispenser
soccer ball
sock
solar dish, solar collector, solar furnace
sombrero
soup bowl
space bar
space heater
space shuttle
spatula
speedboat
spider web, spider's web
spindle
sports car, sport car
spotlight, spot
stage
steam locomotive
steel arch bridge
steel drum
stethoscope
stole
stone wall
stopwatch, stop watch
stove
strainer
streetcar, tram, tramcar, trolley, trolley car
stretcher
studio couch, day bed
stupa, tope
submarine, pigboat, sub, U-boat
suit, suit of clothes
sundial
sunglass
sunglasses, dark glasses, shades
sunscreen, sunblock, sun blocker
suspension bridge
swab, swob, mop
sweatshirt
swimming trunks, bathing trunks
swing
switch, electric switch, electrical switch
syringe
table lamp
tank, army tank, armored combat vehicle, armoured combat vehicle
tape player
teapot
teddy, teddy bear
television, television system
tennis ball
thatch, thatched roof
theater curtain, theatre curtain
thimble
thresher, thrasher, threshing machine
throne
tile roof
toaster
tobacco shop, tobacconist shop, tobacconist
toilet seat
torch
totem pole
tow truck, tow car, wrecker
toyshop
tractor
trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi
tray
trench coat
tricycle, trike, velocipede
trimaran
tripod
triumphal arch
trolleybus, trolley coach, trackless trolley
trombone
tub, vat
turnstile
typewriter keyboard
umbrella
unicycle, monocycle
upright, upright piano
vacuum, vacuum cleaner
vase
vault
velvet
vending machine
vestment
viaduct
violin, fiddle
volleyball
waffle iron
wall clock
wallet, billfold, notecase, pocketbook
wardrobe, closet, press
warplane, military plane
washbasin, handbasin, washbowl, lavabo, wash-hand basin
washer, automatic washer, washing machine
water bottle
water jug
water tower
whiskey jug
whistle
wig
window screen
window shade
Windsor tie
wine bottle
wing
wok
wooden spoon
wool, woolen, woollen
worm fence, snake fence, snake-rail fence, Virginia fence
wreck
yawl
yurt
web site, website, internet site, site
comic book
crossword puzzle, crossword
street sign
traffic light, traffic signal, stoplight
book jacket, dust cover, dust jacket, dust wrapper
menu
plate
guacamole
consomme
hot pot, hotpot
trifle
ice cream, icecream
ice lolly, lolly, lollipop, popsicle
French loaf
bagel, beigel
pretzel
cheeseburger
hotdog, hot dog, red hot
mashed potato
head cabbage
broccoli
cauliflower
zucchini, courgette
spaghetti squash
acorn squash
butternut squash
cucumber, cuke
artichoke, globe artichoke
bell pepper
cardoon
mushroom
Granny Smith
strawberry
orange
lemon
fig
pineapple, ananas
banana
jackfruit, jak, jack
custard apple
pomegranate
hay
carbonara
chocolate sauce, chocolate syrup
dough
meat loaf, meatloaf
pizza, pizza pie
potpie
burrito
red wine
espresso
cup
eggnog
alp
bubble
cliff, drop, drop-off
coral reef
geyser
lakeside, lakeshore
promontory, headland, head, foreland
sandbar, sand bar
seashore, coast, seacoast, sea-coast
valley, vale
volcano
ballplayer, baseball player
groom, bridegroom
scuba diver
rapeseed
daisy
yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum
corn
acorn
hip, rose hip, rosehip
buckeye, horse chestnut, conker
coral fungus
agaric
gyromitra
stinkhorn, carrion fungus
earthstar
hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa
bolete
ear, spike, capitulum
toilet tissue, toilet paper, bathroom tissue'''.split("\n")
``` | /content/code_sandbox/ch12_rank/imagenet_classes.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 6,917 |
```python
from matplotlib import pyplot as plt
import numpy as np
import random
import tensorflow as tf
import random
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
from pandas_datareader import data
import datetime
import requests_cache
class DecisionPolicy:
def select_action(self, current_state, step):
pass
def update_q(self, state, action, reward, next_state):
pass
class RandomDecisionPolicy(DecisionPolicy):
def __init__(self, actions):
self.actions = actions
def select_action(self, current_state, step):
action = self.actions[random.randint(0, len(self.actions) - 1)]
return action
class QLearningDecisionPolicy(DecisionPolicy):
def __init__(self, actions, input_dim):
self.epsilon = 0.9
self.gamma = 0.001
self.actions = actions
output_dim = len(actions)
h1_dim = 200
self.x = tf.placeholder(tf.float32, [None, input_dim])
self.y = tf.placeholder(tf.float32, [output_dim])
W1 = tf.Variable(tf.random_normal([input_dim, h1_dim]))
b1 = tf.Variable(tf.constant(0.1, shape=[h1_dim]))
h1 = tf.nn.relu(tf.matmul(self.x, W1) + b1)
W2 = tf.Variable(tf.random_normal([h1_dim, output_dim]))
b2 = tf.Variable(tf.constant(0.1, shape=[output_dim]))
self.q = tf.nn.relu(tf.matmul(h1, W2) + b2)
loss = tf.square(self.y - self.q)
self.train_op = tf.train.AdagradOptimizer(0.01).minimize(loss)
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
def select_action(self, current_state, step):
threshold = min(self.epsilon, step / 1000.)
if random.random() < threshold:
# Exploit best option with probability epsilon
action_q_vals = self.sess.run(self.q, feed_dict={self.x: current_state})
action_idx = np.argmax(action_q_vals) # TODO: replace w/ tensorflow's argmax
action = self.actions[action_idx]
else:
# Explore random option with probability 1 - epsilon
action = self.actions[random.randint(0, len(self.actions) - 1)]
return action
def update_q(self, state, action, reward, next_state):
action_q_vals = self.sess.run(self.q, feed_dict={self.x: state})
next_action_q_vals = self.sess.run(self.q, feed_dict={self.x: next_state})
next_action_idx = np.argmax(next_action_q_vals)
action_q_vals[0, next_action_idx] = reward + self.gamma * next_action_q_vals[0, next_action_idx]
action_q_vals = np.squeeze(np.asarray(action_q_vals))
self.sess.run(self.train_op, feed_dict={self.x: state, self.y: action_q_vals})
def run_simulation(policy, initial_budget, initial_num_stocks, prices, hist, debug=False):
budget = initial_budget
num_stocks = initial_num_stocks
share_value = 0
transitions = list()
for i in range(len(prices) - hist - 1):
if i % 100 == 0:
print('progress {:.2f}%'.format(float(100*i) / (len(prices) - hist - 1)))
current_state = np.asmatrix(np.hstack((prices[i:i+hist], budget, num_stocks)))
current_portfolio = budget + num_stocks * share_value
action = policy.select_action(current_state, i)
share_value = float(prices[i + hist + 1])
if action == 'Buy' and budget >= share_value:
budget -= share_value
num_stocks += 1
elif action == 'Sell' and num_stocks > 0:
budget += share_value
num_stocks -= 1
else:
action = 'Hold'
new_portfolio = budget + num_stocks * share_value
reward = new_portfolio - current_portfolio
next_state = np.asmatrix(np.hstack((prices[i+1:i+hist+1], budget, num_stocks)))
transitions.append((current_state, action, reward, next_state))
policy.update_q(current_state, action, reward, next_state)
portfolio = budget + num_stocks * share_value
if debug:
print('${}\t{} shares'.format(budget, num_stocks))
return portfolio
def run_simulations(policy, budget, num_stocks, prices, hist):
num_tries = 10
final_portfolios = list()
for i in range(num_tries):
final_portfolio = run_simulation(policy, budget, num_stocks, prices, hist)
final_portfolios.append(final_portfolio)
avg, std = np.mean(final_portfolios), np.std(final_portfolios)
return avg, std
def get_prices(share_symbol, start_date, end_date):
expire_after = datetime.timedelta(days=3)
session = requests_cache.CachedSession(cache_name='cache', backend='sqlite', expire_after=expire_after)
stock_hist = data.DataReader(share_symbol, 'iex', start_date, end_date, session=session)
open_prices = stock_hist['open']
return open_prices.values.tolist()
def plot_prices(prices):
plt.title('Opening stock prices')
plt.xlabel('day')
plt.ylabel('price ($)')
plt.plot(prices)
plt.savefig('prices.png')
if __name__ == '__main__':
prices = get_prices('MSFT', '2013-07-22', '2018-07-22')
plot_prices(prices)
actions = ['Buy', 'Sell', 'Hold']
hist = 200
# policy = RandomDecisionPolicy(actions)
policy = QLearningDecisionPolicy(actions, hist + 2)
budget = 1000.0
num_stocks = 0
avg, std = run_simulations(policy, budget, num_stocks, prices, hist)
print(avg, std)
``` | /content/code_sandbox/ch08_rl/rl.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 1,332 |
```python
import tensorflow as tf
import numpy as np
def get_batch(X, size):
a = np.random.choice(len(X), size, replace=False)
return X[a]
class Autoencoder:
def __init__(self, input_dim, hidden_dim, epoch=1000, batch_size=10, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim])
with tf.name_scope('encode'):
weights = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([hidden_dim]), name='biases')
encoded = tf.nn.sigmoid(tf.matmul(x, weights) + biases)
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([input_dim]), name='biases')
decoded = tf.matmul(encoded, weights) + biases
self.x = x
self.encoded = encoded
self.decoded = decoded
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.sub(self.x, self.decoded))))
self.all_loss = tf.sqrt(tf.reduce_mean(tf.square(tf.sub(self.x, self.decoded)), 1))
self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
self.saver = tf.train.Saver()
def train(self, data):
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(self.epoch):
for j in range(500):
batch_data = get_batch(data, self.batch_size)
l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data})
if i % 10 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
self.saver.save(sess, './model.ckpt')
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
``` | /content/code_sandbox/ch07_autoencoder/autoencoder_batch.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 578 |
```python
from autoencoder import Autoencoder
from sklearn import datasets
hidden_dim = 1
data = datasets.load_iris().data
input_dim = len(data[0])
ae = Autoencoder(input_dim, hidden_dim)
ae.train(data)
ae.test([[8, 4, 6, 2]])
``` | /content/code_sandbox/ch07_autoencoder/main.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 64 |
```python
import tensorflow as tf
import numpy as np
def get_batch(X, size):
a = np.random.choice(len(X), size, replace=False)
return X[a]
class Autoencoder:
def __init__(self, input_dim, hidden_dim, epoch=1000, batch_size=50, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim])
with tf.name_scope('encode'):
weights = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32))
biases = tf.Variable(tf.zeros([hidden_dim]))
encoded = tf.nn.sigmoid(tf.matmul(x, weights) + biases)
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32))
biases = tf.Variable(tf.zeros([input_dim]))
decoded = tf.matmul(encoded, weights) + biases
self.x = x
self.encoded = encoded
self.decoded = decoded
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.sub(self.x, self.decoded))))
self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
self.saver = tf.train.Saver()
def train(self, data):
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(self.epoch):
for j in range(50):
batch_data = get_batch(data, self.batch_size)
l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data})
if i % 10 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
self.saver.save(sess, './model.ckpt')
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
``` | /content/code_sandbox/ch07_autoencoder/denoising_autoencoder.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 536 |
```python
import tensorflow as tf
import numpy as np
def get_batch(X, size):
a = np.random.choice(len(X), size, replace=False)
return X[a]
class Autoencoder:
def __init__(self, input_dim, hidden_dim, epoch=1000, batch_size=50, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim])
with tf.name_scope('encode'):
weights = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([hidden_dim]), name='biases')
encoded = tf.nn.sigmoid(tf.matmul(x, weights) + biases)
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([input_dim]), name='biases')
decoded = tf.matmul(encoded, weights) + biases
self.x = x
self.encoded = encoded
self.decoded = decoded
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.x, self.decoded))))
self.train_op = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)
self.saver = tf.train.Saver()
def train(self, data):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(self.epoch):
for j in range(np.shape(data)[0] // self.batch_size):
batch_data = get_batch(data, self.batch_size)
l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data})
if i % 10 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
self.saver.save(sess, './model.ckpt')
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
def classify(self, data, labels):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
reconstructed = reconstructed[0]
# loss = sess.run(self.all_loss, feed_dict={self.x: data})
print('data', np.shape(data))
print('reconstructed', np.shape(reconstructed))
loss = np.sqrt(np.mean(np.square(data - reconstructed), axis=1))
print('loss', np.shape(loss))
horse_indices = np.where(labels == 7)[0]
not_horse_indices = np.where(labels != 7)[0]
horse_loss = np.mean(loss[horse_indices])
not_horse_loss = np.mean(loss[not_horse_indices])
print('horse', horse_loss)
print('not horse', not_horse_loss)
return hidden
def decode(self, encoding):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
reconstructed = sess.run(self.decoded, feed_dict={self.encoded: encoding})
img = np.reshape(reconstructed, (32, 32))
return img
``` | /content/code_sandbox/ch07_autoencoder/autoencoder.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 845 |
```python
import tensorflow as tf
import numpy as np
import time
def get_batch(X, Xn, size):
a = np.random.choice(len(X), size, replace=False)
return X[a], Xn[a]
class Denoiser:
def __init__(self, input_dim, hidden_dim, epoch=10000, batch_size=50, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
self.x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim], name='x')
self.x_noised = tf.placeholder(dtype=tf.float32, shape=[None, input_dim], name='x_noised')
with tf.name_scope('encode'):
self.weights1 = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32), name='weights')
self.biases1 = tf.Variable(tf.zeros([hidden_dim]), name='biases')
self.encoded = tf.nn.sigmoid(tf.matmul(self.x_noised, self.weights1) + self.biases1, name='encoded')
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([input_dim]), name='biases')
self.decoded = tf.matmul(self.encoded, weights) + biases
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.sub(self.x, self.decoded))))
self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
self.saver = tf.train.Saver()
def add_noise(self, data):
noise_type = 'mask-0.2'
if noise_type == 'gaussian':
n = np.random.normal(0, 0.1, np.shape(data))
return data + n
if 'mask' in noise_type:
frac = float(noise_type.split('-')[1])
temp = np.copy(data)
for i in temp:
n = np.random.choice(len(i), round(frac * len(i)), replace=False)
i[n] = 0
return temp
def train(self, data):
data_noised = self.add_noise(data)
with open('log.csv', 'w') as writer:
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(self.epoch):
for j in range(50):
batch_data, batch_data_noised = get_batch(data, data_noised, self.batch_size)
l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data, self.x_noised: batch_data_noised})
if i % 10 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
epoch_time = int(time.time())
row_str = str(epoch_time) + ',' + str(i) + ',' + str(l) + '\n'
writer.write(row_str)
writer.flush()
self.saver.save(sess, './model.ckpt')
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
``` | /content/code_sandbox/ch07_autoencoder/denoiser.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 799 |
```python
# path_to_url~kriz/cifar-10-python.tar.gz
import cPickle
import numpy as np
from autoencoder import Autoencoder
#
# def grayscale(x):
# gray = np.zeros(len(x)/3)
# for i in range(len(x)/3):
# gray[i] = (x[i] + x[2*i] + x[3*i]) / 3
def grayscale(a):
return a.reshape(a.shape[0], 3, 32, 32).mean(1).reshape(a.shape[0], -1)
def unpickle(file):
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
names = unpickle('./cifar-10-batches-py/batches.meta')['label_names']
data, labels = [], []
for i in range(1, 6):
filename = './cifar-10-batches-py/data_batch_' + str(i)
batch_data = unpickle(filename)
if len(data) > 0:
data = np.vstack((data, batch_data['data']))
labels = np.vstack((labels, batch_data['labels']))
else:
data = batch_data['data']
labels = batch_data['labels']
data = grayscale(data)
x = np.matrix(data)
y = np.array(labels)
horse_indices = np.where(y == 7)[0]
horse_x = x[horse_indices]
print(np.shape(horse_x)) # (5000, 3072)
input_dim = np.shape(horse_x)[1]
hidden_dim = 100
ae = Autoencoder(input_dim, hidden_dim)
ae.train(horse_x)
test_data = unpickle('./cifar-10-batches-py/test_batch')
test_x = grayscale(test_data['data'])
test_labels = np.array(test_data['labels'])
encoding = ae.classify(test_x, test_labels)
encoding = np.matrix(encoding)
from matplotlib import pyplot as plt
# encoding = np.matrix(np.random.choice([0, 1], size=(hidden_dim,)))
original_img = np.reshape(test_x[7,:], (32,32))
plt.imshow(original_img, cmap='Greys_r')
plt.show()
print(np.size(encoding))
while(True):
img = ae.decode(encoding)
plt.imshow(img, cmap='Greys_r')
plt.show()
rand_idx = np.random.randint(np.size(encoding))
encoding[0,rand_idx] = np.random.randint(2)
``` | /content/code_sandbox/ch07_autoencoder/main_imgs.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 524 |
```python
from autoencoder import Autoencoder
from scipy.misc import imread, imresize, imsave
import numpy as np
import h5py
def zero_pad(num, pad):
return format(num, '0' + str(pad))
data_dir = '../vids/'
filename_prefix = 'raw_rgb_'
hidden_dim = 1000
filepath = data_dir + str(1) + '/' + filename_prefix + zero_pad(20, 5) + '.png'
img = imresize(imread(filepath, True), 1. / 8.)
img_data = img.flatten()
ae = Autoencoder([img_data], hidden_dim)
weights, biases = ae.get_params()
print(np.shape(weights))
print(np.shape([biases]))
h5f_W = h5py.File('encoder_W.h5', 'w')
h5f_W.create_dataset('dataset_1', data=weights)
h5f_W.close()
h5f_b = h5py.File('encoder_b.h5', 'w')
h5f_b.create_dataset('dataset_1', data=[biases])
h5f_b.close()
``` | /content/code_sandbox/ch07_autoencoder/export_parameters.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 231 |
```python
import numpy as np
import tensorflow as tf
# initial parameters can be learned on training data
# theory reference path_to_url~jurafsky/slp3/8.pdf
# code reference path_to_url
class HMM(object):
def __init__(self, initial_prob, trans_prob, obs_prob):
self.N = np.size(initial_prob)
self.initial_prob = initial_prob
self.trans_prob = trans_prob
self.obs_prob = obs_prob
self.emission = tf.constant(obs_prob)
assert self.initial_prob.shape == (self.N, 1)
assert self.trans_prob.shape == (self.N, self.N)
assert self.obs_prob.shape[0] == self.N
self.obs = tf.placeholder(tf.int32)
self.fwd = tf.placeholder(tf.float64)
self.viterbi = tf.placeholder(tf.float64)
def get_emission(self, obs_idx):
slice_location = [0, obs_idx]
num_rows = tf.shape(self.emission)[0]
slice_shape = [num_rows, 1]
return tf.slice(self.emission, slice_location, slice_shape)
def forward_init_op(self):
obs_prob = self.get_emission(self.obs)
fwd = tf.mul(self.initial_prob, obs_prob)
return fwd
def forward_op(self):
transitions = tf.matmul(self.fwd, tf.transpose(self.get_emission(self.obs)))
weighted_transitions = transitions * self.trans_prob
fwd = tf.reduce_sum(weighted_transitions, 0)
return tf.reshape(fwd, tf.shape(self.fwd))
def decode_op(self):
transitions = tf.matmul(self.viterbi, tf.transpose(self.get_emission(self.obs)))
weighted_transitions = transitions * self.trans_prob
viterbi = tf.reduce_max(weighted_transitions, 0)
return tf.reshape(viterbi, tf.shape(self.viterbi))
def backpt_op(self):
back_transitions = tf.matmul(self.viterbi, np.ones((1, self.N)))
weighted_back_transitions = back_transitions * self.trans_prob
return tf.argmax(weighted_back_transitions, 0)
def forward_algorithm(sess, hmm, observations):
fwd = sess.run(hmm.forward_init_op(), feed_dict={hmm.obs: observations[0]})
for t in range(1, len(observations)):
fwd = sess.run(hmm.forward_op(), feed_dict={hmm.obs: observations[t], hmm.fwd: fwd})
prob = sess.run(tf.reduce_sum(fwd))
return prob
def viterbi_decode(sess, hmm, observations):
viterbi = sess.run(hmm.forward_init_op(), feed_dict={hmm.obs: observations[0]})
backpts = np.ones((hmm.N, len(observations)), 'int32') * -1
for t in range(1, len(observations)):
viterbi, backpt = sess.run([hmm.decode_op(), hmm.backpt_op()],
feed_dict={hmm.obs: observations[t],
hmm.viterbi: viterbi})
backpts[:, t] = backpt
tokens = [viterbi[:, -1].argmax()]
for i in range(len(observations) - 1, 0, -1):
tokens.append(backpts[tokens[-1], i])
return tokens[::-1]
if __name__ == '__main__':
states = ('Healthy', 'Fever')
observations = ('normal', 'cold', 'dizzy')
start_probability = {'Healthy': 0.6, 'Fever': 0.4}
transition_probability = {
'Healthy': {'Healthy': 0.7, 'Fever': 0.3},
'Fever': {'Healthy': 0.4, 'Fever': 0.6}
}
emission_probability = {
'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},
'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6}
}
initial_prob = np.array([[0.6], [0.4]])
trans_prob = np.array([[0.7, 0.3], [0.4, 0.6]])
obs_prob = np.array([[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]])
hmm = HMM(initial_prob=initial_prob, trans_prob=trans_prob, obs_prob=obs_prob)
observations = [0, 1, 1, 2, 1]
with tf.Session() as sess:
prob = forward_algorithm(sess, hmm, observations)
print('Probability of observing {} is {}'.format(observations, prob))
seq = viterbi_decode(sess, hmm, observations)
print('Most likely hidden states are {}'.format(seq))
``` | /content/code_sandbox/ch06_hmm/hmm.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 1,060 |
```python
import numpy as np
import tensorflow as tf
class HMM(object):
def __init__(self, initial_prob, trans_prob, obs_prob):
self.N = np.size(initial_prob)
self.initial_prob = initial_prob
self.trans_prob = trans_prob
self.emission = tf.constant(obs_prob)
assert self.initial_prob.shape == (self.N, 1)
assert self.trans_prob.shape == (self.N, self.N)
assert obs_prob.shape[0] == self.N
self.obs_idx = tf.placeholder(tf.int32)
self.fwd = tf.placeholder(tf.float64)
def get_emission(self, obs_idx):
slice_location = [0, obs_idx]
num_rows = tf.shape(self.emission)[0]
slice_shape = [num_rows, 1]
return tf.slice(self.emission, slice_location, slice_shape)
def forward_init_op(self):
obs_prob = self.get_emission(self.obs_idx)
fwd = tf.mul(self.initial_prob, obs_prob)
return fwd
def forward_op(self):
transitions = tf.matmul(self.fwd, tf.transpose(self.get_emission(self.obs_idx)))
weighted_transitions = transitions * self.trans_prob
fwd = tf.reduce_sum(weighted_transitions, 0)
return tf.reshape(fwd, tf.shape(self.fwd))
def forward_algorithm(sess, hmm, observations):
fwd = sess.run(hmm.forward_init_op(), feed_dict={hmm.obs_idx: observations[0]})
for t in range(1, len(observations)):
fwd = sess.run(hmm.forward_op(), feed_dict={hmm.obs_idx: observations[t], hmm.fwd: fwd})
prob = sess.run(tf.reduce_sum(fwd))
return prob
if __name__ == '__main__':
initial_prob = np.array([[0.6], [0.4]])
trans_prob = np.array([[0.7, 0.3], [0.4, 0.6]])
obs_prob = np.array([[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]])
hmm = HMM(initial_prob=initial_prob, trans_prob=trans_prob, obs_prob=obs_prob)
observations = [0, 1, 1, 2, 1]
with tf.Session() as sess:
prob = forward_algorithm(sess, hmm, observations)
print('Probability of observing {} is {}'.format(observations, prob))
``` | /content/code_sandbox/ch06_hmm/forward.py | python | 2016-03-06T23:30:57 | 2024-08-13T14:25:18 | TensorFlow-Book | BinRoot/TensorFlow-Book | 4,454 | 531 |
```shell
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#!/bin/sh
echo "Configuring CMake for XCode."
mkdir build-osx-xcode
cd build-osx-xcode
cmake -G Xcode ..
``` | /content/code_sandbox/Configure_XCode.sh | shell | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 254 |
```yaml
version: 1.0.{build}
branches:
only:
- master
- staging_master
image: Visual Studio 2017
clone_depth: 1
install:
- .\Configure_MSVC.bat
# - cd build-msvc
build:
parallel: true
project: build-msvc\NativeJIT.sln
test_script:
- cd build-msvc
- ctest -C Debug --verbose
# TODO: Add Release tests here too.
``` | /content/code_sandbox/appveyor.yml | yaml | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 107 |
```shell
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#!/bin/sh
debugType="RELEASE"
if [ "$#" -eq 1 ]; then
debugType="DEBUG"
fi
echo "Configuring CMake for make with $debugType build."
mkdir build-ninja
cd build-ninja
cmake -DCMAKE_BUILD_TYPE=$debugType -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -G "Ninja" ..
``` | /content/code_sandbox/Configure_Ninja.sh | shell | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 297 |
```shell
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#!/bin/sh
echo "Configuring CMake for make."
mkdir build-make
cd build-make
cmake -G "Unix Makefiles" ..
``` | /content/code_sandbox/Configure_Make.sh | shell | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 250 |
```batchfile
rem Permission is hereby granted, free of charge, to any person obtaining a copy
rem of this software and associated documentation files (the "Software"), to deal
rem in the Software without restriction, including without limitation the rights
rem to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
rem copies of the Software, and to permit persons to whom the Software is
rem furnished to do so, subject to the following conditions:
rem The above copyright notice and this permission notice shall be included in
rem all copies or substantial portions of the Software.
rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
rem IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
rem FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
rem AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
rem LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
rem OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
rem THE SOFTWARE.
setlocal
mkdir build-make
pushd build-make
cmake -G "MinGW Makefiles" ..
popd
``` | /content/code_sandbox/Configure_Make.bat | batchfile | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 245 |
```batchfile
rem Permission is hereby granted, free of charge, to any person obtaining a copy
rem of this software and associated documentation files (the "Software"), to deal
rem in the Software without restriction, including without limitation the rights
rem to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
rem copies of the Software, and to permit persons to whom the Software is
rem furnished to do so, subject to the following conditions:
rem The above copyright notice and this permission notice shall be included in
rem all copies or substantial portions of the Software.
rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
rem IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
rem FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
rem AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
rem LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
rem OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
rem THE SOFTWARE.
setlocal
mkdir build-msvc
pushd build-msvc
cmake -G "Visual Studio 15 2017 Win64" ..
popd
``` | /content/code_sandbox/Configure_MSVC.bat | batchfile | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 252 |
```shell
#!/usr/bin/env sh
set -evx
env | sort
mkdir build || true
mkdir build/$GTEST_TARGET || true
cd build/$GTEST_TARGET
cmake -Dgtest_build_samples=ON \
-Dgmock_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-DCMAKE_CXX_FLAGS=$CXX_FLAGS \
../../$GTEST_TARGET
make
CTEST_OUTPUT_ON_FAILURE=1 make test
``` | /content/code_sandbox/googletest/travis.sh | shell | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 107 |
```yaml
version: '{build}'
os: Visual Studio 2015
environment:
matrix:
- Toolset: v140
- Toolset: v120
- Toolset: v110
- Toolset: v100
platform:
- Win32
- x64
configuration:
# - Release
- Debug
build:
verbosity: minimal
artifacts:
- path: '_build/Testing/Temporary/*'
name: test_results
before_build:
- ps: |
Write-Output "Configuration: $env:CONFIGURATION"
Write-Output "Platform: $env:PLATFORM"
$generator = switch ($env:TOOLSET)
{
"v140" {"Visual Studio 14 2015"}
"v120" {"Visual Studio 12 2013"}
"v110" {"Visual Studio 11 2012"}
"v100" {"Visual Studio 10 2010"}
}
if ($env:PLATFORM -eq "x64")
{
$generator = "$generator Win64"
}
build_script:
- ps: |
if (($env:TOOLSET -eq "v100") -and ($env:PLATFORM -eq "x64"))
{
return
}
md _build -Force | Out-Null
cd _build
& cmake -G "$generator" -DCMAKE_CONFIGURATION_TYPES="Debug;Release" -Dgtest_build_tests=ON -Dgtest_build_samples=ON -Dgmock_build_tests=ON ..
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
& cmake --build . --config $env:CONFIGURATION
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
test_script:
- ps: |
if (($env:Toolset -eq "v100") -and ($env:PLATFORM -eq "x64"))
{
return
}
& ctest -C $env:CONFIGURATION --output-on-failure
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
``` | /content/code_sandbox/googletest/appveyor.yml | yaml | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 465 |
```python
#!/usr/bin/env python
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""A script to prepare version informtion for use the gtest Info.plist file.
This script extracts the version information from the configure.ac file and
uses it to generate a header file containing the same information. The
#defines in this header file will be included in during the generation of
the Info.plist of the framework, giving the correct value to the version
shown in the Finder.
This script makes the following assumptions (these are faults of the script,
not problems with the Autoconf):
1. The AC_INIT macro will be contained within the first 1024 characters
of configure.ac
2. The version string will be 3 integers separated by periods and will be
surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first
segment represents the major version, the second represents the minor
version and the third represents the fix version.
3. No ")" character exists between the opening "(" and closing ")" of
AC_INIT, including in comments and character strings.
"""
import sys
import re
# Read the command line argument (the output directory for Version.h)
if (len(sys.argv) < 3):
print "Usage: versiongenerate.py input_dir output_dir"
sys.exit(1)
else:
input_dir = sys.argv[1]
output_dir = sys.argv[2]
# Read the first 1024 characters of the configure.ac file
config_file = open("%s/configure.ac" % input_dir, 'r')
buffer_size = 1024
opening_string = config_file.read(buffer_size)
config_file.close()
# Extract the version string from the AC_INIT macro
# The following init_expression means:
# Extract three integers separated by periods and surrounded by squre
# brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy
# (*? is the non-greedy flag) since that would pull in everything between
# the first "(" and the last ")" in the file.
version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)",
re.DOTALL)
version_values = version_expression.search(opening_string)
major_version = version_values.group(1)
minor_version = version_values.group(2)
fix_version = version_values.group(3)
# Write the version information to a header file to be included in the
# Info.plist file.
file_data = """//
// DO NOT MODIFY THIS FILE (but you can delete it)
//
// This file is autogenerated by the versiongenerate.py script. This script
// is executed in a "Run Script" build phase when creating gtest.framework. This
// header file is not used during compilation of C-source. Rather, it simply
// defines some version strings for substitution in the Info.plist. Because of
// this, we are not not restricted to C-syntax nor are we using include guards.
//
#define GTEST_VERSIONINFO_SHORT %s.%s
#define GTEST_VERSIONINFO_LONG %s.%s.%s
""" % (major_version, minor_version, major_version, minor_version, fix_version)
version_file = open("%s/Version.h" % output_dir, 'w')
version_file.write(file_data)
version_file.close()
``` | /content/code_sandbox/googletest/googletest/xcode/Scripts/versiongenerate.py | python | 2016-04-09T23:53:19 | 2024-06-29T07:05:56 | NativeJIT | BitFunnel/NativeJIT | 1,133 | 1,011 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.