mardi 4 août 2015

How to import swift file into objective-c file in a swift project

The situation is a little complicated. I have a swift project, and I have import some objective-c file into this project. Right now I want to use some swift class in these objective-c file. How to do that?



via Chebli Mohamed

How can I export the photos from my iOS8 device to Windows 10? [on hold]

My iPhone is not showing up under "This PC" like the other drives on my computer. To import pictures, I used to plug in the cable, the iPhone would pop up like any other drive, right-click, then choose "Import pictures and videos". This is great because it gives you the option to erase the images once they're safely on your computer, freeing up your iPhone or iPad.



via Chebli Mohamed

What's a good machine for iPhone development 2015/2016?

so I'm PC user Windows.
but I used Mac before, now i'm planning on learning C, object-c so I can create my apps you know have some fun.
There is a lot of questions in here but i find that Old.

So what I want to know is what machines are good/The Beast for now in 2015/2016 so i can work with Xcode without problems.
My budget is 4 thousand dollars.



via Chebli Mohamed

How to make a SKPhysicsBody not collide with anyone

I have two types of object: A and B

I want to B to collide with B but I don't want B to collide with A

How I do that?



via Chebli Mohamed

How to remove gray color effect when touch move using objective c

I converted a image fully gray when load. But i want to remove gray color from when touch move and view original image color .

I want to know how i convert a gray color effect to original image and original to gray when user finger move over the image



via Chebli Mohamed

How to implement a UIScrollView using Vertical constraintsWithVisualFormat (SWIFT)

I need to implement UIScrollView in my app using constraintsWithVisualFormat possible that someone would guide me with some code . Thank You!


import UIKit

class ViewController: UIViewController, UIScrollViewDelegate{

var scrollView: UIScrollView!
var containerView = UIView()


//FUNCION PARA PERMITIR COLORES HEXÁDECIMALES
func uicolorFromHex(rgbValue:UInt32)->UIColor{
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0;
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0;
    let blue = CGFloat(rgbValue & 0xFF)/256.0;

    return UIColor(red:red, green:green, blue:blue, alpha:1.0);
}
//***


override func viewDidLoad() {
    super.viewDidLoad()

    self.scrollView = UIScrollView()
    self.scrollView.delegate = self

    containerView = UIView()

    containerView.backgroundColor = uicolorFromHex(0x0099FF);
    containerView.setTranslatesAutoresizingMaskIntoConstraints(false);

    scrollView.addSubview(containerView)
    view.addSubview(scrollView)


    //*** DICCIONARIO
    let viewsDictionary = ["scrollView":scrollView
        ,"containerView":containerView]

    let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollView]-0-|",
                                                                                    options: NSLayoutFormatOptions(0),
                                                                                    metrics: nil,
                                                                                    views: viewsDictionary)

    let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollView]-0-|",
                                                                                    options: NSLayoutFormatOptions(0),
                                                                                    metrics: nil,
                                                                                    views: viewsDictionary)

    view.addConstraints(view_constraint_H as [AnyObject])
    view.addConstraints(view_constraint_V as [AnyObject])


    let view_constraintContainer_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[containerView]-0-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDictionary)

    let view_constraintContainer_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[containerView]-0-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDictionary)

    scrollView.addConstraints(view_constraintContainer_H as [AnyObject])
    scrollView.addConstraints(view_constraintContainer_V as [AnyObject])






}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

error:

2015-08-04 22:26:05.693 dsds[2017:56799] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. 2015-08-04 22:26:05.695 dsds[2017:56799] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. Message from debugger: Terminated due to signal 15

help me!!!! thanks!!!



via Chebli Mohamed

How to change the duration of a movement with count- Swift SpriteKit?

In my game, there's a class for a "wall" that's moving to the left. I want to change the speed of it based on count i that I added to touchesBegan method:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent {
    count++
}

func startMoving() {

    let moveLeft = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 1 )

    let move = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 0.5)

    if(count <= 10)
    {
        runAction(SKAction.repeatActionForever(moveLeft))
    }
    else
    {
    runAction(SKAction.repeatActionForever(move))
    }
}

but it's not working. Can you help?



via Chebli Mohamed

Did Call feature change in iOS 8.4?

I have an app that lets users dial a call. Basically it has number input that user enters and then it dials the number using this code.

        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) 
        {
            //its iphone
            NSString *tmpStr1 = [NSString stringWithFormat:@"tel://%@", labelStr.text];
            NSLog(@"tmpStr1: %@ ...", tmpStr1);
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tmpStr1]];
        }
tmpStr1: tel://8003310500 ...

Recently I submitted an app update to Apple and I keep getting rejections from the Apple reviewer saying that nothing happens when the call button is pushed.

I tested this on my actual device, iPhone 6 running iOS 8 and it works just fine. My question is, did Apple change something in iOS 8.4 to disable this feature? Is there some sort of user permission needed before doing that? Unfortunately I cannot upgrade my device to iOS 8.4 at this time. (there are some personal reasons)



via Chebli Mohamed

Scaling a UIView with UIPanGestureRecognizer

I have a rectangle UIView with a UIWebView as a subview, and I want to change the scale when pan is detected on the upper left corner. I already have another small UIView in the upper left corner so the scaling should start from there. I know this can be done by UIPinchGestureRecognizer but having a UIWebView there will be an obstacle for that. I've added a UIPanGestureRecognizer to the main UIView so it's movable. but I want to check if the pan is from the small UIView in the upper left corner and from there change the scale transform of the UIView. So how to do that? Also is it possible to change the scale horizontally/vertically depending on the direction I'm panning the small UIView to? Also is it possible to set a minimum/maximum scale so the UIView won't scale after that?

Thanks



via Chebli Mohamed

UITextfield value successfully updated, but not shown in table

In my app rows are added to my TableView from a different view. When the user adds the rows the user is taken back to the TableView. The problem is that the text that was previously entered is no longer shown.

I am able to load it with an NSMutableDictionary but the user cannot see it. Any ideas on what I should do? what code I should add and where I should add it? Thanks a lot!

Here is code from a tableview method. I think the fix will go in here somewhere.

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    cell.wtf = [[UITextField alloc]init];

    NSUInteger count =0;
    for (NSMutableDictionary *search in dataForAllRows){ //this just helps me pull the right data out of an array of NSMutableDictionary's

        if ([search valueForKey:@"indexSection"] == [NSNumber numberWithInteger:(indexPath.section -1)]) {

            if ([search valueForKey:@"indexRow"] == [NSNumber numberWithInteger:indexPath.row]) {

                NSMutableDictionary *match = [dataForAllRows objectAtIndex:count];
                [cell.wtf setText:[match objectForKey:@"wtf"]]; 
                NSLog(@"%@",cell.wtf.text); // this outputs the correct value in the command line
            }
        }
        count++;
     }
   }
}

Here is the code for my CustomCell.m

#import "CustomCell.h"

@implementation CustomCell
@synthesize wtf, cellPath;

- (void)awakeFromNib {
// Initialization code

 } 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)layoutSubviews{
wtf = [[UITextField alloc] initWithFrame:CGRectMake(7, 3, 65, self.contentView.bounds.size.height-6)];

self.wtf.delegate = self;

[wtf setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[wtf setAutocorrectionType:UITextAutocorrectionTypeNo];
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[wtf setBorderStyle:UITextBorderStyleRoundedRect];
wtf.textAlignment = NSTextAlignmentCenter;
wtf.keyboardType = UIKeyboardTypeNumberPad;  //
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeWords];
[wtf setPlaceholder:@"enter"];

[self.contentView addSubview:wtf];
}



via Chebli Mohamed

iOS - Create a video from array of images and save to camera roll

I am trying to create a flipbook type video out of an array of images using Objective C. I'm currently using AVCaptureDevice to capture a few picture frames per second of output, and am trying to figure out how to convert these images to be a video. I've seen some examples that use AVAssetWriter, but how do I convert to a video that can be then saved to the camera roll?



via Chebli Mohamed

sqlite3_close_v2 crashes on iOS, sqlite3_close doesn't

I'm writing some sqlite3 code in iOS for the first time. Every time I try and close the sqlite3 database connection with sqlite3_close_v2(db) where db is a sqlite3 * obtained from a call to sqlite2_open_v2, the application crashes with no helpful console output or other information but only on an actual device - it doesn't crash in the simulator.

Here's a code sample:

sqlite3_stmt *statement = NULL;
int returnCode = 0;
if((returnCode = sqlite3_prepare_v2(db, [query UTF8String], (int)strlen([query UTF8String])+1, &statement, NULL)) != SQLITE_OK || statement == NULL) {
    Log(@"Failed to create query. code:%d",returnCode);
    sqlite3_close_v2(db);
}

The code will crash on the last line in the if statement when I pass a bad query. The code will not crash on the simulator, but it will crash on both an iOS 8 iPad and an iOS 7 iPod.

The crash is reported like this (this is not my own breakpoint, by the way):

dyld`dyld_fatal_error:
->  0x1200e5088 <+0>: brk    #0x3

The breakpoint indicator says the crash is Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1200e5088).

Thread crash log

Can anyone help me debug this? I've spent a lot of time googling around to no avail. For now, I'm going to just use sqlite3_close(db), as this does not crash, but I'm worried about any consequences of using the v2 open method with the non-v2 close method...



via Chebli Mohamed

How does Quettra Portrait get the list of installed apps on non-jailbroken iOS devices?

According to the Quettra Portrait for iOS Privacy Policy they manage to get a list of installed apps on iOS. What's more, they're able to do this from an App Store approved app on non-jailbroken devices. Every Google/StackOverflow search I've done on the matter suggests that this is impossible, but Quettra is somehow able to do it without raising the ire of Apple. Any ideas?



via Chebli Mohamed

swift iOS resize view on scroll

I have a VC with a navigation bar and then a uiview under it that acts as an extension to the navbar.

Then I have a embedded table view.

What I would like to do is to add a scroll recogniser to the container view that holds the table view so when I scroll down the uiview under the navigation bar should be hidden.

Is this possible? I have used self.navigationController?.setNavigationBarHidden(true, animated: true) In order to hide the navigation bar and that works. The problem is that I now need to hide the uiview under it. And I can't get it to work/feel smooth since just a hide/show functions looks strange. I would like it to be hidden the same speed as I scroll



via Chebli Mohamed

Can I avoid reaction delay (nearly 1s) in web pages on iPhone 6?

Question

Is there any way, perhaps hardware acceleration, or WebGL, or anything, anything, I can do to speed up touch reaction speed on iPhone? I would really like the reaction to appear instant.

My problem

I noticed that my menu was taking nearly a full second to react to its icon being tapped on an iPhone 6, while the menu reacts instantly to a click on desktop. I notice this seems to be the case with all the mobile websites I visited for testing, and the ~1s delay is really bothersome, it takes away that crisp, reactive feel from the web application. Installed applications on iOS, on the other hand react instantly to touch, so I know it isn't the touch detection speed.

Example

I created an example to test this out:

var size = 'norm';
var $box = $('#box').on('click', function () {
    if (size == 'norm') {
        $box.css({
            'width' : '1in',
            'height' : '1in'
        });
        size = 'big';
    } else {
        $box.css({
            'width' : '',
            'height' : ''
        });
        size = 'norm';
    }
});
#box {
    width:0.5in;
    height:0.5in;
    margin:0.5in;
    background-color:violet;
}
<script src="http://ift.tt/1oMJErh"></script>
<div id="box"></div>

Tap the box on an iPhone and you'll see what I mean.

What I've tried

I tried inserting -webkit-transform: translateZ(0); into the item's style to activate hardware acceleration, but this didn't seem to improve speed.



via Chebli Mohamed

Spotify Embed Doesn't work on iPhone or iPad

I am using a Spotify embed on a new website that is being built in WordPress. The embed works just fine on a computer. However, on my iPad and iPhone it doesn't work. The player shows up just fine, but when I click on a track, it pops up a window that gives me the option to "Download Spotify" or "I Have Spotify." I have Spotify on both devices, but when I tap on the "I Have Spotify" button the window closes but nothing happens. Here's an example of the code I am using to play three songs in a player:

<iframe src="http://ift.tt/1IiG2qb" width="293" height="373" frameborder="0"></iframe>

Am I doing something wrong or does it just not work on iOS devices?

Thanks for any advice and/or help.



via Chebli Mohamed

how to make my win label stay hidden until the user win?

am trying to make my label hidden by changing the x and y parameter but when i start playing the game and on the first click suddenly the label appear i tried the alpha way and all the other way to hide a label were fine except this one.

this my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!


    var goNumber = 1

    var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0]

    let winnerCombination = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

    var winner = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


  override func viewDidAppear(animated: Bool) {
        self.label.center = CGPointMake(self.label.center.x - 400, self.label.center.y)

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
        @IBAction func buttonPressed(sender: UIButton) {

        if gameState[sender.tag] == 0 {
            var image = UIImage(named: "")
            if goNumber % 2 == 0 {
                image = UIImage(named: "cross.png")
                gameState[sender.tag] = 1
            }
            else{
                image = UIImage(named: "nought.png")
                gameState[sender.tag] = 2
            }
            for combination in winnerCombination {

                if (gameState[combination[0]] == gameState[combination[1]] && gameState[combination[0]] == gameState[combination[2]] && gameState[combination[0]] != 0) {

                    winner = gameState[combination[0]]

                    println("the winner is \(winner)")
                }
            }
            if winner != 0 {

                if winner == 1 {
                    label.text = "cross won"
                }
                else {
                    label.text = "nought won"
                }
                UIView.animateWithDuration(0.5, animations: {
                    self.label.center = CGPointMake(self.label.center.x + 400, self.label.center.y)

                    self.label.alpha = 1
                })
            }
            sender.setImage(image, forState: .Normal)
            goNumber++
        }
    }
}



via Chebli Mohamed

Scroll View Size not match with the device screen in xcode

Ok, I tried the page with several buttons but all of them will not fit in one screen. So, I create the scroll view and the view and then put all of buttons inside the view. The storyboard look fine. Other devices such as iPhone 5 and 5S look fine but when I tried 6 and 6 plus, the size of scroll view was incorrect. I couldn't figure what went wrong.

storyboard

tree1

tree2

iPhone 5s

iPhone 6



via Chebli Mohamed

Swift Airdrop Save Device Name To App

When you see someone's device name through Airdrop (when using iPhones/iPads, for example), is there any way to programmatically get and store that device name? I thought it might involve the UIDevice class, but that seems more for getting my OWN device name.

In my app, I'd like to set up a local dictionary for frequently-encountered contacts, where the user can take a picture and save it along with the peer's device name (right now you can't always guarantee the other person will have a photo associated with his or her device). I know how to take and store a picture programmatically. I just need to figure out how to access and save another person's device name when in Airdrop range to associate with the photo.

I'm open to other methods besides Airdrop to get and store a device name to associate with a photo, but I want to keep the ability to read only devices that are within close proximity of the sender's device. Airdrop just seems like a good way to do that.

Thanks in advance.



via Chebli Mohamed

Dynamic cell height in UITableView with variable number of subviews

I was wondering if someone could help me in this feature for dynamic cells for UITablewView.

I need to add subviews to a cell depends on some context. So the cell will grows if a have more than one of this subviews:

enter image description here

I'd like to know how can I add this subviews programatically and how to make the cells grows dynamic using constraints?



via Chebli Mohamed

How to save video recording to documents directory with swift?

I have written this code to record video and would like to save the filePath to the documents directory, how can I do this?

func startRecording() {
    var currentDateTime = NSDate()
    var formatter = NSDateFormatter()
    formatter.dateFormat = "MM-dd-yyyy, hh:mm:ss a"
    var recordingName = formatter.stringFromDate(currentDateTime) + ".mp4"
    var pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
        videoRecorder = UIImagePickerController()
        videoRecorder.delegate = self
        videoRecorder.sourceType = UIImagePickerControllerSourceType.Camera
        videoRecorder.mediaTypes = [kUTTypeMovie]
        videoRecorder.videoMaximumDuration = 3600.0
        videoRecorder.startVideoCapture()
    }
}



via Chebli Mohamed

UIStoryboardSegue: top view is not sliding down

I have the following swift code and what i am trying to achieve is a segue that slides off the top. I want the secondVCView to be below the firstVCView and for the firstVCView to slide off displaying the secondVCView.

Currently there is no animation and it just flashes to the secondVCView.

Many Thanks

import UIKit

class TopToBottomSegue: UIStoryboardSegue {

override func perform() {

    // Assign the source and destination views to local variables.
    var firstVCView = self.sourceViewController.view as UIView!
    var secondVCView = self.destinationViewController.view as UIView!

    // Get the screen width and height.
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(0, 0, screenWidth, screenHeight)

    // Access the app's key window and insert the destination view below the current (source) one.
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(secondVCView, belowSubview: firstVCView)

    // Animate the transition.
    UIView.animateWithDuration(0.4, animations: { () -> Void in

        firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, screenHeight)
        //secondVCView.frame = CGRectOffset(secondVCView.frame, -screenWidth, 0.0)

        }) { (Finished) -> Void in
            self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                animated: false,
                completion: nil)
    }

  }
}



via Chebli Mohamed

CABasicAnimation - view should position on the last frame

Hello i want to do a CABasicAnimation rotation where my view rotates 440 degree. After the animatin i don´t want to reset the view to the old position. It should be on the same position like on the last frame of the animation.

CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];

rotate.toValue = [NSNumber numberWithFloat:degrees / 180.0 * M_PI];
rotate.duration = 4.4;
[rotate setFillMode:kCAFillModeForwards];
UIView *animationView = [self getBGContainerViewForSender:sender];
[animationView.layer addAnimation:rotate forKey:@"myRotationAnimation"];</i>

Can anybody tell me how to position the view on the last frame?



via Chebli Mohamed

UITableView is displayed half of the screen after converting to Universal app

I want to convert an iphone app to universal. the iphone storyboard has a UITableView. I used Auto-layout and Use Size Classes using the latest XCode and added missing constraints however I cannot make the tableView and its cells go all the way down; it's only half way of the screen. Can anyone have an idea on how to do this; Thank you very much. I attached the screenshot here View Screenshot



via Chebli Mohamed

I want to make Custom Lock Screen iOS app

I am making custom lock screen app for iOS, having a locker type objects with user defined color matching scheme to open locked screen, Can anybody help me while providing useful tutorial or any other useful material coding or anything else helpful in this regards that how to make a lock screen app programmatically?



via Chebli Mohamed

bootstrap slider not showing tooltip on iphone 6, mobile device

Hi just found an issue on bootstrap sliders which you can download from http://ift.tt/1lwYnrc or http://ift.tt/1bHa8Vr

both of these plugins seem to be having the same issue on iphone 6 - the tooltip is not showing up when sliding the slider. I have checked only on iphone 6 but i assume the same issue is for other mobile devices. Has anyone found a solution for that?



via Chebli Mohamed

Where is iCloud Drive for Sandbox?

I create a folder on iCloud Drive using this:

NSFileManager *fManager = [NSFileManager defaultManager];

NSURL *ubiq = [fManager URLForUbiquityContainerIdentifier:nil];
NSURL *iCloudDocumentsURLTemp = [ubiq URLByAppendingPathComponent:@"Documents"];

NSError *error = nil;

if (![fManager fileExistsAtPath:iCloudDocumentsURLTemp.path]) {
  [fManager createDirectoryAtURL:iCloudDocumentsURLTemp
     withIntermediateDirectories:YES
                      attributes:nil
                           error:&error];      
}

The first time I run this, it creates the folder. The second time it says the folder already exists.

I don't see the folder on icloud.com or in beta.cloud.com.

How do I see the folders/files I am creating there?



via Chebli Mohamed

Why doesn't my best score value load after game closes and launches again? (Swift)

My best score value works perfectly fine if the game keeps running, but it won't load the best score if the game closed and was to launch again. It goes back to zero every time it the launches again.

Here is what I'm doing:

import SpriteKit

class EM: SKScene, SKPhysicsContactDelegate {

var bestScoreText = SKSpriteNode()

let bestScoreCategory: UInt32 = 1 << 4

var bestScoreLabelNode = SKLabelNode()
var bestScore = NSInteger()

override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    var bestScoreDefault = NSUserDefaults.standardUserDefaults()

    if (bestScoreDefault.valueForKey("bestScore") != nil) {
        bestScore = bestScoreDefault.valueForKey("bestScore") as! NSInteger!

    }
.......
....... 
     bestScore = 0
  }



func didBeginContact(contact: SKPhysicsContact) {


    if (score > bestScore) {

        bestScore = score

        var bestScoreDefault = NSUserDefaults.standardUserDefaults()
        bestScoreDefault.setValue(bestScore, forKey: "bestScore")
        bestScoreDefault.synchronize()

    } else {
......
}



via Chebli Mohamed

Swift ios is it bad to have an embedded table view

I wonder if there is any downside in having an embedded table view?

I have a navigation controller VC that leads to another VC which is my apps "main/root" VC.

Inside that VC I have a container view which holds an table view.

Is this a bad setup? The table view then has more segues leading to other VC's



via Chebli Mohamed

Videos recorded from app has incorrect creation date from PHAsset

I have an app that records video and displays them in a certain order. The videos recorded in my app has the correct date, but the times were all the same. So, all of the video recorded today show: 2015-07-31 13:15:51 +0000

I'm not setting any properties related to time in my capture session or movie output. I can't seem to find any documentation on how to do this properly. Does anyone have an idea?

Thanks!

Update: I recorded more video within the app. Turns out that the date is also wrong. It’s creation date reads the same as all the other videos created previously. For kicks, I delete the app from my phone, recorded a new video. It has the correct day and time. But after recording a second video, the date and time is the same as the previous recorded video.



via Chebli Mohamed

xcode build is fine for some platforms, but failed with others (files not found)

My project builds perfectly for iPhone6(8.4), 6+, 5s, iPad air, but fails for iPhone 5, 4s, iPad retina and iPad2. It fails also if I build it for my own iPhone6(8.4), whereas it works for the same device in simulator. It therefore prevents me from making an archive.

Each time, it is the same errors : use of undeclared type... As shown below

build fails

It looks like it doesn't find the DrawerController framework.

I've tried to clean several times, to start again XCode, to remove and add the framework, to add them into embedded libraries, but nothing works.

I can not manage to find what I may have did wrong, as it works perfectly for some architectures, so the frameworks are found for those ones.

Thanks



via Chebli Mohamed

direct video streaming from s3 to ios devices

I am new to ios development and creating the application which will stream videos from amazon s3 to ios device moreover I store videos in mp4 format.Can I directly stream mp4 videos from s3 to ios?if so how can I start to achieve it.



via Chebli Mohamed

Non-renewing subscription end date

I'm developing an iOS app with a non-renewing subscription. We want to use MKStoreKit to handle everything related with IAP. My understanding is that we've to manage "manually" when the subscription is finished in order to don't show the premium contents to the users.

  • How can this be done if nothing is stored in our servers?
  • Can we check (somehow with MKStoreKit) the subscription date in order to calculate the ending date?
  • If users have several devices, we guess we'll need to implement the "restore" method so all the devices will be able to see the premium contents, no?
  • And what happens if once the first subscription is over, a user decides to subscribe again? Will we know both beginning dates? just the last one?

Thanks!



via Chebli Mohamed

Converting tethered jailbreak into untethered jailbreak?

Hello is it possible to convert a downgraded iphone 4 (tethered) into a untethered jailbreak with saving of shsh blobs? Or there any other ways to make it possible? ios on the iphone 4 is horrible.



via Chebli Mohamed

SpriteKit move physics body on touch (air hockey game)

I'm trying to make an air hockey game using SpriteKit. I trying to make the pucks draggable but I can't make them continue to move after the touch has ended. Right now I am binding the touch and the puck and setting it's position when the touch moves.



via Chebli Mohamed

iPhone OS does not match app deployment version

I am using the Xcode 7.0 beta, trying to use iBeacon thing. I don't have developer account, but heard the beta can run apps on your device. But when I was trying to run the program, device OS version is lower than deployment target my phone is iPhone 5 ios 8.4 which is the most new version. however the deployment target is IOS 9.0. How can i fix this problem.



via Chebli Mohamed

iOS best practice to display errors for a uitableview after pull to refresh and/or scroll to load more

I've recently developed an android app and used toasts to display any errors (network or web service errors) that may have happened when pulling to refresh or scrolling to load more in a table. They were great at displaying these errors without being to invasive or requiring user input to remove.

Seeing as iOS doesn't have a toast equivalent I wanted to know what are considered best practices on iOS to display errors when pulling to refresh or scrolling to load more in a UITableView.

Personally a UIAlertView seems a bit to invasive and requires a user input to remove, but I could be wrong and that may be the standard on iOS. I'm not opposed to using libraries out there that have implemented toast like views, but I figured I'd check if there was a better way since it's not built in.

Any suggestions on this would be great. Thanks!



via Chebli Mohamed

How to sign out with Google+ on iPhone

I am writing an application where user can login using Google+. I followed GOOGLE Developer console and successfully logged in and obtained the user profile information through Access_Token. and i want to login through web view, but how to make sign out after login?

My Webview method

-(void)addWebView
{

    NSString *url = [NSString stringWithFormat:@"http://ift.tt/Kyk9ty",client_id,callbakc,scope,visibleactions];

    self.webview = [[UIWebView alloc]init];
    self.webview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    self.webview.delegate = self;
    [self.view addSubview:self.webview];
    [self.webview  loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];


}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    //    [indicator startAnimating];
    if ([[[request URL] host] isEqualToString:@"localhost"]) {

        // Extract oauth_verifier from URL query
        NSString* verifier = nil;
        NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"];
        for (NSString* param in urlParams) {
            NSArray* keyValue = [param componentsSeparatedByString:@"="];
            NSString* key = [keyValue objectAtIndex:0];
            if ([key isEqualToString:@"code"]) {
                verifier = [keyValue objectAtIndex:1];
                NSLog(@"verifier %@",verifier);
                break;
            }
        }

        if (verifier) {
            NSString *data = [NSString stringWithFormat:@"code=%@&client_id=%@&client_secret=%@&redirect_uri=%@&grant_type=authorization_code", verifier,client_id,secret,callbakc];
            NSString *url = [NSString stringWithFormat:@"http://ift.tt/IlrJjr"];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
            NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
            receivedData = [[NSMutableData alloc] init];

        } else {
            // ERROR!
        }

        [webView removeFromSuperview];

        return NO;
    }
    return YES;
}



via Chebli Mohamed

Replay button doesn't work. (Swift, SpriteKit)

Once my game ends, it displays a button for replay, but I can't understand how to let Xcode know if there is a touch after the game has ended. My replay button's code is in didBeginContact Method and is as follows:

func didBeginContact(contact: SKPhysicsContact) {
       if (.....) {
            ..........
      }  else {
         replayButton = SKSpriteNode(imageNamed: "ReplayButton")
            replayButton.position = CGPoint(x: size.width / 1.75, y: size.height / 2.5)
            replayButton.name = "replayButton"
            self.addChild(replayButton)
       }

New Swift file:

class button: Mode {


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

var touch = touches as!  Set<UITouch>
var location = touch.first!.locationInNode(self)
var node = self.nodeAtPoint(location)


if (node.name == "replayButton") {

    let myScene = EasyMode(size: self.size)
    myScene.scaleMode = scaleMode
    let reveal = SKTransition.fadeWithDuration(2.0)
    self.view?.presentScene(myScene, transition: reveal)
    }
  }
}



via Chebli Mohamed

How i can play [UInt8] audio stream?

I am connected to the server via TCP / IP and receives [UInt8]. I know that it is the audio. How to play the stream on the iPhone?



via Chebli Mohamed

Constraints for buttons between all device sizes xcode 7

I have three buttons laid out like this in Xcode: http://ift.tt/1DquD8w

As you can see, I have errors for my constraints within my storyboard. I used constraints from a picture that someone from here on stack overflow drew up for me:

http://ift.tt/1Ul0Xyc

I've tried many other constraints but I can't seem to figure out what constraints to use.

How can I fix this so it looks like it does in the storyboard across all iPhones and iPads? Landscape mode will not be a part of this application.



via Chebli Mohamed

How to change the duration of a movement with count- Swift SpriteKit?

In my game, there's a class for a "wall" that's moving to the left. I want to change the speed of it based on count i that I added to touchesBegan method:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent {
    count++
}

func startMoving() {

    let moveLeft = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 1 )

    let move = SKAction.moveByX(-kDefaultXToMovePerSecond, y: 0, duration: 0.5)

    if(count <= 10)
    {
        runAction(SKAction.repeatActionForever(moveLeft))
    }
    else
    {
    runAction(SKAction.repeatActionForever(move))
    }
}

but it's not working. Can you help?



via Chebli Mohamed

How can I save video to photo library?

I copied this code from a book and arrange it to my code but I have doubts how to save the videos that I'm recording. Do I need to take the video URL? if so, how can I take it? Thanks

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as? NSString

    self.dismissViewControllerAnimated(true, completion: nil)

    if mediaType == (kUTTypeImage as! String) {
        let image = info[UIImagePickerControllerOriginalImage] as? UIImage

        imageView.image = image

        if (newMedia == true) {
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        } else if mediaType == (kUTTypeMovie as! String) {
            //Code to support video


        }

    }
}



via Chebli Mohamed

Segue from Container View

I am trying to create a segue from a container view (left VC) to a view controller (right VC). I want to be able to click on a person, who will be displayed on the left VC, and chat with him on the right VC. The thing is when I create the segue, the VC on the right instantly becomes the same size as the container view and gains the tab bar/navigation bar that the container view has. It there any way I can connect the container view with the new VC and making the new VC an independent one? Thanks

enter image description here



via Chebli Mohamed

Swift iOS static uitableviewheader

I wonder if its possible to add a static uitableviewheader? I want the header to look like an extension of the navigation bar. But I can't get it to work, my header keeps scrolling with the table view.



via Chebli Mohamed

Push messages longer than 255 characters not reaching iPhone

I'm trying to send a push notification to a device - which is longer than 255 characters.

I'm not getting any errors from Apple servers but the push notification does not reach my device.

  1. Using Pusher (http://ift.tt/M5cofk) the push notification DOES reach the device - using the same certificate.
  2. Sending a push notification smaller than 255 characters DOES reach the device

What could be the issue?



via Chebli Mohamed

iOS autolayout issue

i am using xcode 6.4. i have a view controller named "sample".The view controller contain a scroll view.The scrollview contain another view(container view).The width of container view is thrice of the width of scrollview.when the scroll view is swiping right(or left) it must show the 3 parts of the container view.I did it using paging enabled property of UIscrollview(without auto-layout).But when using auto-layout i cant find a solution.Can anybody tell me a solution for this???please explain constraints for scroll view and container view.Can anybody upload a demo???



via Chebli Mohamed

what is typedef long dispatch_once_t in objective c [duplicate]

This question already has an answer here:

i was going through this tutorial, and i noticed they used:

typedef long dispatch_once_t

yet they did not explain what it does. Furthermore, I have no idea what does "typedef long" mean ? i tried searching through references but didnt find an answer. Can you provide an example of how typedef long works ?



via Chebli Mohamed

JSON parsing using [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error] thowing nil

error = Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7fa4e25da7c0 {NSDebugDescription=Garbage at end.}

If changing NSData to NSString , response is getting but using

id jsonData = [NSJSONSerialization JSONObjectWithData:dataJson options:0 error:&error]

showing above error, and response nil.



via Chebli Mohamed

How to force or disable interface orientation for some but not all UIViewController?

I have an app with 9-10 screens. I embedded a UINavigationController into my view controller. I have few view controllers which I want set only portrait orientation: it means that rotating the device should not rotate these view controllers to landscape mode. I have tried the following solutions:

first:

   NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
   [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

but screen still rotates to landscape.

Second: I created a custom view controller class as PortraitViewController and added the code below in PortraitViewController.m

@interface PortraitViewController ()
@end

@implementation PortraitViewController
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    //Here check class name and then return type of orientation
    return UIInterfaceOrientationMaskPortrait;
}
@end

After that I implemented PortraitViewController.h as a base class

#import <UIKit/UIKit.h>
#import "PortraitViewController.h"
@interface Login : PortraitViewController
@end

It does not work at all, still allows view controller to rotate in landscape mode.

Is there any other solution i am using iOS 8 & don't want viewcontroller to rotate in landscape mode?

EDIT: Is it possible to have Landscape orientation only for some view controllers, and force other view controllers orientation to stick to Portrait?



via Chebli Mohamed

dimanche 28 juin 2015

Python script to reboot server N times

I'm trying to stress test several servers that I can ssh into. I'm trying to write a python script that causes a reboot loop for N times. I call

os.system('reboot') 

But, I'm not sure how to have the script continue execution once the server has finished booting to continue execution. The servers do run various distros of Linux. Any help would be great.

The use of need_resched flag and schedule() routine within Linux kernel [2.4]

As per my understanding when the kernel finds out that the current running process should be striped of the CPU, it enables the need_resched flag. The flag is checked before returning to user space, and if the flag enabled the kernel initiates call for schedule(). However I have noticed that within sys_sched_yield() routine we don't use the need_resched flag but explicitly call the schedule() routine. Why?

Easyphp works, linux server return Call to a member function on a non-object

I am using Easyphp for development with default settings. All my code works fine with connection on local Easyphp db. But when I upload it on my webhosting which is using linux server - all functions with objects suddenly are returing OOP errors. This is exp. of normal function I normaly write:

function user_data($user_id){
    global $db;
    $data = array();
    $user_id = (int)$user_id;

    $func_num_args = func_num_args();
    $func_get_args = func_get_args();

    if($func_num_args > 1) {
        unset($func_get_args[0]);
        $fields = '`' . implode('`, `', $func_get_args) . '`';
        $query = "SELECT $fields FROM users WHERE user_id = '$user_id'";
        $result = $db->query($query);
        $data = $result->fetch_assoc(); 
        return $data;
        $result->free();
        $data->free();
    }
}

Everything works fine on my local php server. After I upload it on webhosting with linux server I get " Call to a member function fetch_assoc() on a non-object error " on lines like :

 $data = $result->fetch_assoc();

Can anybody tell me what I am writing wrong?

DB connection for easyphp:

 $db = new mysqli("$DB_HOST","$DB_USER","$DB_PASSWORD","$DB_NAME");

DB connection for linux server:

 $socket = "/tmp/mysql51.sock";
 $db = new mysqli("$DB_HOST","$DB_USER","$DB_PASSWORD","$DB_NAME", 0, $socket);

Thank you

EDIT - SOLUTION

I found the reason for error. It is in writing variables in SQL query inside PHP code. Query should be like:

$query = "SELECT $fields FROM users WHERE user_id = '".$user_id."'";

Reason of error is still for me mistery. it can be platform or PHP versions.

UNIX: Unexpected End of file

I have a problem where the editor reports no problems, but when I run it in a terminal, it reports: Unexpected end of file.

What I'm trying to do is get it so that when this script is run, it changes the permissions so that everyone can execute the file.

I'm scripting the file on a Windows Machine:

#!/bin/bash

file=~\scripts\chmxtextfile.txt

if [[  -e "$file"  ]];   
then {chmod ugo+x $file} 
elif [[  ! -e "$file"  ]];
then echo "File doesn't exist"
fi

Beaglebone Black; Wrong SPI Frequency

I'm new at programming the Beaglebone Black and to Linux in general, so I'm trying to figure out what's happening when I'm setting up a SPI-connection. I'm running Linux beaglebone 3.8.13-bone47.

I have set up a SPI-connection, using a Device Tree Overlay, and I'm now running spidev_test.c to test the connection. For the application I'm making, I need a quite specific frequency. So when I run spidev_test and measure the frequency of the bits shiftet out, I don't get the expected frequency.

enter image description here

I'm sending a SPI-packet containing 0xAA, and in spidev_test I've modified the "spi_ioc_transfer.speed_hz" to 4000000 (4MHz). But I'm measuring a data transfer frequency of 2,98MHz. I'm seeing the same result with other speeds as well, deviations are usually around 25-33%.

How come the measured speed doesn't match the assigned speed? How is the speed assigned in "speed_hz" defined? How precise should I expect the frequency to be?

Thank you :)

How to debug a simple program using gdb inside a complex command line?

Let's say I have a program called _program. I run it inside a larger stdin/stdout command line like that:

echo Hello world | _program >> output.txt

How to debug _program using gdb?

Why does this command kill my shell?

Update: This is a more general command that is more reproducible. ShellFish identified that there is a more general pattern:

non-existingcommand & existingcommand &

for example,

xyz & echo &

Also, I had a coworker try over an ssh connection and his connection was closed after running the command. So this doesn't appear to be limited to a certain terminal emulator.

Original question:

echo?a=1&b=2|3&c=4=

Behavior:

After executing the command, my current Gnome Terminal tab closes without warning.

Background:

We were testing a URL with a curl command but forgot to quote it or escape the special characters (hence the ampersands and equals signs). Expecting some nonsense about syntax issues or commands not found, we instead watched our shell simply quit. We spent some time narrowing the command down to the minimum that would cause the behavior.

We are using Gnome Terminal on Ubuntu 14.10. Strangely, the behavior is not present on another box I have running byobu even if I detach from the session. It also doesn't happen on Cygwin. Unfortunately I'm limited to testing with Ubuntu 14.10 otherwise.

Note: The following command also kills my terminal but only about half of the time:

echo?a=1&b=2&c=3=

Additional tests:

Someone recommend using a subshell...

guest-cvow8T@chortles:~$ bash -c 'echo?a=1&b=2|4&c=3='
bash: echo?a=1: command not found
guest-cvow8T@chortles:~$ bash: 4: command not found

No exit.

location direct domain.com to www.domain.com on multi site server

thank you for viewing this. Please advise that my server is running LEMP on Debian Jessie.

I am trying to force "www." to occur. I was able to do this with the following solution found on Stackoverflow.

return       301 http://ift.tt/1mDYAZp;

However, I am running several websites from the server and the issue I am running into is as follows.

When logging into wordpress http://ift.tt/1KiJWke on one website, it routes me to http://ift.tt/1LOLvFH. I believe this issue has to do with a default_server or hostname issue. Do I need to add all hostnames to /etc/hostname ?

Here is my host file

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        listen 443 ssl default_server;
        listen [::]:443 ssl default_server;

        root /var/www/site0;

        index index.php index.html index.htm;

        server_name site0.com;
        #return 301 http://ift.tt/1KiJWki;
        location / {
                try_files $uri $uri/ =404;
                #try_files $uri $uri/ /index.html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php5-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php5-fpm:
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                #fastcgi_index index.php
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

server {
        listen 80;
        listen [::]:80;

        # SSL configuration
        #listen 443 ssl;
        #listen [::]:443 ssl;

        root /var/www/site1;

        index index.php index.html index.htm;

        server_name site1.com;
        #return 301 http://ift.tt/1KiJYZo;
        location / {
                try_files $uri $uri/ =404;
                #try_files $uri $uri/ /index.html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php5-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php5-fpm:
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                #fastcgi_index index.php
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

I am thinking part of the issue has to do with: listen 80 default_server; listen [::]:80 default_server;

Please help if you can, it will be very much appreciate.

character issue utf-8 lamp centos

after installation of LAMP on centos, every work fine but show a ptoblem with character, every letters such as "is" "u" "ò" and other classic characters are replaced by "?", frequently recurring problem with UTF-8.

so i started this setting :

**http.conf** : AddDefaultCharset utf-8


in **php.ini** : default_charset = "utf-8"
mbstring.internal_encoding=utf-8
mbstring.http_output=UTF-8
mbstring.encoding_translation=On
mbstring.func_overload=6

**my.conf**   character_set_server=utf8    

**in html php file**: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

and finally on /etc/sysconfig/i18n with this code :

default setting:

LANG="en_US.UTF-8"
SYSFONT="latarcyrheb-sun16"

my setting:

LANG="it_IT.UTF-8"
SYSFONT="latarcyrheb-sun16"

italian is my language , after this also show the command linux ""locale ""

LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

if you show not change the language , why ??

Why does my assembly program gives segfault?

I have the following piece of code that I have to debug:

global _start
_start:
pop esp
js 0x36
xor [eax+edi*2+0x43],ebx
xor [eax+edi*2+0x35],bl
xor [eax+edi*2+0x36],bl
cmp [eax+edi*2+0x37],bl
ss pop esp
js 0x49
aaa
pop esp
js 0x52
xor al,0x5c
js 0x56
xor al,0x5c
js 0x59
cmp [eax+edi*2+0x37],bl
xor ebx,[eax+edi*2+0x32]

After compiling and running that code I obtain a segmentation fault error, it seems that something goes wrong after the 5th line. My linux asm knowledge is very basic, any hints or ideas about what is exactly going wrong and how to fix it?

how to configure Qt for android

I am using Debian Linux and I want to configure Qt for Android application. I downloaded Qt from the Qt site and configured JDK, SDK and NDK and gave the path of SDK and NDK path to Qt option, then I restarted Qt creator. But in Debuggers option Qt says:

/home/user/Qtrequirement/android-ndk-r10e/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gdb not exist.

I searched in Google and I found out another NDK at Qt official that has a gdb file but not have every file for NDK. Qt says this is not top level NDK folder.
I googled everything and installed every dependency package that Qt uses.

Can anyone give me any solution that makes apk file and run in any Android device?
FYI any other application that does not use Android will run successfully, but I can not make an apk file using Qt.
Does anyone know the answer for this problem for Debian Linux?

How to grep just strings "ip" into a file?

I am trying to find every way to find a string in some text. I want to find more ways using grep or sed. (bear in mind It's case sensitive)

  • Every word (strings) containing string "ip" and redirect the output result in /root/found;
 grep ip /usr/share/dict/words/ > /root/found
  • Just words (strings) initiating with "ip" and redirect the output result in /root/found;
 grep ^ip  /ust/share/dict/words > /root/found 
  • Just the word "ip" and redirect the output result in /root/found;
grep ^ip$ /ust/share/dict/words > /root/found

does gSoapWinhttp plugin with gSoap supports linux

I'm using gSoap proxy services for ews and i need SSL and Auth. support for the endpoint. While my prefer platform is Linux. From gSoap documentation http://ift.tt/1QXhMko found that it has all SSL and Auth. support in C for linux but i'm using C++.

So when i search on google for SSL and Auth. supports with gSoap in C++, i found http://ift.tt/1QXhKcp link for gsoapwinhttp.

gSoap documentation says that it support most of the platform like windows, linux, macOS etc. and gsoapwinhttp use windows library, so i'm bit of confusing does this gsoapwinhttp plugin with gsoap supports linux platform?

Any help appreciated. thank you.

Getting the destination address of UDP packet

I have been using the following example posted in this same site. This is my version of it. (Please excuse my lack of experience with C socket programming:)

In constructor:

int sock = udpsocket_.native();
// sock is bound AF_INET socket, usually SOCK_DGRAM
// include struct in_pktinfo in the message "ancilliary" control data
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
int opt = 1;
setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt));

Where "udpsocket_" is actually a boost asio udp socket. This is very convenient since on one hand I can have a function which gets the destination IP from the incoming UDP message without the need for using a raw socket:

int sock = udpsocket_.native();
char cmbuf[0x100];
struct sockaddr_in peeraddr;
struct msghdr mh;
mh.msg_name = &peeraddr;
mh.msg_namelen = sizeof(peeraddr);
mh.msg_control = cmbuf;
mh.msg_controllen = sizeof(cmbuf);
int received = recvmsg(sock, &mh, 0);
for ( // iterate through all the control headers
        struct cmsghdr *cmsg = CMSG_FIRSTHDR(&mh);
        cmsg != NULL;
        cmsg = CMSG_NXTHDR(&mh, cmsg))
{
    if (cmsg->cmsg_level != IPPROTO_IP ||
            cmsg->cmsg_type != IP_PKTINFO)
    {
        continue;
    }
    struct in_pktinfo *pi = (struct in_pktinfo*) CMSG_DATA(cmsg);
    char* destAddr = (char*) calloc(4, sizeof(char));
    destAddr = inet_ntoa(pi->ipi_spec_dst);

    stored_UDP_dest_ip_ = ip::address::from_string(destAddr);
}

Now here come the problems:

  • Could I call this "get_destination_IP" asynchronously, in a non-blocking way in the same way as I call "async_receive_from" ?

    • "recvmsg" stores the right destination IP info, but returns 0. In theory according to the man page, the "size_t numbytes" is returned there. Can I still read the datagram with "recvmsg"?
  • Is FD_ZERO necessary here?

  • Is FD_ZERO necessary at every call of the function?

Thank you beforehand for your help

Read only debugfs file is being written to. Why is that?

I have created a file using debugfs API inside /sys/kernel/debug/test/testFile. I have created the file with mode set to 444, so it is now read only.

Now I have essentially followed this tutorial in creating this debugfs file. And for this file both read and write are define. Moreover, concretely, I create file using this:

debugfs_create_file("testFile", 444, pDebugfs, NULL, &debugfs_fops)

File is successfully created and I can easily read from it by cat ... but why I can write to it too even though I can explicitly created as read only. I am logged in as root. Why is that? Should not it not allow me to write to it?

Finally, ls -l results:

-r--r--r-- 1 root root 0 جون 28 15:27 /sys/kernel/debug/test/testFile

Now, you may argue that since I am root, I can write to any file. Well, then if you search let's access blob file on the page, the OP cannot write to blob file, even though as root, because it is read only. Why is that?

Best Light server (Linux + Web server + Database) for Raspberry Pi [on hold]

I would like to install a web server with a database on a Raspberry Pi (little computer). The computer has only 1GB RAM.

I want to know what is the best combination: Linux distribution and web server and DBMS to run the local server with multiple users with minimal latency, I will use PHP on the server. And what are the best settings for good performance and to not have bugs (memory usage, disable plugin, disable service, etc)?

I thought a light Debian , a lighttpd server and SQLite for the database. Is this is a good solution?

Performance of system("rm x.*") vs unlink()?

I'm maintaining a Linux legacy system which maintains millions of small files in a large storage array. (yes, filesystem nightmare)

In the C++ code I found files being deleted like system("rm -f /dir/dir/file.*")

I suspect using unlink() is going to be a lot faster, but how much faster? (I can't really test it in production)

Anybody have some comparative data on this?

The old code is already fragile and replacing the handy system() calls with unlink() and getting the globbing to work, etc, is a good chunk of work...

g++ fails with "undefined reference" errors to the standard C++ library

I have built and installed g++ and tested it on a simple "Hello World" program and it appears to work.

However, for our larger code, the compile fails with errors such as:

CMakeFiles/gaim_convert.dir/GaimConvert.cpp.o: In function Output(std::string const&, std::ostream&)':GaimConvert.cpp:(.text._Z6OutputRKSsRSo[_Z6OutputRKSsRSo]+0x12): undefined reference tostd::basic_ostream >& st d::__ostream_insert >(std::basic_ostream >&, char const*, long)'

The program that works correctly is:

#include <iostream>

int main() {
  std::cout << "Hello World!" << std::endl;
  std::cin.get();
  return 0;
}

So clearly certain parts of the C++ standard library are installed correctly. This is not simply an "obvious" installation bug that does not have libstdc++ installed.

The code will compile with a different version of the compiler, so it's not the code.

What is a way to debug the installation so that this error message is removed? The library path is LD_LIBRARY_PATH:

/tec/mannucci/gccBuild/lib64:/tec/mannucci/gccBuild/lib:/usr/local/gmp510/lib:/usr/local/mpfr311/lib:/usr/local/mpc101/lib:/usr/local/ppl011/lib:/usr/local/cloog0162/lib:/usr/local/lib64:/usr/lib64:...

Thank you.

-Tony

What happens internally when deleting an opened file in linux

I came across this and this questions on deleting opened files in linux

However, I'm still confused what happened in the RAM when a process(call it A) deletes an opened file by another process B.

What baffles me is this(my analysis could be wrong, please correct me if so):

  • When a process opens a file, a new entry for that file in the UFDT is created.
  • When a process deletes a file, all the links to the file are gone especially, we have no reference to its inode, thus, it gets removed from the GFDT
  • However, when modifying the file(say writing to it) it must be updated in the disk(since its pages gets modified/dirty), but it got no reference in the GFDT because of the earlier delete, so we don't know the inode to it.

The Question is why the "deleted" file still accessible by the process which opened it? And how is that been done by the operating system?

Make "Add Qt Sources" work for Qt SDK on Linux (NOT built from source)

This is similar to my question about Step into Qt Sources from Qt Creator on Windows (NOT built from source), but I can't make it work for Linux.

Instead of building from source, I have downloaded the Qt SDK installer, and I've installed Qt to /opt/Qt, and I have the sources at /opt/Qt/5.4/Src.

I cannot step into Qt Sources, so I tried adding a Source Mapping using "Add Qt Sources":

enter image description here

I have tried mapping /var/tmp/qt-src to /opt/Qt/5.4/Src, /opt/Qt/5.4/Src/qtbase, and /opt/Qt/5.4/Src/qtbase/src, none of which worked.

What am I doing wrong? Is the source mapping not /var/tmp/qt-src, or is the target mapping wrong? Does "Add Qt Sources" work at all for the Qt SDK?

I saw a suggestion in a forum thread that it's because the Qt SDK for Linux ships only stripped binaries, while it ships both debug and release DLLs for Windows (which would explain why it worked for Windows, but not for Linux).

Find the process information with top command in java

I want to get the process information using the top command ,i have the below code but it is not working ,it just exists the program without any output .My objective is to get the processname,processid,memoryusage but that's the later part,I am stuck in getting process information using top command in java using grep.

public void getProcessInfo(String processName){

    Runtime rt = Runtime.getRuntime();
    try{
        String[] cmd = { "/bin/sh", "-c", "top | grep "+processName };

        Process proc = rt.exec(cmd);

        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);

        String line = null;


        while ( (line = br.readLine()) != null){

            System.out.println(line);

        }



    }catch(Exception e){
        e.printStackTrace();
    }
}

}

format and filter file to Csv table

I have a file that contains many logs :

Ps: the question is inspired from a previous question here. but slightly improved.

at 10:00 carl 1 STR0 STR1 STR2 STR3 <STR4 STR5> [STR6 STR7] STR8:
academy/course1:oftheory:SMTGHO:nothing:
academy/course1:ofapplicaton:SMTGHP:onehour:

at 10:00 carl 2 STR0 STR1 STR2 STR3 <STR4 STR78> [STR6 STR111] STR8:
academy/course2:oftheory:SMTGHM:math:
academy/course2:ofapplicaton:SMTGHN:twohour:

at 10:00 david 1 STR0 STR1 STR2 STR3 <STR4 STR758> [STR6 STR155] STR8:
academy/course3:oftheory:SMTGHK:geo:
academy/course3:ofapplicaton:SMTGHL:halfhour:

at 10:00 david 2 STR0 STR1 STR2 STR3 <STR4 STR87> [STR6 STR74] STR8:
academy/course4:oftheory:SMTGH:SMTGHI:history:
academy/course4:ofapplicaton:SMTGHJ:nothing:

at 14:00 carl 1 STR0 STR1 STR2 STR3 <STR4 STR11> [STR6 STR784] STR8:
academy/course5:oftheory:SMTGHG:nothing:
academy/course5:ofapplicaton:SMTGHH:twohours:

at 14:00 carl 2 STR0 STR1 STR2 STR3 <STR4 STR86> [STR6 STR85] STR8:
academy/course6:oftheory:SMTGHE:music:
academy/course6:ofapplicaton:SMTGHF:twohours:

at 14:00 david 1 STR0 STR1 STR2 STR3 <STR4 STR96> [STR6 STR01] STR8:
academy/course7:oftheory:SMTGHC:programmation:
academy/course7:ofapplicaton:SMTGHD:onehours:

at 14:00 david 2 STR0 STR1 STR2 STR3 <STR4 STR335> [STR6 STR66] STR8:
academy/course8:oftheory:SMTGHA:philosophy:
academy/course8:ofapplicaton:SMTGHB:nothing:

I have tried to apply the code below but in vain :

BEGIN {
    # set records separated by empty lines
    RS=""
    # set fields separated by newline, each record has 3 fields
    FS="\n"
}
{
    # remove undesired parts of every first line of a record
    sub("at ", "", $1)
    # now store the rest in time and course
    time=$1
    course=$1
    # remove time from string to extract the course title
    sub("^[^ ]* ", "", course)
    # remove course title to retrieve time from string
    sub(course, "", time)
    # get theory info from second line per record
    sub("course:theory:", "", $2)
    # get application info from third line
    sub("course:applicaton:", "", $3)
    # if new course
    if (! (course in header)) {
        # save header information (first words of each line in output)
        header[course] = course
        theory[course] = "theory"
        app[course] = "application"
    }
    # append the relevant info to the output strings
    header[course] = header[course] "," time
    theory[course] = theory[course] "," $2
    app[course] = app[course] "," $3

}
END {
    # now for each course found
    for (key in header) {
        # print the strings constructed
        print header[key]
        print theory[key]
        print app[key]
        print ""
}

Is there anyway to get a ride of these strings STR* and SMTGH* in order to get this output:

carl 1,10:00,14:00
applicaton,halfhour,onehours
theory,geo,programmation

carl 2,10:00,14:00
applicaton,nothing,nothing
theory,history,philosophy

david 1,10:00,14:00
applicaton,onehour,twohours
theory,nothing,nothing

david 2,10:00,14:00
applicaton,twohour,twohours
theory,math,music

IA32 IDT and linux interrupt handler

In the IDT each line has some bits called "DPL" - Descriptor Privileg Level, 0 for kernel and 3 for normal users(maybe there are more levels). I don't understand 2 things:

  1. this is the level required to run the interrupt handler code? or to the trigger the event that leads to it?. because system_call has DPL=3, so in user-mode we can do "int 0x80". but in linux only the kernel handle interrupts, so we can trigger the event but not handle it? even though we have the right CPL.

  2. In linux only the kernel handle interrupts, but when an interrupt(or trap) happens, what get us into the kernel mode?

Sorry for any mistakes, I am new to all this stuff and just trying to learn.

Reading camera input from /dev/video0 in python or c

I want to read from the file /dev/video0 either through c or python,and store the incoming bytes in a different file. Here is my c code:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
    int fd,wfd;
    fd=open("/dev/video0",O_RDONLY);
    wfd=open("image",O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
    if(fd==-1)
        perror("open");
    while(1)
    {
        char buffer[50];
        int rd;
        rd=read(fd,buffer,50);
        write(wfd,buffer,rd);
    }

    return 0;
}

When i run this code and after some time terminate the program nothing happens except a file name "image" is generated which is usual.

This is my python code:

    image=open("/dev/video0","rb")
    image.read()

and this is my error when my run this snippet:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

I want to know how to do this using pure c or python code.Please no external library suggestions.

irssi apt-get not installing

I'm trying to install irssi via apt-get. When i enter sudo apt-get install irssi i get the following error:

Err http://ift.tt/1gRm4rd kali/main libperl5.14 armel 5.14.2-21+deb7u1
  404  Not Found
Get:1 http://ift.tt/1gRm4rd kali/main irssi armel 0.8.15-5 [1,053 kB]
Fetched 1,053 kB in 7s (141 kB/s)                                              
Failed to fetch http://ift.tt/1KipaRQ  404  Not Found
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

when i type irssi in the terminal screen i get -bash: irssi: command not found. How do i correctly install irssi? thanks. when i try sudo apt-get update i get the following error:

W: A error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ift.tt/1nrLYFu kali/updates Release: The following signatures were invalid: KEYEXPIRED 1425567400 KEYEXPIRED 1425567400 KEYEXPIRED 1425567400

W: A error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://http.kali.org kali Release: The following signatures were invalid: KEYEXPIRED 1425567400 KEYEXPIRED 1425567400 KEYEXPIRED 1425567400

W: Failed to fetch http://ift.tt/1rwn4Xr  

W: Failed to fetch http://ift.tt/1rwn6OV  

W: Some index files failed to download. They have been ignored, or old ones used instead.

I'm using kali linux as my os

Decompile ioncube obfuscated PHP code

My test file is:

<?php
echo "Hello";
?>

Now i Encoded with ioncube, it becomes obfuscated.

ioncube.sh -55 test.php -o test_e.php

Whenerver i run php test_e.php > out it print Hello in out file. so it executed somewhere in system and decompile php code in system. is there any way to obtain that decompiled code? I search lots of thing in google like xdebug, parsing, trace, but not working to obtain decompiled php.

Is there a way to rename bulk of files in linux

Is there a command in Shell/Bash or Perl that can rename all the files in a folder.

I am looking for here is in my folder documents with the following naming convention:

smith_welding_<XXXXXX>.jpg

Where XXXXXX is the counter and it is started from 001191 to 001254.jpg

I would like to rename all the files with the above given convention and the counter needs to be started from 000000:

smith_welding_<XXXXXX>.jpg

Is there any command that can help me with the above?

C++ thread attach/dettach segfaults

I use a plugin written in C++ for running queries on MySQL. It's used inside a Xojo (www.xojo.com) made application.

The problem is that if too many queries are executed too often it crashes on linux with a segmentation fault.

The plugin itself works by detaching from the calling thread before executing the query in order to not block the main application etc and then re-attaching once it's done. I think this re-attaching is the problem (gdb debugging in linux seems like this) but due to not having symbols on the Xojo's framework I'm not so sure.

This are the two methods/functions used for detaching and re-attaching

void ReattachCurrentThread(void *token)
{
    static void (*pAttachThread)(void*) = nullptr;
    if (!pAttachThread)
        pAttachThread = (void (*)(void *)) gResolver("_UnsafeAttachCurrentThread");
    if (pAttachThread) pAttachThread( token );
}

void * DetachCurrentThread(void)
{
    static void * (*pDetachThread)(void) = nullptr;
    if (!pDetachThread)
        pDetachThread = (void * (*)(void)) gResolver("_UnsafeDetachCurrentThread");
    if (pDetachThread) return pDetachThread();
    return nullptr;
}

And here is one place where those are called:

REALdbCursor MySQLPerformSelect(MySQLDatabaseData *db, REALstring queryStr)
{
    if (db->fConnection == nullptr) return nullptr;

    if (!LockDatabaseUsage( db )) return nullptr;

    REALstringData stringData;
    if (!REALGetStringData( queryStr, REALGetStringEncoding( queryStr ), &stringData )) return nullptr;

    void *detachToken = DetachCurrentThread();
    int err = mysql_real_query( db->fConnection, (const char *)stringData.data, stringData.length );
    ReattachCurrentThread( detachToken );
    db->CaptureLastError();

    REALDisposeStringData( &stringData );

    REALdbCursor retCursor = nullptr;
    if (0 == err) {
        // Allocate a cursor
        MySQLCursorData *curs = new MySQLCursorData;
        bzero( curs, sizeof( MySQLCursorData ) );

        curs->fCursor = new MySQLCursor( db );

        retCursor = NewDBCursor( curs );
    }

    UnlockDatabaseUsage( db );

    return retCursor;
}

My question is: is there anything wrong with the code above and is it expected to cause a segfault because it's not being careful somehow etc? I'm not a C++ programmer but it seems too blunt in my understanding, like not trying to see if thread is available first etc. Again, I'm not a C++ programmer so all I'm saying may be absurd etc...

The "whole" plugin's code is here: plugin's source

examples of user-space and kernel-space

I was asked :

  • of examples of user-space-threaded-only systems, kernel-space-threaded-only systems.
  • whether Native POSIX Thread Library is considered part of user-space or kernel-space.
  • and if Java threading is done in user-space.

there's a huge amount of information about all these topics, but there doesn't seem to be a direct answer to those specific questions. I hope you could help me.

How can I install fedora via LAN from an existing installed fedora system

I'm already having a system with Fedora 21 installed on it. I want to install the same OS with exact software packages on the other existing system that are interconnected via LAN. How do I do that? Is there any existing solution?

Currently other systems are running windows 7, and we're migrating to Fedora at our infrastructure.

How file system block size works?

All Linux file systems have 4kb block size. Let's say I have 10mb of hard disk storage. That means I have 2560 blocks available and let's say I copied 2560 files each having 1kb of size. Each 1 kb block will occupy 1 block though it is not filling entire block.

So my entire disk is now filled but still I have 2560x3kb of free space. If I want to store another file of say 1mb will the file system allow me to store? Will it write in the free space left in the individual blocks? Is there any concept addressing this problem?

I would appreciate some clarification. Thanks in advance.

join two files based

I have two files, I want to join them.

$cat t1
 1 1.2
 2 2.2
$cat t2
 1
 2
 1

I want to have the blow output

$cat joind.txt
 1 1.2
 2 2.2
 1 1.2

but when I use join command the third command not exist.

Thanks

Speed of Azure File Service

Reading the documentation regarding Azure File Service I expected an easy and fast way to mount more space to my virtual Azure machine. However, after mounting a file service on my ubuntu machine (done exactly as explained on this page) I get super slow read/write speeds to this mount.

To give an example, downloading a 1000mb.bin file to my local disk:

sander@sanderpihost:~$ wget http://ift.tt/1rgWNKC
--2015-06-28 08:34:38--  http://ift.tt/1rgWNKC
Resolving www.colocenter.nl (www.colocenter.nl)... 5.39.184.5
Connecting to www.colocenter.nl (www.colocenter.nl)|5.39.184.5|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1048576000 (1000M) [application/octet-stream]
Saving to: ‘1000mb.bin’

12% [==========>                                                                                ] 134,018,596 37.3MB/s  eta 25s  

And to my mounted folder:

sander@sanderpihost:~/myazuredisk/Incomplete$ wget http://ift.tt/1rgWNKC
--2015-06-28 08:31:39--  http://ift.tt/1rgWNKC
Resolving www.colocenter.nl (www.colocenter.nl)... 5.39.184.5
Connecting to www.colocenter.nl (www.colocenter.nl)|5.39.184.5|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1048576000 (1000M) [application/octet-stream]
Saving to: ‘1000mb.bin.1’

 0% [                                                                                           ] 3,768,320    466KB/s  eta 34m 8s 

Is this expected? Is there any reason why this is soo slow? I would expect to hit much higher speeds than this meagre ±500KB/s I seem to get right now.

CTRL-V mapped to paste instead block visual mode in Vim on Elementary OS (linux)

I have just started using Vim on a Linux distribution -- Elementary OS. In Vim, CTRL-V appears to be mapped to paste instead of taking me to block visual mode. How do I reverse this? I'm pretty sure I didn't configure vim to behave this way and from what I've read so far this should only happen in MS Windows.

Channels missing in compiled kernel in kvm

I have a ubuntu in virtual machine using libvirt. I configured my guest to create pipe and unix channels for trace-virtio purpose:

<channel type='unix'>
  <source mode='connect' path='path/to/socket'/>
  <target type='virtio' name='unix-name'/>
  <address type='virtio-serial' controller='0' bus='0' port='1'/>
</channel>
<channel type='pipe'>
  <source path='path/to/pipe'/>
  <target type='virtio' name='pipe-name'/>
  <address type='virtio-serial' controller='0' bus='0' port='2'/>
</channel>

Everything works fine in my guest and I have my channel in /dev inside my virtual machine and I can send data to host using these channels. But when I compile kernel and install it inside my vm and select it from grub, these channels disappear. When I reboot and select the original kernel, it has the channels and works correctly. How can I tell kvm to create channels in compiled kernel inside my virtual machine?

how to use xrandr from script?

I am trying to use bash script to add resolution through xrandr and i keep getting error, here is my script:

#!/bin/bash

out=`cvt 1500 800`
out=`echo $out | sed 's/\(.*\)MHz\(.*\)/\2/g'`
input=`echo $out | sed 's/Modeline//g'`
#echo $input
xrandr --newmode $input
input2=`echo $out | cut -d\" -f2`
#echo $input2
xrandr --addmode VNC-0 $input2

when trying to do this manually it works fine. i keep getting from the script cannot find mode... , but when i do xrandr, i do see the new mode

sending signal from parent to child

I am using this tutorial from website http://ift.tt/1fXCwYE and trying to understand why signal is not recieved by child?

here is the code:

 #include <stdio.h>  
 #include <signal.h>
 #include<stdlib.h>  
 void sighup(); /* routines child will call upon sigtrap */  
 void sigint();  
 void sigquit();  
 void main()  
 { int pid;  
  /* get child process */  
   if ((pid = fork()) < 0) {  
     perror("fork");  
     exit(1);  
   }  
   if (pid == 0)  
    { /* child */  
     signal(SIGHUP,sighup); /* set function calls */  
     signal(SIGINT,sigint);  
     signal(SIGQUIT, sigquit);  
     for(;;); /* loop for ever */  
    }  
  else /* parent */  
    { /* pid hold id of child */  
     printf("\nPARENT: sending SIGHUP\n\n");  
     kill(pid,SIGHUP);  
     sleep(3); /* pause for 3 secs */  
     printf("\nPARENT: sending SIGINT\n\n");  
     kill(pid,SIGINT);  
     sleep(3); /* pause for 3 secs */  
     printf("\nPARENT: sending SIGQUIT\n\n");  
     kill(pid,SIGQUIT);  
     sleep(3);  
    }  
 }  
 void sighup()  
 { signal(SIGHUP,sighup); /* reset signal */  
   printf("CHILD: I have received a SIGHUP\n");  
 }  
 void sigint()  
 { signal(SIGINT,sigint); /* reset signal */  
   printf("CHILD: I have received a SIGINT\n");  
 }  
 void sigquit()  
 { printf("My DADDY has Killed me!!!\n");  
  exit(0);  
 }  

samedi 27 juin 2015

PulledPork can't locate Snort binary

I have a problem there. I've installed Snort on my CentOS 7 server and wanted to use PulledPork as a source for rules. Pretty basic stuff...

Configured PulledPork conf:

# What path you want the .so files to actually go to *i.e. where is it
# defined in your snort.conf, needs a trailing slash
sorule_path=/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/

# Path to the snort binary, we need this to generate the stub files
snort_path=/usr/sbin/snort/

# We need to know where your snort.conf file lives so that we can
# generate the stub files
config_path=/etc/snort/snort.conf

Then I ran my PulledPork script:

./pulledpork.pl -c /etc/pulledpork/etc/pulledpork.conf

It gave me an error:

The specified Snort binary does not exist!
Please correct the value or specify the FULL rules tarball name in the pulledpork.conf!
 at ./pulledpork.pl line 1816.

I tried to install different snort (from the snort binaries section:snort-openappid-2.9.7.3-1.centos7.x86_64.rpm), changed pullerpork conf file. Nothing changed. Couldn't google it as well, so now I am here seeking for help. Thank you!

Here are my snort files locations:

/home/aivanov/snort-2.9.7.3-1.centos7.x86_64.rpm
/home/aivanov/snort-openappid-2.9.7.3-1.centos7.x86_64.rpm
/home/aivanov/snort-2.9.7.3-1.src.rpm
/home/aivanov/snort-openappid-2.9.7.3-1.centos7.x86_64.rpm.1
/run/lock/subsys/snort
/sys/fs/cgroup/systemd/system.slice/snortd.service
/sys/fs/cgroup/systemd/system.slice/snortd.service/cgroup.clone_children
/sys/fs/cgroup/systemd/system.slice/snortd.service/cgroup.event_control
/sys/fs/cgroup/systemd/system.slice/snortd.service/notify_on_release
/sys/fs/cgroup/systemd/system.slice/snortd.service/cgroup.procs
/sys/fs/cgroup/systemd/system.slice/snortd.service/tasks
/etc/selinux/targeted/modules/active/modules/snort.pp
/etc/logrotate.d/snort
/etc/sysconfig/snort
/etc/rc.d/init.d/snortd.rpmsave
/etc/rc.d/init.d/snortd
/etc/rc.d/rc0.d/K60snortd
/etc/rc.d/rc1.d/K60snortd
/etc/rc.d/rc2.d/S40snortd
/etc/rc.d/rc3.d/S40snortd
/etc/rc.d/rc4.d/S40snortd
/etc/rc.d/rc5.d/S40snortd
/etc/rc.d/rc6.d/K60snortd
/etc/snort
/etc/snort/rules
/etc/snort/rules/snort-2.9.7.3-1.src.rpm
/etc/snort/rules/snort-2.9.7.3-1.centos7.x86_64.rpm
/etc/snort/rules/snort-openappid-2.9.7.3-1.centos7.x86_64.rpm
/etc/snort/snort.conf.rpmsave
/etc/snort/classification.config
/etc/snort/gen-msg.map
/etc/snort/reference.config
/etc/snort/snort.conf
/etc/snort/threshold.conf
/etc/snort/unicode.map
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/from_repo
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/reason
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/releasever
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/var_uuid
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/var_infra
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/command_line
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/checksum_type
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/checksum_data
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/from_repo_revision
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/from_repo_timestamp
/var/lib/yum/yumdb/s/bbf08ea2dbaff9bcfb7095d8dfcf486e694aa1cf-snort-openappid-2.9.7.3-1-x86_64/installed_by
/var/log/snort
/var/spool/mail/snort
/var/tmp/yum-root-3bDmpR/snort-2.9.7.3-1.centos7.x86_64.rpm
/usr/bin/snort_control
/usr/sbin/snort
/usr/sbin/snort-openappid
/usr/lib64/snort-2.9.7.3_dynamicengine
/usr/lib64/snort-2.9.7.3_dynamicengine/libsf_engine.so
/usr/lib64/snort-2.9.7.3_dynamicengine/libsf_engine.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_appid_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_appid_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_appid_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dce2_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dce2_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dce2_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dnp3_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dnp3_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dnp3_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dns_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dns_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_dns_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ftptelnet_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ftptelnet_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssl_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ftptelnet_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_gtp_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_gtp_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_gtp_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_imap_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_imap_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_imap_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_modbus_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_modbus_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_modbus_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_pop_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_pop_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_pop_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_reputation_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssl_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_reputation_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssl_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_reputation_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sdf_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sdf_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sdf_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sip_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sip_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_sip_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_smtp_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_smtp_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_smtp_preproc.so.0.0.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssh_preproc.so
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssh_preproc.so.0
/usr/lib64/snort-2.9.7.3_dynamicpreprocessor/libsf_ssh_preproc.so.0.0.0
/usr/share/doc/snort-2.9.7.3
/usr/share/doc/snort-2.9.7.3/AUTHORS
/usr/share/doc/snort-2.9.7.3/BUGS
/usr/share/doc/snort-2.9.7.3/CREDITS
/usr/share/doc/snort-2.9.7.3/INSTALL
/usr/share/doc/snort-2.9.7.3/NEWS
/usr/share/doc/snort-2.9.7.3/README.unified2
/usr/share/doc/snort-2.9.7.3/OpenDetectorDeveloperGuide.pdf
/usr/share/doc/snort-2.9.7.3/PROBLEMS
/usr/share/doc/snort-2.9.7.3/README
/usr/share/doc/snort-2.9.7.3/README.GTP
/usr/share/doc/snort-2.9.7.3/WISHLIST
/usr/share/doc/snort-2.9.7.3/README.PLUGINS
/usr/share/doc/snort-2.9.7.3/generators
/usr/share/doc/snort-2.9.7.3/README.PerfProfiling
/usr/share/doc/snort-2.9.7.3/README.SMTP
/usr/share/doc/snort-2.9.7.3/snort_manual.tex
/usr/share/doc/snort-2.9.7.3/README.UNSOCK
/usr/share/doc/snort-2.9.7.3/README.WIN32
/usr/share/doc/snort-2.9.7.3/snort_manual.pdf
/usr/share/doc/snort-2.9.7.3/README.active
/usr/share/doc/snort-2.9.7.3/README.alert_order
/usr/share/doc/snort-2.9.7.3/README.appid
/usr/share/doc/snort-2.9.7.3/README.asn1
/usr/share/doc/snort-2.9.7.3/README.counts
/usr/share/doc/snort-2.9.7.3/README.csv
/usr/share/doc/snort-2.9.7.3/README.daq
/usr/share/doc/snort-2.9.7.3/README.dcerpc2
/usr/share/doc/snort-2.9.7.3/README.decode
/usr/share/doc/snort-2.9.7.3/README.variables
/usr/share/doc/snort-2.9.7.3/README.decoder_preproc_rules
/usr/share/doc/snort-2.9.7.3/README.dnp3
/usr/share/doc/snort-2.9.7.3/README.dns
/usr/share/doc/snort-2.9.7.3/README.event_queue
/usr/share/doc/snort-2.9.7.3/README.file
/usr/share/doc/snort-2.9.7.3/README.file_ips
/usr/share/doc/snort-2.9.7.3/README.filters
/usr/share/doc/snort-2.9.7.3/README.flowbits
/usr/share/doc/snort-2.9.7.3/README.frag3
/usr/share/doc/snort-2.9.7.3/README.ftptelnet
/usr/share/doc/snort-2.9.7.3/README.gre
/usr/share/doc/snort-2.9.7.3/README.ha
/usr/share/doc/snort-2.9.7.3/README.http_inspect
/usr/share/doc/snort-2.9.7.3/README.imap
/usr/share/doc/snort-2.9.7.3/README.ipip
/usr/share/doc/snort-2.9.7.3/README.ipv6
/usr/share/doc/snort-2.9.7.3/README.modbus
/usr/share/doc/snort-2.9.7.3/TODO
/usr/share/doc/snort-2.9.7.3/README.multipleconfigs
/usr/share/doc/snort-2.9.7.3/README.normalize
/usr/share/doc/snort-2.9.7.3/README.pcap_readmode
/usr/share/doc/snort-2.9.7.3/README.pop
/usr/share/doc/snort-2.9.7.3/README.ppm
/usr/share/doc/snort-2.9.7.3/README.reload
/usr/share/doc/snort-2.9.7.3/README.reputation
/usr/share/doc/snort-2.9.7.3/USAGE
/usr/share/doc/snort-2.9.7.3/README.sensitive_data
/usr/share/doc/snort-2.9.7.3/README.sfportscan
/usr/share/doc/snort-2.9.7.3/README.sip
/usr/share/doc/snort-2.9.7.3/README.ssh
/usr/share/doc/snort-2.9.7.3/README.ssl
/usr/share/doc/snort-2.9.7.3/README.stream5
/usr/share/doc/snort-2.9.7.3/README.tag
/usr/share/doc/snort-2.9.7.3/README.thresholding
/usr/share/man/man8/snort.8.gz
/usr/local/lib/snort_dynamicrules

Thanks for your help!

How to prompt user to change password with a certain complexity in Ubuntu?

I have to change the passwords of about 100 computers connected in a network all of which are running either Linux Mint or Ubuntu 14.04. How would I approach this with the help of a script and a server pushing it to the computers?

Linux Kernel init fails in encrypted filesystem

I am trying to make a linux os with encrypted filesystem for the whole OS (boot,kernel,root,...)

I modified EXT4 filesystem's read and write functions. after running a lot of tests everything read and write work fine.

EDIT:

my change is a simple XOR to file contents.

my tests include reading/writing text files, tar archive creation/deletion, sound and videofile creation/copying/deletion and some stress tests.

next step was to boot a simple linux based OS on this encrypted filesystem, I modified GRUB 2 bootloader so it cat boot the kernel from encrypted disk. then I faced this problem:

  • grub can load linux kernel and kernel boots, but when it tries to run the init proccess I get kernel panic with the message: "init Not tained".

I can see from previous messages that filesystem is loaded by kernel and it is actually reading init file but refuses to run init.

my question is: is kernel reading init file in any other way than using standard read system call? is there something I am doing wrong here?

Any help would be greatly appreciated

EDIT:

now the question is:

how can I decrypt the data that kernel uses by mapping memory?

browse ftp file in firefox browser linux

I want to set users upload file to my server in browser. I use <input type="file" /> for upload file.

some of my users want to upload file from ftp server to my server. in windows this users can set ftp URL in address bar and select file to upload. but Linux users can't upload file from ftp with file browse.

so how can my Linux users upload files from ftp to my server with input HTML tag? or how can my Linux users access ftp from file browser? Not that my users use Firefox.

IPv6: Does DAD happens for IPs that do not belong to link-local address family too?

As per the RFC 4862, for IPv6, Duplicate Address Detection (DAD) happens for every self-assigned link-local IP? However, it is unclear if the term "link-local" there refers only to the "link-local family/type" of addresses, or "any" IP address that is present a link/one-hop away (in other words: in a LAN).

If a static IPv6 IP is assigned, to a node in LAN, that does not belong to the link-local type (but rather global type), then does DAD happen for such an IP too?

If this is implementation-dependent, what is the behavior in Linux?