broderboy + stackoverflow   177

Core Data: Query objectIDs in a predicate?
I am fetching a set of objects from a Core Data persistent store using a fetch request and a predicate. My current predicate simply checks whether an attribute is >= a certain value. This all works great, except that I want to finally exclude any objects that are currently held in an array.

I basically need to be able to exclude a set of objects, and the only way I think I can do this is to be able to get a list of objectID from my managed objects array, and create another expression in my predicate to ensure that any objects returned don't have the same objectID . I.E.@"ANY records.objectID NOT IN %@", arrayOfObjectID .

How can I do this?
stackoverflow 
yesterday by broderboy
How to Determine if PHPUnit Tests are Running?
I currently have a problem that I have to work around in legacy code to get our interaction with a PHP Extension to work properly (Singleton Testing Question ).

As such, I do not want to execute this code when running our normal production code with the application. Therefore, I need to check in regular PHP code if the code being executed is being executed as part of a test or not.

Any suggestions on how to determine this? I thought about a defined variable tied to the presence of the test files themselves (we do not ship the tests to customers) but our developers need the Extension to work normally, while the CI server needs to run the tests.

Would a Global set in the PHPUnit.xml file be recommended? Other thoughts?
stackoverflow 
4 days ago by broderboy
Prevent nginx 504 Gateway timeout using PHP set_time_limit()
I am getting 504 timeouts message from nginx when my PHP script is running longer than usual. set_time_limit(0) does not seem to prevent that! Does it not work when running php5-fpm on nginx? If so, whats the proper way of setting the time limit?

Error:

504 Gateway Time-out

nginx/1.2.7
stackoverflow 
5 days ago by broderboy
Controlling which view controller loads after receiving a push notification in SWIFT
Once I receive a push notification and swipe to open it, it just opens my app and not the VC I want.

So my question is how do I load the VC I want? I know if the app is open I would move the VC over to another inside the didReceiveRemoteNotification but how do I do it if the app isn't open? or if it is in background mode?

Also I have TWO different push notifications, so therefore I need it to move ONE of TWO different VCs. How can I tell the difference between different push notifactions?

Thanks.
stackoverflow 
7 days ago by broderboy
How do I check if a string contains a specific word?
Consider:

$a = 'How are you?';

if ($a contains 'are')

echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are') ?
stackoverflow 
8 days ago by broderboy
How to present UIAlertController when not in a view controller?
Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method called on another class. A bad thing happens there and I want to display an alert right there before control returns to the view controller.

+ (void)myUtilityMethod {

// do stuff

// something bad happened, display an alert.

}

This was possible with UIAlertView (but perhaps not quite proper).

In this case, how do you present a UIAlertController , right there in myUtilityMethod ?
stackoverflow 
8 days ago by broderboy
Fire a method from a Static Cell in a Table view Controller
In my code i have a table with static cell inside storyboards. I'm trying to fire a method upon clicking the last static cell.

What should i write in the code to make this happen. How can i refer static cells inside the code without firing error.
stackoverflow 
9 days ago by broderboy
Make column not nullable in a Laravel migration
I'm writing a migration to make certain columns in a table nullable right now. For the down function, I of course want to make those columns not nullable again. I looked through the schema builder docs , but couldn't see a way to do this.

Any help would be appreciated.
stackoverflow 
9 days ago by broderboy
How to update pods to Swift 3.0
Currently in the process of migrating to Swift 3.0. This is my first time doing anything like this and I am not entirely sure how to deal with the various pods I am using. For example I am using the pod SwiftDate: https://github.com/malcommac/SwiftDate . The Swift 3.0 branch isn't on the master so I assume running pod update won't pull the Swift 3.0 version. Am I correct in putting pod:

'SwiftDate', :git => 'https://github.com/malcommac/SwiftDate.git', :branch => 'feature/swift-3.0'

into my podfile and then running the update? Checking the github page seems this is the correct branch. Do branches only need to be specified like this when the Swift 3.0 version isn't on the master? Any tips and pointers on this would be greatly appreciated! Thanks!
stackoverflow 
13 days ago by broderboy
CocoaPods and Swift 3.0
I just want to try Swift 3.0 in one of my projects. Xcode open the migration window to update my project to use Swift 3.0.

The problem is, I just want to to update my project, and leave the Pods project untouched because any changes will be discard after I run the pod install again.

Anyone already have a solution for that?
stackoverflow 
13 days ago by broderboy
Swift, could not cast value of type
I created a subclass of UICollectionViewController and called it LibraryCollectionViewController , and marked both checkboxes for the project and test. Also it's storyboard id is LibraryCollectionViewController and set its corresponding class on interface builder.

Being new to Swift and iOS Testing I went and attempted to instantiate said view controller inside my test case as follows:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let libraryCollectionVC = storyboard.instantiateViewControllerWithIdentifier("LibraryCollectionViewController") as! LibraryCollectionViewController

And I'm getting the following error:

Could not cast value of type 'MyApp.LibraryCollectionViewController' (0x1010b01f0) to 'MyAppTests.LibraryCollectionViewController' (0x10bd7f580).

So it is clear that it isn't casting, but as I'm still new to Swift, I find myself unable to determine if the error itself is being caused by:

I did something wrong when creating the subclass and I'm referencing a different one (Ergo the MyApp.[vc] vs MyAppTests.[vc])

The casting using as! is incorrect

Any other reason

Any help would be appreciate, thanks in advance.

Update 1: When I was creating the view controller, the last step shows 2 checkboxes under a Target header, I enabled both of them, could that be the cause?
stackoverflow 
13 days ago by broderboy
How do I get a PHP class constructor to call its parent's parent's constructor
I need to have a class constructor in PHP call its parent's parent's (grandparent?) constructor without calling the parent constructor.

// main class that everything inherits

class Grandpa

{

public function __construct()

{

}

}

class Papa extends Grandpa

{

public function __construct()

{

// call Grandpa's constructor

parent::__construct();

}

}

class Kiddo extends Papa

{

public function __construct()

{

// THIS IS WHERE I NEED TO CALL GRANDPA'S

// CONSTRUCTOR AND NOT PAPA'S

}

}

I know this is a bizarre thing to do and I'm attempting to find a means that doesn't smell bad but nonetheless, I'm curious if it's possible.

EDIT

I thought I should post the rationale for the chosen answer. The reason being; it most elegant solutionto the problem of wanting to call the "grandparent's" constructor while retaining all the values. It's certainly not the best approach nor is it OOP friendly, but that's not what the question was asking.

For anyone coming across this question at a later date - Please find another solution . I was able to find a much better approach that didn't wreak havoc on the class structure. So should you.
stackoverflow 
17 days ago by broderboy
Does PHPUnit have some inbuilt recursive array comparison function?
Some of the testing I will need to do will require comparing a known array with the result I am getting from the functions I will be running.

For comparing arrays recursively:

Does PHPUnit have an inbuilt function?

Does someone here have some code they have constructed to share?

Will this be something I will have to construct on my own?
stackoverflow 
22 days ago by broderboy
Navigation bar with multiple buttons
I have a navigation bar with a left and right button, and I need to put another button next to the right button. Does anyone know how I can go about this? Here is some code to help:

- (id)init {

self = [super initWithStyle:UITableViewStyleGrouped];

if (self) {

_pinArray = [[NSArray alloc]init];

_pinArray = [Data singleton].annotations;

UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"Map"

style:UIBarButtonItemStylePlain

target:self

action:@selector(goToMap:)];

self.navigationItem.rightBarButtonItem = right;

UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"Menu"

style:UIBarButtonItemStylePlain

target:self

action:@selector(goToMenu:)];

self.navigationItem.leftBarButtonItem = left;

self.navigationItem.title = @"My Homes";

}

return self;

}
stackoverflow 
25 days ago by broderboy
Adding observer for KVO without pointers using Swift
In Objective-C, I would normally use something like this:

static NSString *kViewTransformChanged = @"view transform changed";

// or

static const void *kViewTransformChanged = &kViewTransformChanged;

[clearContentView addObserver:self

forKeyPath:@"transform"

options:NSKeyValueObservingOptionNew

context:&kViewTransformChanged];

I have two overloaded methods to choose from to add an observer for KVO with the only difference being the context argument:

clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, context: CMutableVoidPointer)

clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, kvoContext: KVOContext)

With Swift not using pointers, I'm not sure how to dereference a pointer to use the first method.

If I create my own KVOContext constant for use with the second method, I wind up with it asking for this:

let test:KVOContext = KVOContext.fromVoidContext(context: CMutableVoidPointer)

EDIT: What is the difference between CMutableVoidPointer and KVOContext? Can someone give me an example how how to use them both and when I would use one over the other?

EDIT #2: A dev at Apple just posted this to the forums: KVOContext is going away; using a global reference as your context is the way to go right now.
stackoverflow 
27 days ago by broderboy
dealloc in Swift
I would like to perform some cleanup at the end of a view controller's life, namely to remove an NSNotificationCenter notification. Implementing dealloc results in a Swift compiler error:

Cannot override 'dealloc' which has been marked unavailable

What is the preferred way to perform some cleanup at the end of an object's life in Swift?
stackoverflow 
27 days ago by broderboy
Entitlements file do not match those specified in your provisioning profile.(0xE8008016)
The executable was signed with invalid entitlements.

The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.(0xE8008016).

I am getting this error. please help me.

I have create the provisioning profile and change the bundle id. I have enable the keychain sharing from Target->Capabilities and generate the new .entitlement file. and i have also change the bundle id in that.
stackoverflow 
27 days ago by broderboy
NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll
Recently I started to get this error:

NSPhotoLibraryUsageDescription key must be present in Info.plist to

use camera roll.

I am using React Native to build my app (I am not familiar with ios native development) and I don't know how to add this key to Info.plist

Can you post an example? Thanks

I am using npm package "react-native-camera-roll-picker": "^1.1.7"
stackoverflow 
4 weeks ago by broderboy
JSON and Core Data on the iPhone
I have a core data object graph (consisting of two entities linked by a to-many relationship).

I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to:

1) convert the core data records into a JSON string (whilst maintaining the relationship between the entities); and

2) convert the JSON string back into core data objects (again preserving the relationship between entities).

I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.
stackoverflow 
5 weeks ago by broderboy
Exception thrown in NSOrderedSet generated accessors
On my Lion app, I have this data model:

The relationship subitems inside Item is ordered .

Xcode 4.1 (build 4B110) has created for me the file Item.h , Item.m , SubItem.h and SubItem.h .

Here is the content (autogenerated) of Item.h :

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>

@class SubItem;

@interface Item : NSManagedObject {

@private

}

@property (nonatomic, retain) NSString * name;

@property (nonatomic, retain) NSOrderedSet *subitems;

@end

@interface Item (CoreDataGeneratedAccessors)

- (void)insertObject:(SubItem *)value inSubitemsAtIndex:(NSUInteger)idx;

- (void)removeObjectFromSubitemsAtIndex:(NSUInteger)idx;

- (void)insertSubitems:(NSArray *)value atIndexes:(NSIndexSet *)indexes;

- (void)removeSubitemsAtIndexes:(NSIndexSet *)indexes;

- (void)replaceObjectInSubitemsAtIndex:(NSUInteger)idx withObject:(SubItem *)value;

- (void)replaceSubitemsAtIndexes:(NSIndexSet *)indexes withSubitems:(NSArray *)values;

- (void)addSubitemsObject:(SubItem *)value;

- (void)removeSubitemsObject:(SubItem *)value;

- (void)addSubitems:(NSOrderedSet *)values;

- (void)removeSubitems:(NSOrderedSet *)values;

@end

And here is the content (autogenerated) of Item.m :

#import "Item.h"

#import "SubItem.h"

@implementation Item

@dynamic name;

@dynamic subitems;

@end

As you can see, the class Item offers a method called addSubitemsObject: . Unfortunately, when trying to use it in this way:

Item *item = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:self.managedObjectContext];

item.name = @"FirstItem";

SubItem *subItem = [NSEntityDescription insertNewObjectForEntityForName:@"SubItem" inManagedObjectContext:self.managedObjectContext];

[item addSubitemsObject:subItem];

this error appear:

2011-09-12 10:28:45.236 Test[2002:707] *** -[NSSet intersectsSet:]: set argument is not an NSSet

Can you help me?

Update:

After just 1,787 days from my bug report, today (August 1, 2016) Apple wrote me this: "Please verify this issue with the latest iOS 10 beta build and update your bug report at bugreport.apple.com with your results." . Let's hope this is the right time :)
stackoverflow 
5 weeks ago by broderboy
How to calculate UILabel height dynamically?
I want to calculate number of lines and height of UILabel dynamically from given text for same.
stackoverflow 
5 weeks ago by broderboy
How to set focus on input field?
What is the 'Angular way' to set focus on input field in AngularJS?

More specific requirements:

When a Modal is opened, set focus on a predefined <input> inside this Modal.

Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

I tried to achieve the first requirement with autofocus , but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).

Any help will be appreciated.
stackoverflow 
6 weeks ago by broderboy
How to log a method's execution time exactly in milliseconds?
Is there a way to determine how much time a method needs to execute (in milliseconds)?
stackoverflow 
6 weeks ago by broderboy
Detect if app is being built for device or simulator in Swift
In Objective-C we can know if an app is being built for device or simulator using macros:

#if TARGET_IPHONE_SIMULATOR

// Simulator

#else

// Device

#endif

These are compile time macros and not available at runtime.

How can I achieve the same in Swift? I searched stack overflow, had a look into the docs and cannot figure it out.
stackoverflow 
6 weeks ago by broderboy
What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION and this error. What does it mean, and how do I fix it?

fatal error: unexpectedly found nil while unwrapping an Optional value

This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
stackoverflow 
6 weeks ago by broderboy
How to Correctly handle Weak Self in Swift Blocks with Arguments
In my TextViewTableViewCell , I have a variable to keep track of a block and a configure method where the block is passed in and assigned.

Here is my TextViewTableViewCell class:

//

// TextViewTableViewCell.swift

//

import UIKit

class TextViewTableViewCell: UITableViewCell, UITextViewDelegate {

@IBOutlet var textView : UITextView

var onTextViewEditClosure : ((text : String) -> Void)?

func configure(#text: String?, onTextEdit : ((text : String) -> Void)) {

onTextViewEditClosure = onTextEdit

textView.delegate = self

textView.text = text

}

// #pragma mark - Text View Delegate

func textViewDidEndEditing(textView: UITextView!) {

if onTextViewEditClosure {

onTextViewEditClosure!(text: textView.text)

}

}

}

When I use the configure method in my cellForRowAtIndexPath method, how do I properly use weak self in the block that I pass in.

Here is what I have without the weak self:

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell

myCell.configure(text: body, onTextEdit: {(text: String) in

// THIS SELF NEEDS TO BE WEAK

self.body = text

})

cell = bodyCell

UPDATE : I got the following to work using [weak self] :

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell

myCell.configure(text: body, onTextEdit: {[weak self] (text: String) in

if let strongSelf = self {

strongSelf.body = text

}

})

cell = myCell

When I do [unowned self] instead of [weak self] and take out the if statement, the app crashes. Any ideas on how this should work with [unowned self] ?
stackoverflow 
6 weeks ago by broderboy
What is the swift equivalent of respondsToSelector?
I've googled but not been able to find out what the swift equivalent to respondsToSelector: is.

This is the only thing I could find (Swift alternative to respondsToSelector: ) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists or not when running on the device and if not fall back to a previous version of the api.
stackoverflow 
7 weeks ago by broderboy
Assign xib to the UIView in Swift
in objective c it can be done in init method by

-(id)init{

self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil] objectAtIndex:0];

return self;

}

but when i do this in swift

init(frame: CGRect) {

self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu", owner: 0, options: nil)[0] as? UIView

}

cannot assign to self in a method error is shown.

now my approach is to create a view, and add the view loaded from nib to it.

anyone have a better idea?
stackoverflow 
8 weeks ago by broderboy
How do you check "if not null" with Eloquent?
How do you check if a field is not null with Eloquent?

I tried Model::where('sent_at', 'IS NOT', DB::raw('null'))->... but it gives IS NOT as a binding instead of a comparison.

This is what DB::getQueryLog() says about it:

'query' => string 'select * from my_table where sent_at = ? and profile_id in (?, ?) order by created_at desc' (length=101)

'bindings' =>

array (size=3)

0 => string 'IS NOT' (length=6)

1 => int 1

2 => int 4
stackoverflow 
8 weeks ago by broderboy
OpenURL in iOS10
So apparently OpenURL has been depreciated in iOS 10. Does anyone have any documentation on why or can explain what to do next? I looked on the Apple site already and found a few things pertaining to OpenURL and this is what they say to use now:

UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?)

Does anyone have any evidence that this is the new way to use OpenURL in Swift 3.0? In addition what values are to be used in the options: and completionHandler: parameters respectively?
stackoverflow 
9 weeks ago by broderboy
How to "set a breakpoint in malloc_error_break to debug"
I'm getting lots of console outputs like this without my application crashing:

malloc: * error for object 0xc6a3970: pointer being freed was not

allocated * set a breakpoint in malloc_error_break to debug

How can I find out which object or variable is affected?

I tried setting a symbolic breakpoint like this but it never halts:
stackoverflow 
9 weeks ago by broderboy
Update Angular model after setting input value with jQuery
I have this simple scenario:

Input element which value is changed by jQuery's val() method.

I am trying to update the angular model with the value that jQuery set. I tried to write a simple directive, but it's not doing what I want.

Here's the directive:

var myApp = angular.module('myApp', []);

myApp.directive('testChange', function() {

return function(scope, element, attrs) {

element.bind('change', function() {

console.log('value changed');

})

}

})

this is the jQuery part:

$(function(){

$('button').click(function(){

$('input').val('xxx');

})

})

and html:

<div ng-app="myApp">

<div ng-controller="MyCtrl">

<input test-change ng-model="foo" />

<span></span>

</div>

</div>

<button>clickme</button>

Here is the fiddle with my try:

http://jsfiddle.net/U3pVM/743/

Can someone please point me in the right direction?
stackoverflow 
9 weeks ago by broderboy
Correct way to retrieve a single object from Realm database
I am absolutely loving Realm (0.92) in combination with Swift but have a question about reading an object from the database. My goal is to retrieve a single object with a known, unique ID (which also happens to be the primary key.

All the documentation appears to be oriented around queries for multiple objects which are then filtered. In this case I know the object ID and, since it is known to be unique, would like to retrieve it directly.

My current approach is as follows:

Realm().objects(Book).filter("id == %@", prevBook.nextID).first

This seems heavy-handed. Documentation from prior versions suggest that there is a more direct way but I can't seem to locate it in the documentation.

The problem with my current approach is that it is crashing with an exception on the following function:

public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T>

The exception is mysteriously reported as:

EXC_BAD_ACCESS (code=1, address=0xedf)

Any suggestions are very welcome.

Anticipating one line of questioning: I have confirmed that replacing prevBook.nextID with a known, good ID does not solve the problem
stackoverflow 
9 weeks ago by broderboy
Create tap-able "links" in the NSAttributedString of a UILabel?
I have been searching this for hours but I've failed. I probably don't even know what I should be looking for.

Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView opens. What puzzles me is that they often have custom links, for example if words starts with # it is also clickable and the application responds by opening another view. How can I do that? Is it possible with UILabel or do I need UITextView or something else?
stackoverflow 
9 weeks ago by broderboy
iOS 7 and button and border
I am making my app ready for iOS7. I did conversion and was working with a user. The button in the app does not look like button. Looks very flat. Is there someway to put border or make it stand like a button?
stackoverflow 
9 weeks ago by broderboy
UIFont with custom font fails with Nil
I'm trying to add a custom font to my project in Xcode 4.2, but whenever I try to use it, I get a error that the object is nil.

I have done the following:

1) Added a row to my .plist 'Fonts provided by application' value: "LCDMono2 Ultra.ttf"

2) Added the font to my Supporting Files and showed it in XCode to verify it was added.

3) Verified using Get Info that the Full Name is "LCDMono2 Ultra"

4) Created the font in my project with:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16];

and I've tried this variant:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16.f];

5) Tried to use the font name (addObject:myFont.fontName) , generating the 'nil' error.

What could be causing the error? Could it be something like the space in the name?
stackoverflow 
9 weeks ago by broderboy
dispatch_after - GCD in swift?
I've gone through the iBook from Apple, and couldn't find any definition of it :

Can someone explain the structure of dispatch_after ?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
stackoverflow 
9 weeks ago by broderboy
Swift 2: guard in for loop?
what is the correct way to use guard inside a for loop?

for (index,user) in myUsersArray.enumerate() {

guard user.id != nil else {

print("no userId")

//neither break / return will keep running the for loop

}

if user.id == myUser.id {

//do stuff

}

}
stackoverflow 
9 weeks ago by broderboy
How to print call stack in Swift?
In Objective-C, you can print the call stack by doing the following:

NSLog(@"%@", [NSThread callStackSymbols]);

How do you do this in Swift without using Foundation class?
stackoverflow 
9 weeks ago by broderboy
AngularJS: Display blob (.pdf) in an angular app
I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using <embed src> for example.

I came across couple of stack posts but some how my example doesnt seem to work.

JS:

according to this doc , I went on and tried...

$http.post('/postUrlHere',{myParams}).success(function (response) {

var file = new Blob([response], {type: 'application/pdf'});

var fileURL = URL.createObjectURL(file);

$scope.content = fileURL;

});

Now from what I understand, fileURL creates a temporary url that the blog can use as refference.

HTML:

<embed src="" width="200" height="200"></embed>

I am not sure how to handle this in angular, the ideal situation would be to (1) assign it to a scope, (2) 'prepare/rebuild' the blob to a pdf (3) pass it to the HTML using <embed> cause I want to display it within the app.

I have been researching for more than a day now but some how I cant seem to understand how this works in angular.. and lets just assume the pdf viewer libraries out there weren't an option.
stackoverflow 
9 weeks ago by broderboy
Best architecture for many asynchronous Realm writes
I'm getting crashes from Realm writes already being in a transaction, due to Realm data being updated from several asynchronous network callbacks. I understand why Realm is crashing, but I'm wondering what the right architecture is here.

So far, I can minimize the crashes by moving the individual write transactions to background threads, but is this the recommended best practice? It relies on me remembering to do this every time. Or should the network requests all be run through some central clearing house, which then moves callbacks (and therefore writes) onto background threads? Or are background threads not even the right way to do this?
stackoverflow 
9 weeks ago by broderboy
Convert String to float in Apple's Swift
I'm trying to convert numbers taken from a UITextField, which I presume, are actually strings, and convert them to float, so I can multiply them.

I have two UITextfield s which are declared as follows:

@IBOutlet var wage: UITextField

@IBOutlet var hour: UITextField

When the user presses a UIButton I want to calculate the wages the user earns, but I can't, as I need to convert them to floats first, before I can use them.

I know how to convert them to an integer by doing this:

var wageConversion:Int = 0

wageConversion = wage.text.toInt()!

However, I have no idea how to convert them to floats.
stackoverflow 
9 weeks ago by broderboy
How can I tell AngularJS to "refresh"
I have a click event that happens outside the scope of my custom directive, so instead of using the "ng-click" attribute, I am using a jQuery.click() listener and calling a function inside my scope like so:

$('html').click(function(e) {

scope.close();

);

close() is a simple function that looks like this:

scope.close = function() {

scope.isOpen = false;

}

In my view, I have an element with "ng-show" bound to isOpen like this:

<div ng-show="isOpen">My Div</div>

When debugging, I am finding that close() is being called, isOpen is being updated to false, but the AngularJS view is not updating. Is there a way I can manually tell Angular to update the view? Or is there a more "Angular" approach to solving this problem that I am not seeing?
stackoverflow 
9 weeks ago by broderboy
Xcode 8 Beta 3 Use Legacy Swift issue
I have an Objective-C project in Xcode 8 Beta 3. Since updating, whenever I try to build I receive the following error:

“Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Has anyone encountered this? Since it's an Objective-C project there's no build setting to configure Swift. I have also made sure none of the project dependencies or CocoaPods are using Swift. The only solution I have is to use Beta 2. Any ideas how I might fix this issue?

I should also mention I'm running OSX 10.12 Beta 2.
stackoverflow 
9 weeks ago by broderboy
Using a dispatch_once singleton model in Swift
I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:

class var sharedInstance:TPScopeManager {

get {

struct Static {

static var instance : TPScopeManager? = nil

}

if !Static.instance {

Static.instance = TPScopeManager()

}

return Static.instance!

}

}

Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and it should make things fairly private. Obviously though, this model isn't thread safe, so I tried to add dispatch_once to the whole thing:

class var sharedInstance:TPScopeManager {

get {

struct Static {

static var instance : TPScopeManager? = nil

static var token : dispatch_once_t = 0

}

dispatch_once(Static.token) { Static.instance = TPScopeManager() }

return Static.instance!

}

}

But I get a compiler error on the dispatch_once line:

Cannot convert the expression's type 'Void' to type '()'

I've tried several different variants of the syntax, but they all seem to have the same results:

dispatch_once(Static.token, { Static.instance = TPScopeManager() })

What is the proper usage of dispatch_once using Swift? I initially thought the problem was with the block due to the () in the error message, but the more I look at it, the more I think it may be a matter of getting the dispatch_once_t correctly defined.
stackoverflow 
9 weeks ago by broderboy
Installing Apple's Network Link Conditioner Tool
I have installed xcode 4.3.1 on my machine running Lion.

I can't find the Network Link Conditioner tool anywhere.

I have checked the utilities folder, also the xcode/contents/developer/* directories.. no such luck.

Do I need to install specific components or has this tool been removed or renamed recently?
stackoverflow 
9 weeks ago by broderboy
Is there a way to 'uniq' by column?
I have a .csv file like this:

stack2@example.com,2009-11-27 01:05:47.893000000,example.net,127.0.0.1

overflow@example.com,2009-11-27 00:58:29.793000000,example.net,255.255.255.0

overflow@example.com,2009-11-27 00:58:29.646465785,example.net,256.255.255.0

...

I have to remove duplicate e-mails (the entire line) from the file (i.e. one of the lines containing overflow@example.com in the above example). How do I use uniq on only field 1 (separated by commas)? According to man , uniq doesn't have options for columns.

I tried something with sort | uniq but it doesn't work.
stackoverflow 
9 weeks ago by broderboy
Opening Realm file in browser always requires an encryption key
I'm using Realm Browser 0.9.85 and using the examples in https://github.com/realm/realm-cocoa .

I'm a total Realm newbie so go easy on me. Every time I try to open up a Realm file from the example from GitHub, I get a request to enter in the encryption key. It seems like the default configuration in Realm is to not have it's db be encrypted, so I don't know what gives. Any help would be greatly appreciated. Thanks.
stackoverflow 
9 weeks ago by broderboy
cURL error 60: SSL certificate: unable to get local issuer certificate
I use WAMP on a local development environment and am trying to charge a credit card but get the error message:

cURL error 60: SSL certificate problem: unable to get local issuer certificate

I searched a lot on Google and lots of people are suggesting that I download this file: cacert.pem , put it somewhere and reference it in my php.ini. This is the part in my php.ini:

curl.cainfo = "C:\Windows\cacert.pem"

Yet, even after restarting my server several times and changing the path, I get the same error message.

I use WAMP from the Apache Modules and have the ssl_module enabled. And from the PGP extensions I have php_curl enabled.

Still the same error message. Why is that happening?

Now I am following this fix: How to fix PHP CURL Error 60 SSL

Which suggests that I add these lines to my cURL options:

curl_setopt($process, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');

curl_setopt($process, CURLOPT_SSL_VERIFYPEER, true);

Where do I add options to my cURL? Apparently not through the command line, since my CLI doesn't find the command "curl_setopt"

EDIT

This is the code I am running:

public function chargeStripe()

{

$stripe = new Stripe;

$stripe = Stripe::make(env('STRIPE_PUBLIC_KEY'));

$charge = $stripe->charges()->create([

'amount' => 2900,

'customer' => Input::get('stripeEmail'),

'currency' => 'EUR',

]);

dd($charge);

// echo $charge[Input::get('stripeToken')];

return Redirect::route('step1');

}
stackoverflow 
9 weeks ago by broderboy
Specify sudo password for Ansible
How do I specify a sudo password for Ansible in non-interactive way?

I'm running Ansible playbook like this:

ansible-playbook playbook.yml -i inventory.ini --user=username --ask-sudo-pass

But I want to run it like this:

ansible-playbook playbook.yml -i inventory.ini --user=username --sudo-pass=12345

Is there a way? I want to automate my project deployment as much as possible.
stackoverflow 
9 weeks ago by broderboy
#pragma mark in Swift?
In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?
stackoverflow 
9 weeks ago by broderboy
Laravel daily log created with wrong permissions
I have a script that I run using php artisan (with root user), and sometimes it causes the daily log file to be created before the apache www-data user does - which means that when a real user uses my web application, I get the folder permission error:

Failed to open stream: Permission denied

I change the permissions back to www-data everytime but I want to solve this by having the log file always created with the correct permissions.

I've considered creating a cron job that creates the file or touches it to make sure it has the right permission everyday, but I'm looking for a better solution that doesn't rely on another script.

We've also considered wrapping php artisan in another script to make sure that it is always run with the www-data credentials, but somethings that we want to do are actually root procedures that apache should not be allowed to do.

Any more suggestions?
stackoverflow 
9 weeks ago by broderboy
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am trying to run a Swift app on my iPhone 4s. It works fine on the simulator, and my friend can successfully run it on his iPhone 4s. I have iOS 8 and the official release of Xcode 6.

I have tried

Restarting Xcode, iPhone, computer

Cleaning & rebuilding

Revoking and creating new certificate/provision profile

Runpath Search Paths is $(inherited) @executable_path/Frameworks

Embedded Content Contains Swift Code is 'Yes'

Code Signing Identity is developer

Below is the error in entirety

dyld: Library not loaded: @rpath/libswiftCore.dylib

Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName

Reason: no suitable image found. Did find:

/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at

address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping

/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib
stackoverflow 
9 weeks ago by broderboy
How do I convert NSMutableArray to NSArray?
How do I convert NSMutableArray to NSArray in objective-c ?
stackoverflow 
9 weeks ago by broderboy
How to add a long pause for AVSpeechSynthesizer?
I found -- can add a small pause like the number count down:

10--9--8--7--6--5--4--3--2--1--

But I don't know how to add a long pause, for like 1 sec?

Any idea?
stackoverflow 
9 weeks ago by broderboy
Precision String Format Specifier In Swift
Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b);

I checked the docs and the eBook but haven't been able to figure it out. Thanks!
stackoverflow 
9 weeks ago by broderboy
Getting error "No such module" using Xcode, but the framework is there
I'm currently coding in Swift, and I've got an error:

No such module Social

But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries".

The frameworks is in Objective-C, so I wrote a Bridge Header for it.

Please, how can I make Xcode recognize the framework?
stackoverflow 
9 weeks ago by broderboy
How to get First and Last Day of Previous Month with Carbon - Laravel
I need First and Last Day of Previous Month using Carbon Library, what I have tried is as follows:

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();

$lastDayofPreviousMonth = Carbon::now()->endOfMonth()->subMonth()->toDateString();

Result I'm getting is for $firstDayofPreviousMonth = '2016-04-01'(as current month is 5th(May)) and for $lastDayofPreviousMonth = '2016-05-01'.

I'm getting correct result for $firstDayofPreviousMonth, but it's giving me 30 days previous result, and giving me wrong result for $lastDayofPreviousMonth.

Can anyone help me out with this? Thank you
stackoverflow 
9 weeks ago by broderboy
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
How do you use Auto Layout within UITableViewCell s in a table view to let each cell's content and subviews determine the row height, while maintaining smooth scrolling performance?
stackoverflow 
9 weeks ago by broderboy
How do I check if a string contains a specific word in PHP?
Consider:

$a = 'How are you?';

if ($a contains 'are')

echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are') ?
stackoverflow 
9 weeks ago by broderboy
XCODE 7.1 Swift 2 Unknown class in Interface Builder file
I've created new Cocoa Touch File. Named it SwipingViewController.

Then try to add Custom Class to ViewController.

And when I run the app i receive an error

2015-10-09 10:53:25.054 ParseStarterProject[5369:389307] Unknown class SwipingViewController in Interface Builder file.

I've tried to find in Google by myself.

I've found some solutions

Xcode 6 Strange Bug: Unknown class in Interface Builder file

But they all did not help to fix the problem.

Any idea how to fix it?

here is my projects files
stackoverflow 
9 weeks ago by broderboy
Specify sudo password for Ansible
How do I specify a sudo password for Ansible in non-interactive way?

I'm running Ansible playbook like this:

ansible-playbook playbook.yml -i inventory.ini --user=username --ask-sudo-pass

But I want to run it like this:

ansible-playbook playbook.yml -i inventory.ini --user=username --sudo-pass=12345

Is there a way? I want to automate my project deployment as much as possible.
stackoverflow 
10 weeks ago by broderboy
How to add a long pause for AVSpeechSynthesizer?
I found -- can add a small pause like the number count down:

10--9--8--7--6--5--4--3--2--1--

But I don't know how to add a long pause, for like 1 sec?

Any idea?
stackoverflow 
11 weeks ago by broderboy
Opening Realm file in browser always requires an encryption key
I'm using Realm Browser 0.9.85 and using the examples in https://github.com/realm/realm-cocoa .

I'm a total Realm newbie so go easy on me. Every time I try to open up a Realm file from the example from GitHub, I get a request to enter in the encryption key. It seems like the default configuration in Realm is to not have it's db be encrypted, so I don't know what gives. Any help would be greatly appreciated. Thanks.
stackoverflow 
april 2017 by broderboy
Is there a way to 'uniq' by column?
I have a .csv file like this:

stack2@example.com,2009-11-27 01:05:47.893000000,example.net,127.0.0.1

overflow@example.com,2009-11-27 00:58:29.793000000,example.net,255.255.255.0

overflow@example.com,2009-11-27 00:58:29.646465785,example.net,256.255.255.0

...

I have to remove duplicate e-mails (the entire line) from the file (i.e. one of the lines containing overflow@example.com in the above example). How do I use uniq on only field 1 (separated by commas)? According to man , uniq doesn't have options for columns.

I tried something with sort | uniq but it doesn't work.
stackoverflow 
april 2017 by broderboy
Best architecture for many asynchronous Realm writes
I'm getting crashes from Realm writes already being in a transaction, due to Realm data being updated from several asynchronous network callbacks. I understand why Realm is crashing, but I'm wondering what the right architecture is here.

So far, I can minimize the crashes by moving the individual write transactions to background threads, but is this the recommended best practice? It relies on me remembering to do this every time. Or should the network requests all be run through some central clearing house, which then moves callbacks (and therefore writes) onto background threads? Or are background threads not even the right way to do this?
stackoverflow 
april 2017 by broderboy
How to get First and Last Day of Previous Month with Carbon - Laravel
I need First and Last Day of Previous Month using Carbon Library, what I have tried is as follows:

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();

$lastDayofPreviousMonth = Carbon::now()->endOfMonth()->subMonth()->toDateString();

Result I'm getting is for $firstDayofPreviousMonth = '2016-04-01'(as current month is 5th(May)) and for $lastDayofPreviousMonth = '2016-05-01'.

I'm getting correct result for $firstDayofPreviousMonth, but it's giving me 30 days previous result, and giving me wrong result for $lastDayofPreviousMonth.

Can anyone help me out with this? Thank you
stackoverflow 
april 2017 by broderboy
Swift 2: guard in for loop?
what is the correct way to use guard inside a for loop?

for (index,user) in myUsersArray.enumerate() {

guard user.id != nil else {

print("no userId")

//neither break / return will keep running the for loop

}

if user.id == myUser.id {

//do stuff

}

}
stackoverflow 
april 2017 by broderboy
UIFont with custom font fails with Nil
I'm trying to add a custom font to my project in Xcode 4.2, but whenever I try to use it, I get a error that the object is nil.

I have done the following:

1) Added a row to my .plist 'Fonts provided by application' value: "LCDMono2 Ultra.ttf"

2) Added the font to my Supporting Files and showed it in XCode to verify it was added.

3) Verified using Get Info that the Full Name is "LCDMono2 Ultra"

4) Created the font in my project with:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16];

and I've tried this variant:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16.f];

5) Tried to use the font name (addObject:myFont.fontName) , generating the 'nil' error.

What could be causing the error? Could it be something like the space in the name?
stackoverflow 
april 2017 by broderboy
iOS 7 and button and border
I am making my app ready for iOS7. I did conversion and was working with a user. The button in the app does not look like button. Looks very flat. Is there someway to put border or make it stand like a button?
stackoverflow 
march 2017 by broderboy
Correct way to retrieve a single object from Realm database
I am absolutely loving Realm (0.92) in combination with Swift but have a question about reading an object from the database. My goal is to retrieve a single object with a known, unique ID (which also happens to be the primary key.

All the documentation appears to be oriented around queries for multiple objects which are then filtered. In this case I know the object ID and, since it is known to be unique, would like to retrieve it directly.

My current approach is as follows:

Realm().objects(Book).filter("id == %@", prevBook.nextID).first

This seems heavy-handed. Documentation from prior versions suggest that there is a more direct way but I can't seem to locate it in the documentation.

The problem with my current approach is that it is crashing with an exception on the following function:

public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T>

The exception is mysteriously reported as:

EXC_BAD_ACCESS (code=1, address=0xedf)

Any suggestions are very welcome.

Anticipating one line of questioning: I have confirmed that replacing prevBook.nextID with a known, good ID does not solve the problem
stackoverflow 
march 2017 by broderboy
Create tap-able "links" in the NSAttributedString of a UILabel?
I have been searching this for hours but I've failed. I probably don't even know what I should be looking for.

Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView opens. What puzzles me is that they often have custom links, for example if words starts with # it is also clickable and the application responds by opening another view. How can I do that? Is it possible with UILabel or do I need UITextView or something else?
stackoverflow 
march 2017 by broderboy
NSNotification with delay
How to post NSNotification with delay.

One solution that is in my mind :- post notification in performSelectorAfterDelay method. Is there any better solution for this.

Is NSNotificationQueue can help me to achieve this ?
stackoverflow 
march 2017 by broderboy
Run R script from command line
I have a file, called a.r , it has a chmod of 755,

sayHello <- function(){

print('hello')

}

sayHello()

How can I run this via command-line?
stackoverflow 
march 2017 by broderboy
OpenURL in iOS10
So apparently OpenURL has been depreciated in iOS 10. Does anyone have any doccumentation on why or can explain what to do next? I looked on the Apple site already and found a few things pertaining to OpenURL and this is what they say to use now:

UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?)

Does anyone have any evidence that this is the new way to use OpenURL in Swift 3.0? In addition what values are to be used in the options: and completionHandler: parameters respectively?
stackoverflow 
march 2017 by broderboy
How to present UIAlertController when not in a view controller?
Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method called on another class. A bad thing happens there and I want to display an alert right there before control returns to the view controller.

+ (void)myUtilityMethod {

// do stuff

// something bad happened, display an alert.

}

This was possible with UIAlertView (but perhaps not quite proper).

In this case, how do you present a UIAlertController , right there in myUtilityMethod ?
stackoverflow 
march 2017 by broderboy
Entitlements file do not match those specified in your provisioning profile.(0xE8008016)
The executable was signed with invalid entitlements.

The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.(0xE8008016).

I am getting this error. please help me.

I have create the provisioning profile and change the bundle id. I have enable the keychain sharing from Target->Capabilities and generate the new .entitlement file. and i have also change the bundle id in that.
stackoverflow 
march 2017 by broderboy
UIActivityViewController customize text based on selected activity
I want to customize text for the same information but when I am sharing it on Facebook I don't want to use the twitter hash tags or @username scheme...

How can I diversify text for sharing based on which sharing service would be used?

Ofcourse I'm using UIActivityViewController:

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[shareText, shareURL] applicationActivities:nil];
stackoverflow 
march 2017 by broderboy
How can i run Laravel Queue only once?
I used laravel 5.1 Queue for my background function with async.

But i want to run that function for only 1 time. If that function fail, i want to do other process.

How can i detect my job is failed or not?

Am i doing right or wrong ? What should i change?

ps: I'm beginner. I used like this in my controller.

$job = new myjob($var1, $var2);

$this->dispatch($job);

$job->release();

if ($job->attempts() >= 1)

{

$job->delete();

//will do other process

}
stackoverflow 
february 2017 by broderboy
How do I convert NSMutableArray to NSArray?
How do I convert NSMutableArray to NSArray in objective-c ?
stackoverflow 
february 2017 by broderboy
« earlier      
per page:    204080120160

Copy this bookmark:



description:


tags: