I designed my viewControllers in storyboard like from A to B,C and D by segue of Show. In A I called self.performSegue(withIdentifier: "xxxx", sender: nil) to show the target viewController.

Now my question is how to get to know in A that which viewController just disappeared? any delegate?

Thanks.

I am trying to send the user to another viewcontroller only if they haven't verified their phone number. Unfortunately, when that is the case, nothing happens, and the user is saved as logged in. However, when a user did in fact verify their phone number and the boolean phoneVerified is true, the user is redirected to the protected page.

PFUser.logInWithUsernameInBackground(userEmail!, password: userPassword!) { (user:PFUser?, error:NSError?) -> Void in

        var userMessage = "You are logged in!"

        if(user != nil)
        {
            // Remember the log in state
            let userName:String? = user?.username

            NSUserDefaults.standardUserDefaults().setObject(userName, forKey: "username")
            NSUserDefaults.standardUserDefaults().synchronize()
        }

        if(user == nil)
        {
            userMessage = error!.localizedDescription

            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)

            let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)

            myAlert.addAction(okAction)

            self.presentViewController(myAlert, animated: true, completion: nil)
        }
        let phoneVerified = PFUser.currentUser()?.objectForKey("phoneVerified")?.boolValue

        if phoneVerified! == false{
            //self.displayAlert("Error", message: "Please verify your phone number.")
            let verifyVC = self.storyboard?.instantiateViewControllerWithIdentifier("verifyCode")
            self.navigationController?.pushViewController(verifyVC!, animated: true)
        }else{
            //let mainVC = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController")
            //self.navigationController?.pushViewController(mainVC!, animated: true)

            //Navigate to protected page

            let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            appDelegate.buildUserInterface()
        }

 }
 }
 }

I have JSON looking like this:

{"posts":
    [
    {
    "id":"1","title":"title 1"
    },
    {
    "id":"2","title":"title 2"
    },
    {
    "id":"3","title":"title 3"
    },
    {
    "id":"4","title":"title 4"
    },
    {
    "id":"5","title":"title 5"
    }
    ],
    "text":"Some text",
    "result":1
}

How can I parse that JSON with Swift 3?

I have this:

let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
            return
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
            // Parse JSON
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: .utf8)
            print("raw response: \(responseString)")
        }
    }
    task.resume()
}

Trying to find simple way to record screen video of all user sessions and upload them to some server. Can anyone suggest how to implement this feature?

Hy, I try to add labels programmatically to a GridLayout in NativeScript. The code works well on Android emulator and physical device, but crashes on the iPhone Simulator

The error:
JS ERROR TypeError: undefined is not an object (evaluating 'columnGroup.getIsAuto') Oct 9 04:04:23 IfYourAgeIsOnTheClocks-MacBook-Air com.apple.CoreSimulator.SimDevice.6E21AA70-C0DE-4BC1-8656-17BF56EAB3E0.launchd_sim[18085] (UIKitApplication:org.nativescript.LocisApp[0xf579][20614]): Service exited due to Segmentation fault: 11

My code:

var labels = [];
for(var row = 0; row < rowsCount; row++){
    for(var i = 0; i < cols; i++){
        labels[i*row + i] = new labelModule.Label(); 
        labels[i*row + i].backgroundColor = "green";
        labels[i*row + i].rowSpan = 1;
        labels[i * row + i].colSpan = 1;
        labels[i*row + i].col = i;
        labels[i*row + i].scaleX = scaleFactor;
        labels[i*row + i].width = cellSmall;
        labels[i*row + i].height = cellSmall;
        gridLayout.addChild(labels[i*row + i]);  // <-- CRASH HERE
        layout.GridLayout.setColumn(labels[i*row + i], i * scaleFactor);
        layout.GridLayout.setRow(labels[i*row + i],row);
    }
}

When I call the addChild() method once it also works on iOS.
But when I call it multiple times the app crashes, but still runs on Android.
Hope someone can help.

After upgrading to XCode 8, I noticed some of my views (layed out in Interface Builder) now have incorrect colors.

Specifically, I have two custom views on my login page which normally have a white background. After upgrading to XCode 8, their background color is clear! Looks terrible.

I've done some investigation and found this from Apple:

Color values in Interface Builder documents correctly use color space during rendering and compilation. Earlier versions of Xcode mishandled color spaces saved in iOS and tvOS documents. Xcode 8 converts existing colors in a way that preserves their perceptual appearance on device, and updates either the color space or component values in the source document as appropriate. (7645087)

And sure enough, when I look at the diff for the commit that broke things:

This:

<rect key="frame" x="8" y="8" width="88" height="48"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>

Was replaced by this:

<color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/>

What can I do to fix this? Here are some things I have tried:

1) Within interface builder, select the view, and open the color pallet for background color. Click the gear icon, and select SRGB. Tried other profiles as well, nothing seems to work.

2) Tried reverting the XIB file. Can't do this since it was part of XCode 8 upgrade. This change to the color profiles happens when you call "Update Frames" for the view controller, after selecting the iPhone size you want.

Anyone have any other suggestions would be so helpful!

Let's say to all geeks out there with iOS knowledge, what is the best way to have drawing application developed. My idea is to develop drawing application that will have as starting point UIViewController and Main.Storyboard. Let's say I developed functionality to draw with different colors in one scene using single UIViewController and Main.Storyboard. If we want to have more than one scene in our app, in my case 32 more scenes, transitioning in order from first scene to the last 32nd scene, what is the best option to implementment this.

  1. Single UIViewController, single storyboard for all 32 scenes
  2. Single UIViewController, single storyboard for each scene, equal to 32 UIViewControllers and storyboards.

Appreciate your support!!!

This segment of code worked perfectly in Swift 2

override func prepare(for segue: UIStoryboardSegue?, sender: Any?) {
    if (segue!.identifier == "FeedDetailSeg") {
        let viewController:ItemDetail = segue!.destination as! ItemDetail

        viewController.DetailItem = collectionItems![self.selectedRow]

        if self.cognitoID == collectionItems![self.selectedRow].seller {
            viewController.owned = true
        }
        else {
            viewController.owned = false
        }

        //remove item from untapped
        //appDelegate.untapped.removeAtIndex(self.selectedRow)

        //collect view info
        self.dataStash(collectionItems![self.selectedRow].ID, itemCondition: 2).continueWithBlock({
            (task: BFTask!) -> BFTask! in

            if (task.error != nil) {
                print(task.error!.description)
            } else {
                print("DynamoDB save succeeded")
            }

            return nil;
        })

    }
}

Now in Swift 3 I get an error on line

//collect view info    
self.dataStash(collectionItems![self.selectedRow].ID, itemCondition: 2).continueWithBlock({

that says: Cannot convert value of type '(BFTask<_>!) -> BFTask!' to expected argument type '(BFTask?) -> Any?!'

This is using AWS to save an item to DynamoDB.

After the latest windows 10 update, my Nokia Lumia 635 RM-975 does no longer appear when connected to the Pc. When i try to update the drivers automatically, it says :

A service installation section in this INF is invalid.

When i try to browse my computer for software and try to pick on the list of devices, after installation, i can not access the phone content as i used to previously.

How to make Nokia Lumia 635 RM-975 display on pc after windows 10 new update ?

We build a desktop app for both Windows and Mac. Mostly C++ with some Obj-C on Mac. The platform code is cross platform, but the UI code are separate code bases on both platforms with very little possibility of cross-compiling. We are starting to approach cross-platform development from many different angles. (e.g. licensing Qt). But it is important to recognize that we can't just throw out all our existing code and features and re-write everything. A lot of the new features that we want to be cross-platform will still need to interface with the old code on both platforms. Read: write once, integrate twice.

As I look at the types of integrations between "view" and "model", there are two common patterns that we have to do on both Windows and Mac that I'm looking at solving in a cross-platform way.

  1. Something initiated by the user on the main UI thread needs to operate on a background thread (e.g. web request, long series of file i/o, etc...). And then when that operation is completed, the UI thread needs to be notified such that it can handle the result of that operation.

  2. A callback of data originates from the platform code on one of its threads. That event needs to be marshalled to the UI thread for it to handle it.

We have helper libraries in our Windows code base that help manage worker threads and signal event queues with PostMessage and hidden HWNDs. On Mac, Objective-C provides performSelectorOnMainThread. Both have their pros and cons, but neither are universal or complete.

I had looked at using std::async. But the future object returned provides no signaling of when the task is complete for the UI thread to obtain the result on without blocking. At best, it's a building block for a cross-platform library, but not a solution, especially for getting events queued onto the UI thread.

I'd like to have something closer to Android's AsyncTask class to solve #1. Whereby the execution of the task is implemented in on method and happens on a background thread, but the completion event method is invoked back on the UI thread - and the developer doesn't have to think about the marshalling and queuing between threads. Similarly, Android's Handler class solves #2 above. I've started prototyping these classes into C++ and think I might be on the right track, but I want to make sure I'm not re-inventing the wheel.

Before I go deeper into my implementation, is there a well known pattern or open source C++ library that might already be a solution?

To simplify the use case, let's say I have a mobile app available for Android and iOS, similar to Instagram, where users can upload photos that can be commented, liked or disliked by other users. When a user comments, likes or dislikes a photo you uploaded, you would get a real time notification on your phone telling you about the type of action, the name of the user and the photo it is about.
Users can follow each other, followers would also get a notification when a user they follow uploads a new photo.

I will use AWS SNS, so I need to decide about how to organize and use the topics. By default, SNS offers 10 million subscriptions per topic, and 100,000 topics per account. My app has less than 100,000 users and is not expected to reach 1 million users anytime soon. I guess the design would be very similar with Microsoft Azure ou Google Cloud (but with different constraints).

I see 4 options so far:

  1. I create only 1 topic, I publish all the notifications in it with details about what kind of action happened: all users subscribe to that topic and are notified about everything that happens. The mobile app has to filter the relevant notifications (according to some locally stored data like the IDs of the users the user follows, the IDs of his photos, etc.). I am new to mobile development, maybe I am wrong but I feel like it's a bad design to process all the notifications and query the local storage all the time.
  2. I create 1 topic per action: photo posted, photo commented, photo liked, photo disliked, and users select the topics they want to subscribe to. Still, the app needs to filter all the notifications for each selected topic.
  3. I create 1 topic per user where his actions will be published, and "followers" would be subscribed to appropriate topics (the users they follow). Doable now but the AWS limit being 100,000 I suppose there is a reason and it's maybe not the way big companies do. Also this only works between users who follow each other, ideally I want users to also be notified when random users comment/like/dislike their photos.
  4. Similar to point 3, I create 1 topic per user but this time I publish what other users do with his stuff (comment, etc.) in that topic (+ his followers posting new photos for instance), so he would be the only subscriber to that topic and would get only relevant notifications. There is still the 100,000 topics limit problem.

What do you guys think or how have you designed/implemented such system?

Basically this is what I have so far:

SELECT * FROM [HumanResources].[Employee] AS E JOIN [HumanResources].[EmployeeDepartmentHistory] AS EDH ON E.BusinessEntityID = EDH.BusinessEntityID JOIN [HumanResources].[EmployeePayHistory] AS EPH ON E.BusinessEntityID = EPH.BusinessEntityID WHERE E.MARITALSTATUS = 'S'
EPH.Rate BETWEEN '100' AND '120'

I would like to be able to query the table so that I can show those with Marital Status of 'S' and also those with a pay rate between 100 - 120, but when I add the second query it errors out with "Incorrect Syntax near EPH". The only reason why I am confused is because if I remove the second query and run them individually, they both work fine!

Any help here would be greatly appreciated!

I am receiving an authentication error "CONNECTIVITY_ISSUE" when i try to login using android sdk LoginManager in sandbox mode.

SessionConfiguration config = new SessionConfiguration.Builder()
            .setClientId(Constants.UBER_CLIENTID) 
            .setEnvironment(SessionConfiguration.Environment.SANDBOX) 
            .setScopes(Arrays.asList(Scope.PROFILE, Scope.RIDE_WIDGETS,Scope.REQUEST)) 
            .build();
UberSdk.initialize(config);
    accessTokenManager = new AccessTokenManager(this);
    LoginCallback loginCallback = new LoginCallback() {
        @Override
        public void onLoginCancel() {

        }

        @Override
        public void onLoginError(@NonNull AuthenticationError error) {

        }

        @Override
        public void onLoginSuccess(@NonNull AccessToken accessToken) {

        }

        @Override
        public void onAuthorizationCodeReceived(@NonNull String authorizationCode) {
        authorizationCode=authorizationCode;
        }
    };
    loginManager = new LoginManager(accessTokenManager, loginCallback);
    if (accessTokenManager.getAccessToken() == null) {
        loginManager.setRedirectForAuthorizationCode(true);
        loginManager.login(this);
    }

I have followed uber developer documentation and I am not able to solve this error. Can anyone help me on this?

I am getting a "cannot use instance member 'appearance' within property initializer; property initializers run before 'self' is available". Please do not suggest to remove appearance from the code, that will not work. I also added a self.appearence.kcirclebackround and got and error as well.

Here is where the kCircleHeightBackground cgfloat is set `open class SCLAlertView: UIViewController {

public struct SCLAppearance {
    let kDefaultShadowOpacity: CGFloat
    let kCircleHeightBackground: CGFloat 
    let kCircleTopPosition: CGFloat
    let kCircleBackgroundTopPosition: CGFloat
    let kCircleHeight: CGFloat
    let kCircleIconHeight: CGFloat
    let kTitleTop:CGFloat
    let kTitleHeight:CGFloat
    let kWindowWidth: CGFloat
    var kWindowHeight: CGFloat
    var kTextHeight: CGFloat
    let kTextFieldHeight: CGFloat
    let kTextViewdHeight: CGFloat
    let kButtonHeight: CGFloat
    let contentViewColor: UIColor
    let contentViewBorderColor: UIColor
    let titleColor: UIColor

`

and then i'm getting an error at

var appearance: SCLAppearance!

// UI Colour
var viewColor = UIColor()

// UI Options
open var iconTintColor: UIColor?
open var customSubview : UIView?



// Members declaration
var baseView = UIView()
var labelTitle = UILabel()
var viewText = UITextView()
var contentView = UIView()
// "I get an error here at appearance.kCircleHeightBackground"__________var circleBG = UIView(frame:CGRect(x:0, y:0, width: appearance.kCircleHeightBackground, height: appearance.kCircleHeightBackground))
var circleView = UIView()
var circleIconView : UIView?
var duration: TimeInterval!
var durationStatusTimer: Timer!
var durationTimer: Timer!
var dismissBlock : DismissBlock?
fileprivate var inputs = [UITextField]()
fileprivate var input = [UITextView]()
internal var buttons = [SCLButton]()
fileprivate var selfReference: SCLAlertView?

public init(appearance: SCLAppearance) {
    self.appearance = appearance
    super.init(nibName:nil, bundle:nil)
    setup()
}

Image of error i get

I'm writing an update to a game app (Swift, iOS), and currently have written a module to download new level data when new levels are available. My aim is to save the need to submit a new build to the App Store for the sake of the few kb of data that each level needs. However, my game relies on a separate leaderboard for each level, and it seems that you can only add new leaderboards along with an app update. So that kinda negates the benefit of providing levels on the fly...

One solution that comes to mind is to add lots of extra leaderboards with the next app build, then use those IDs with future levels. The problem with that is it ends up cluttering the leaderboard list with empty ones before they're available, so it's far from ideal.

Does anyone have any knowledge on this? Is there any workaround I can use to add leaderboards without needing to add a new app build each time, or is an external leaderboard (my own or 3rd party) the only way to overcome this? Any advice is appreciated, thank you all!

I want my app to Update the pre-existing text present in a TextView by one letter. The method that I came to know from web is by Overriding onKeyUp method and the way I am doing this is as follows-

public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(!((keyCode <= 90 && keyCode >= 65) || (keyCode >= 97 && keyCode <= 122))){
            TextView text = (TextView) findViewById(ghostText);
            String str = (String) text.getText();
            text.setText(str + Character.valueOf((char) event.getKeyCode()));
            return true;
        }
        return true;
    }

But the problem is when I am using this method, on pressing a key on keyboard instead of a letter I am getting special symbols. I don't know what's wrong with this piece of code. This maybe totally wrong. And if there is any simpler way to achieve what I want to achieve then please tell me. Thank you in advance.

I'm having trouble in figuring out why the output for theses two lines is different ..

public static void main(String[] args) {
   System.out.println("6.0+1="+6.0+1);
   System.out.println("6.0+1="+(6.0+1));
}

The output
6.0+1=6.01
6.0+1=7.0

I am trying to implement VIPER architecture on iOS in Swift.

The problem I have is how to set up the object graph. Please ignore the Router and the Entity as it is not relevant to my problem. That leaves us with the Interactor, Presenter, and the View.

Interactor - business logic, has state, does work, accepts commands. Presenter - transforms abstract data to presentation format, or ask interactor to do work. View - presents presentable info, sends actions to Presenter to translate to business logic requests.

The communication between these three components is bidirectional and the Interactor and View are not aware of each other:
Interactor <-> Presenter <-> View.

All are defined as protocols. (interfaces in other languages...) Each concrete component conforms to its corresponding a protocol (i.e. implements an interface)...and those components only see each other as interfaces.

Here comes the problem:

For the presenter to work correctly, it simply has to have a reference to an Interactor instance where the business logic and state sits. Same goes for the View, it cannot work correctly without a reference to a properly initialized Presenter instance.

I have two options:

OPTION A: 1) The presenter will have a required initializer which will take in an interactor instance. 2) The view will have a required initializer which will take in a presenter instance. 3) I will enforce this in protocols.

OPTION B: 1) There will be a public .interactor variable on the presenter, and this will be settable on a presenter instance. 2) There will be a public .presenter variable on the view, and this will be settable in a view instance.

Option A with initializers gives me a mechanism that ensures things are set up in the right order and they are initialized to a valid state. However, this leads to having to replicate the same mechanism in unit testing where mocks, stub implementations of those protocols actually have to have those initializers and initialize with each other..that means now I have a chain of mocks depending on each other which smells.

Option B prevents the problem with a chain of mocks, but then I will potentially have objects in invalid state, or I have to actually unit-test the router methods that sets up the dependency chain. But then I will be able to only deal with one layer of mocks for each unit test case. At least in theory I think, I haven't try that yet.

Which approach is correct? Or is there some other approach? Can you advise please?

I have seen a lot of algorithm problems with matrices and a lot of them can be solved with DP but for this one, I still have no idea how to solve it. Here is a description of the problem:

Say you are provided with a nxn matrix of characters. There are only three different characters in the matrix:

1 - which means there is one point in the cell. You can pass this cell and get one point.

0 - which means it is a path. You can pass the cell but can’t get any point.

-1 - which means there is a block in the cell and you can’t pass.

You have to travel from the top left corner to the bottom right corner (I call it forward trip) and then back to the top left corner (backward trip). Your mission is to get the max points during your trip. You can go right and down during the forward trip and left and up when backwards. When you collect a point during the forward trip, that cell becomes a path and you can’t get another point when going back.

If the problem only asks the max points collected from the forward trip or backward trip, it can be easily solved with DP. However, since we have to travel forward and then backward, there is no guarantee that the max points we collect in the backward trip can leads to the overall max points after the matrix has been modified by the forward trip when we try to obtain the max points. Namely, we cannot prove the validity of the following equation:

Max points in the forward trip + max points in the backward trip after the matrix has been modified by the forward trip for max points = Overall max points from the forward and backward trip

Anybody has any idea how to solve this problem?

One example here

Say the matrix is:

0 1 -1

1 0 -1

1 1 1

The max points can be obtained is 5. In the forward trip, you go (0,0)->(0,1)->(1,1)->(2,1)->(2,2). And in the backward trip, (2,2)->(2,1)->(2,0)->(1,0)->(0,)

To my knowledge multi-threading is just an illusion since CPU schedules time for each of the process. So when scrapping at a particular time, only one content from the website will be scrapped and it will also lead to so much of difficulty since all of the process are urging for the same resource so there might be a problem with "resource allocation" requiring mutex to be implemented.

The ultimate role of mutex is to prevent another thread to access the same resource. So if mutex is implemented, even the perfect implementation of threads would result is in scrapping one info from the website at a particular time.

So how does multi-threading help in scrapping website?

Consider the bot has no GUI(for preventing comments that threading will help in managing GUI and time taking process).

TDLR? Will multithreading speed up web-scrapping process?

Suppose you are selling a web app. There is no data or operation that involves more than 1 customer. Each customer is totally separate.

How would you prefer to make the deployments?

1) Deploy one instance for each customer, meaning you are running and managing many small apps on different servers/virtual machines/on the cloud etc.

2) Build a multitenant app that manages different customers itself, manage 1 big app, scale it on the cloud. You are basically selling a username/pass pair.

OR a 3rd approach I am not aware of.

Is the choice clear (like everyone is doing this second way), or are there many considerations, pro-cons between those models?