Swift - Updating Tableview after saving Core data

I have a mainVC where i perform a fetch request.
I then pass the fetched data to a second view controller (HomeVc) and then to  third (MyparamsVc)
In the third VC i have a tableView Which list all the parameters which have a relation one-to-may with the entity i fetched in the main VC

In a fourth View controller i add the new parameters through a form (addParamVC). After saving i dismiss the controller and pop the previous one (MyparamsVc).
My problem is that the tableview is not updating with the new data unless i go back to my HomeVC and then again into the MyparamsVC

I have implemented the func controllerDidChange an Object but since i'm not performing the fetch in the same controller the function is never called... How can i Update the tableview with new data?

MainVc fetchRequest:

 var controller: NSFetchedResultsController<SwimminPool>!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    attemptFetch()

}
func attemptFetch() {

    let fetchRequest: NSFetchRequest<SwimminPool> = SwimminPool.fetchRequest()
    let dataSort = NSSortDescriptor(key: "poolCreatedAt", ascending: false)
    fetchRequest.sortDescriptors = [dataSort]

     let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }

}

addParamVC saving func:

var swimmingPoolToConnect: SwimmingPool!
var parameterToEdit: Parameter?

@IBAction func saveBtnPressed(_ sender: Any) {

    var parameter: Parameter

    if parameterToEdit == nil {
        parameter = Parameter(context:context)
    } else {
        parameter = parameterToEdit!
    }

    if let pH = phTextField.text?.characters.split(separator: ",").joined(separator: ".") {
        if let pHnoComma =  Double(String(pH)) {
        parameter.paramPH = pHnoComma
        }
    }
  parameter.createdAt = Date()

    swimmingPoolToConnect.addToParameters(parameter)

    ad.saveContext()
    self.presentingViewController?.dismiss(animated: true, completion: nil)
}

MyparamsVC:

 var parameters = [Parameter]()
var swimmingPool: SwimmingPool! {
    didSet {
        parameters = (swimmingPool.parameters?.allObjects as! [Parameter]).sorted(by: {$0.createdAt! > $1.createdAt!})
    }
}

var controller: NSFetchedResultsController<Parameter>?

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ParamCell", for: indexPath) as! ParamCell
    configureCell(cell: cell, indexPath: indexPath)
    return cell
}

 func configureCell(cell: ParamCell, indexPath: IndexPath) {

    let param = parameters[indexPath.row]
    cell.configureCell(parameter: param)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

  let  parameterToPass = parameters[indexPath.row]
        DispatchQueue.main.async { () -> Void in
            self.performSegue(withIdentifier: "MyParameterDetail", sender: parameterToPass)
        }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return parameters.count
   }
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

  //Never enter these func

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

    switch(type){
    case.insert:
        if let indexPath = newIndexPath{
            tableView.insertRows(at: [indexPath], with: .fade)

        }

    case.delete:
        if let indexPath = indexPath{
            tableView.deleteRows(at: [indexPath], with: .fade)
        }

    case.update:
        if let indexPath = indexPath{
            let cell = tableView.cellForRow(at: indexPath) as! ParamCell
            configureCell(cell: cell, indexPath: indexPath)
        }

    case.move:
        if let indexPath = indexPath{
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
        if let indexPath = newIndexPath{
            tableView.insertRows(at: [indexPath], with: .fade)
        }
    }
}


cannot get string inside an element - object literal javascript

I'm trying to to get the strings of two divs .class-date and .class-time  but i'm getting an Uncaught TypeError "e.siblings is not a function". This probably a rudimentary mistake but I can't work it out. Any pointers in the right direction would be greatly appreciated .

var Cc = {
    init: function() {
        Cc.bindEvent();
    },
    bindEvent: function() {
        $('.book-class').on("click", function() {
            let selectedclass = this;
            Cc.parseClass(selectedclass);
        });
    },
    parseClass: function(selectedclass) {
        let classdate = selectedclass.siblings('.class-date').text();
        let classtime = selectedclass.siblings('.class-time').text();
        console.log(classdate, classtime);
    }
}

jQuery(document).ready(function($) {
    Cc.init();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class">
    <div class="class-date">Thursday, 1 January</div>
    <div class="class-time">18:00 — 20:00</div>
    <div class="book-class">Book Class</div>
</div>


Extract lines corresponding to the minimum value in the last column

I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111

I could use awk to get the least value as "7" from the last column using the code as below:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

and to print only the values in square brackets [] buy using the awk code as below:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.


Help with creating a scheduled task

I came across this code which should be able to compare my PC time with the time stored in theTime; however, I can't get it to work. Can anybody help?

dim theTime as datetime

theTime = CDate(txtTime.Text)

if theTime.hour = now.hour and theTime.minute = now.minute then
'shut down code
System.Diagnostics.Process.Start("Shutdown.exe", "-s -t 0")
end if


Linux Q: Cannot access to the file. No permission. Although [-rw-rw-rw]

I'm using CentOS 6.5

User : Erik

I cannot access to the specific file although permission is [-rw-rw-rw].

Why this happening.

State:

--- Parent Directory ---

  Dir Name : Source

  Permission : [dr-r-x-r--] Owner : Erik

--- Source File List ---

  header.php    Erik [-rw-rw-rw-] : Can read but cannot edit file.

  footer.php    Erik [-rw-rw-rw-] : Can read but cannot edit file.

  banner.php    Erik [-rw-rw-rw-] : Can read and edit.

  customer.php  Erik [-rw-rw-rw-] : Can read and edit.

  list.php      Erik [-rw-rw-rw-] : Can read and edit.

--- Result of ls -alp

  drwxr-xr-x.  2 Erik Erik 4096 2017-03-15 11:33 ./

  drwxr-xr-x. 14 Erik Erik 4096 2017-03-15 11:30 ../

  -rw-rw-rw-.  1 Erik Erik 1102 2017-10-24 23:07 header.php

  -rw-rw-rw-.  1 Erik Erik 680 2015-01-19 13:01 footer.php

  -rw-rw-rw-.  1 Erik Erik 1449 2015-01-23 09:42 banner.php

  -rw-rw-rw-.  1 Erik Erik 953 2014-12-03 09:31 customer.php

  -rw-rw-rw-.  1 Erik Erik 810 2014-12-03 09:31 list.php

I can't understand why I can't edit the header.php and footer.php althogh I'm Erik with permission -rw-rw-rw.

Is there any way to edit header.php & footer.php file avoid to change permission of Parent Directory.
Someone please help me. This is very important to me.

Thank you in advance.


how to allow only one vote for a rating system

guys i have made a jquery and css based star rating system. now i cant really think of way as how to save the user vote to database. and most importantly how to limit one user only to one vote.

since the number of visitors in the site is huge, i cant afford saving each user's ip to the database. and moreover i don't think it works good because even my ip address itself is dynamic. every time i disconnect and reconnect my internet my ip changes and i am able to vote again. so i don't think this will work.

this is what i have thought about saving the votes to the database:
ill just save the number of votes a page has received and ill save the total rating of the page.

and ill divide the rating points with number of votes. so it will give me the average rating. right?

but i can think of no way to limit one user to one vote. please help.


Failure when Simplesamlphp is behind load balancer

We use simplesamlphp as a service provider. We've integrated with a number of Idp's.  Everything works fine.

Now we want to change our server architecture to load balancer -> webserver -> database server.  The problem comes up when we put the load balancer in front of the webserver. The idp's get an error.

The load balancer terminates https, which I believe is where the problem is happening.  So when the load balancer sends the request to the webserver it is a regular http request.

When I log the initial happenings I get

I'm gonna simplify the xml a bit and put the parts that were different

with load balancer

Session: 'idp-name' not valid because we are not authenticated.
Saved state: '_somelongstringofnumbersandletters'
Sending SAML 2 AuthnRequest to '{{their info}}'
Sending message:
    <samlp:AuthnRequest ... AssertionConsumerServiceURL="http://{{our-info}}">
        <saml:Issuer>http://{{our-info}}</saml:Issuer>
        <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" AllowCreate="true"/>
    </samlp:AuthnRequest>

So above the only parts that are different between pointing to load balancer and webserver is the http and https, respectively.

Wasn't sure if there was a way to have simplesamlphp just return https. Or will it always check the current state of the request and assume http.

Just to make sure I'm giving all the data.  The process is initialized by the SP. So they just go to a url like https://oursite.com/idp-name.  And we are always using https.

Let me know if I need to clarify something.

UPDATE

We solved the problem by NOT terminating the HTTPS request at the load balancer, and allowing the request to pass through to the servers.  So our SSL certificates are directly on our Web servers and not the load balancer.

I couldn't get the solution given to work, but that could just be my own fault.  We needed a solution quick, and not decrypting SSL on the load balancer was the easiest way.


Warning message: In curlOptions: Duplicated curl options

I am working on an R script that will fetch posts from twitter. I've noticed that everytime I run below statements:

l_get <- GET( l_twitterQuery, config(httpheader = c("Authorization" = l_token)))

l_post   <- POST( url    = l_oAuthUrl
                , config( httpheader = c( "Authorization" = paste("Basic", l_encodCons)
                                        , "Content-Type"  = l_postContentType ))
                , body   = l_postBody
                , encode = l_encode
                );

Below warning message is displayed:

Warning message:
In curlOptions(..., .opts = .opts) :
  Duplicated curl options: proxyport, proxyuserpwd, proxy

I haven't found any good information on the web to solve this? Do I need to modify the httpheader only once in the set_config statement? Please find my script below:

Code:

###########################################################
#
# Libraries
#
###########################################################

library(httr)
library(jsonlite)
library(RCurl)
library(RJSONIO)

###########################################################
#
# Variables
#
###########################################################

# Proxy Variables for VPN
#l_proxyUrl    <- "XXXXXXXXXXXXXXX
#l_proxyPort   <- 80;

# Access Key , Tokens, POST, GETt variables
l_consKey     <- "YVY6KPUyNIhKLpz0Y66CJKssr";
l_consSecret  <- "noVJNzneZMuWq4uJSnX70Y20FAF2eu0gL42yhz9uq6xNEGlAiB";
l_cons        <- paste(l_consKey, l_consSecret, sep = ":");
l_encodCons   <- c()
l_token       <- c()
l_post        <- c()
l_get         <- c()

l_oAuthUrl    <- "https://api.twitter.com/oauth2/token";
l_postBody    <- "grant_type=client_credentials";
l_encode      <- "multipart";

l_postContentType <- "application/x-www-form-urlencoded;charset=UTF-8";

# Twitter Variables
l_twitterUrl      <- "https://api.twitter.com/1.1/search/tweets.json"
l_queryParams     <- "?q=%23Oracle&result_type=recent&count=100"
l_twitterQuery    <- c()

###########################################################
#
# Body
#
###########################################################

#Configure Proxy
#set_config( use_proxy( url  = l_proxyUrl, port = l_proxyPort ))

#Encode the consumer key and secret.
l_encodCons <- base64( txt = l_cons );

#Request
l_post   <- POST( url    = l_oAuthUrl
                , config( httpheader = c( "Authorization" = paste("Basic", l_encodCons)
                                        , "Content-Type"  = l_postContentType ))
                , body   = l_postBody
                , encode = l_encode
                );

l_token  <- paste("Bearer", content(l_post)$access_token)

i <- 0

while ( TRUE )
{

  l_twitterQuery <- paste(l_twitterUrl, l_queryParams, sep ="")
  l_get          <- GET( l_twitterQuery, config(httpheader = c("Authorization" = l_token)))
  l_results      <- content( l_get, as = "text")
  l_tweets       <- fromJSON(l_results)

  i <- i + 1
  x <- names( l_tweets )[1]

  cat( sprintf( "System Time %s \t Iteration %s \t Names: %s \t Time Taken: %s \t Query: %s \n", Sys.time(), i, x, l_tweets$search_metadata$completed_in, l_twitterQuery ))

  l_queryParams  <- l_tweets$search_metadata$next_results

}

SessionInfo:

> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=Spanish_Mexico.1252  LC_CTYPE=Spanish_Mexico.1252    LC_MONETARY=Spanish_Mexico.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Mexico.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RJSONIO_1.3-0   jsonlite_0.9.14 httr_0.5        RCurl_1.95-4.4  bitops_1.0-6

loaded via a namespace (and not attached):
[1] stringr_0.6.2 tools_3.1.0


In mongoDB can I efficiently group documents into groups of a set size?

I need to group data into subgroups of a set size.  Like if there are 6 records, ordered by date.

[1,2,3,4,5,6]

and I have a subgroup size of 2.  I would end up with an array(length of 3) of arrays(each length 2):

[[1,2],[3,4],[5,6]]

Nothing about the record factors into the grouping, just how they are ordered over all and the subgroup size.

Does the aggregation framework have something that would help with this?


How to add more button at the end of UILabel?

I have been working on this for a long time.
I need to expand and collapse the UILabel text on click of a button located at the end of text of UILabel.

Thinks I have tried
I have use VSWordDetector to detect which word of UILabel get tapped but it not gave correct word tapped.


Set layout background color using SMYK Seekbars

Basically, I made 3 Seekbars with max value of 255 (RGB values) and with this method:

private void updateBackground() {

    seekR = redSeekBar.getProgress();
    seekG = greenSeekBar.getProgress();
    seekB = blueSeekBar.getProgress();
    myLayout.setBackgroundColor(0xff000000
            + seekR * 0x10000
            + seekG * 0x100
            + seekB
    );
}

then used in SeekBar.OnSeekBarChangeListener I was able to change my background dynamically using Red, Green and Blue values and it works perfectly fine.

Anyone having any idea how can I change this to 4 Seekbars, but using a CMYK method, instead of RGB..?


How do I make and if else statement for individual radio buttons?

I have this code that creates radio buttons, can someone show me the code to select each button separately when a radio button is check on an If Else statement when I click a button please?. How can I make the text of each radio button different?

private void createButtons()
        {
            flowLayoutPanel1.Controls.Clear();
            for(int i = 0;i <10;i++)
            {
                RadioButton b = new RadioButton();
                b.Name = i.ToString();
                b.Text = "radiobutton" + i.ToString();
                b.AutoSize = true;
                flowLayoutPanel1.Controls.Add(b);

            }
        }


How to change style of HTML element depending on another elements style?

In my Web application i am changing style of HTML Element using javascript.

See be below code,

function layout() {
    if(document.getElementById('sh1').getAttribute('src') == "abc.png") {
        document.getElementById("sh1").style.display="none";
    } else {
        document.getElementById("sh1").style.display="block";
    }
}

and HTML is :

<img id="sh1" src="abc.png" />

Now i want that if img elements style is display:none; then below Elements

<p id="Text1">Name<br />description</p>

style should also get changed to display:none; and if img elements style is display:block; then above Elements style should also get changed to display:block; automatically.

how this can get achieved?


Grid inside a scrollviewer with multiple user controls inside

I am new to WPF and xaml and I have a problem with my apps UI.

I am using this xaml code:

<ScrollViewer HorizontalAlignment="Left" Margin="252,12,0,0" Name="captchaControlsScrollableContainer" VerticalAlignment="Top">
    <Grid Name="captchaControls" Width="339" Height="286">
    </Grid>
</ScrollViewer>

And this code behind code that populates the grid:

captchaControls.Children.Add(new Captcha(data));

which is called more than one time

My problem is that only the first user control app apperas in the grid although in the debugger captchaControls.Children.Count is the right size and the scrollviewer's scrollbar is disabled.

Does anyone have any idea what I am doing wrong? Thank you in advance.


How to retrieve history of pubnub chat in xamarin.forms

I am trying for chat application in xamarin.forms using pubnub,i successfully did sending and retrieving messages,but the problem is when i closes the app and reopen is iam not getting previous messages.

 {
        PNConfiguration config = new PNConfiguration();
        // never share your keys in public, especially pub-key
        config.PublishKey = "pub-c-6de-redacted";
        config.SubscribeKey = "sub-c-85f-redacted";
        config.Uuid = username;

        config.LogVerbosity = PNLogVerbosity.BODY;
        config.PubnubLog = new Logger();
        _pubnub = new Pubnub(config);

        _pubnub.AddListener(this);

        _pubnub.Subscribe<string>()
            .Channels(new string[] { "my_channel1" })
            .WithPresence()
            .Execute();
        _pubnub.HereNow()
            .Channels(new string[]
            {
                "my_channel1"
            })
            .IncludeUUIDs(true)
            .Async(new HereNowResult());

        _pubnub.History()
            .Channel("my_channel1")
            .IncludeTimetoken(true)
            .Count(100)
            .Async(new DemoHistoryResult());

and my publish method is:

public void PublishMessage(string text,string selectednametoChat)
    {
        _pubnub.Publish()
            .Channel("my_channel1")
            .ShouldStore(true)
            .Message(text)
            .UsePOST(true)
            .Async(new PubnubResult());

    }`

Here is method to store previous messages
[I think you mean retrieve previous messages]

 public class DemoHistoryResult : PNCallback<PNHistoryResult>
{
    public static ChatWindowViewModel ChatWindowViewModel { get; set; }

    public override void OnResponse(PNHistoryResult result, PNStatus status)
    {
        try
        {
            if (result.Messages != null && result.Messages.Count > 0)
            {
                foreach (var message in result.Messages)
                {
                    ChatWindowViewModel.MessagesList.Add(message.Entry.ToString());
                }
            }
        }
        catch (Exception ex)
        {

        }

    }

how to get the history to the MessagesList.


AreEqual comparing objects with ToString

I'm using Assert.AreEqual to compare two objects.  The objects are two different instances of the same class and there is a ToString method in that class.  When I call AreEqual I can see from the debugger that the ToString method gets called (once for each of the two variables).

The ToString method returns exactly the same string in each case but still for some reason the AreEqual method returns false.

Why might this be?

The error is

Additional information:   Expected: <DeliveryTag: 0, RoutingKey: , Body: test, Headers: test: test, ContentType: text/plain>

  But was:  <DeliveryTag: 0, RoutingKey: , Body: test, Headers: test: test, ContentType: text/plain>


WebMaping using Flex 3 (GeoServer, PostgreSQL, PostGIS, php)

Any idea of WebMaping (Displaying a GeoSpatial Map) using flex 3.
I have few vector layers and also a raster layer, and i had already build a Geodatabase using PostGIS. I am using GeoServer as map engine.
  If any one have idea please reply me.

Thans in advance..>>>


Pass List of Checkboxes into View and Pull out IENumerable

I have a list of items that will be associated to a user. It's a one-to-many relationship. I want the entire list of items passed into the view so that they can choose from ones that are not associated to them yet (and also see those that are already associated). I want to create checkboxes from these. I then want to send the selected ones back into the controller to be associated. How can I pass in the list of all of them, including those that aren't yet associated, and reliably pass them back in to be associated?

Here's what I tried first, but it's clear this won't work as I'm basing the inputs off the items passed in via the AllItems collection, which has no connection to the Items on the user itself.

<div id="item-list">
    @foreach (var item in Model.AllItems)
    {
        <div class="ui field">
            <div class="ui toggle checkbox">
                <input type="checkbox" id="item-@item.ItemID" name="Items" value="@item.Active" />
                <label for="item-@item.ItemID">@item.ItemName</label>
            </div>
        </div>
    }
</div>


Program to reverse an inputted chain of characters

I need to make a program that lets the user enter a string character by character and then print it in reverse. space means end of input (space should be entered by user.)

section .bss
c : resb 1
section .text
global _start
_start :
mov ecx, 0
mov edx, 0
saisie :
    push ecx
    push edx
    mov eax,3
    mov ebx,0
    mov ecx,c
    mov edx,1
    int 80h
    mov ecx,[c] ; put the entered value in ecx
    cmp ecx,32  ; compare ecx with space.
    je espace   ;
    pop edx
    inc edx
    pop ecx
    jmp saisie
espace :
    pop edx
    cmp edx,0 ; if counter is 0 we exit if not we print what's in stack.
    je fin
    mov eax,4
    mov ebx,1
    pop ecx
    int 80h
    dec edx
    jmp espace
fin :
mov eax, 1
mov ebx, 0
int 80h

When I enter characters and space at the end, the program just exits without error like it has done its job.

Can anyone explain this behavior and how I can correct it?


Static initializer in Python

My question is similar to Is there a static constructor or static initializer in Python?. However I still don't quite follow how to implement a static constructor as I would in Java:

public class TestBuilder {
    private String uid;
    private String name;
    private double speed;

    public static final TestBuilder SLEEPY;
    public static final TestBuilder SPEEDY;

    static {
        SLEEPY = new TestBuilder("1", "slow test", 500.00);
        SPEEDY = new TestBuilder("2", "fast test", 2000.00);
    }

    private TestBuilder(String uid, String name, double speed){
        this.uid = uid;
        this.name = name;
        this.speed = speed;
    }

    public double getSpeed(){
        return speed;
    }

    public String getUid() {
        return uid;
    }

    public String getName() {
        return name;
    }

In java from another class I could then call TestBuilder.SLEEPY to access a populated class.

In python I have tried:

class TestBuilder:
    uid = str()
    name = str()
    speed = float()

    def __init__(self, uid, name, speed):
        self.uid = uid
        self.name = name
        self.speed = speed

    def lookupByName(self, name):
        result = None
        members = [attr for attr in dir(TestBuilder()) if not callable(attr) and not   attr.startswith("__")]
        for testbuilder in members:
        if testbuilder.name == name:
            result = testbuilder.uid
            break
        return result

TestBuilder.SLEEPY = TestBuilder("1","slow test", 500.0)
TestBuilder.SPEEDY = TestBuilder("2","fast test", 2000.0)

Then in another module I tried:

from examples.testbuilder import TestBuilder
import unittest

class Tester(unittest.TestCase):

    def test_builder(self):
        dummy = TestBuilder
        ref = dummy.SPEEDY
        sleepyid = dummy.lookupByName("slow test")
        self.assertTrue(dummy.SPEEDY.__str__() == ref.__str__())
        self.assertEqual(1, sleepyid)

However I get a "TypeError: lookupByName() missing 1 required positional argument: 'name'" on the dummy.lookupByName("slow test") call and am not sure why.
Does this look like a 'pythonic' way to generate similar functionality to a Java static initializer? Are there alternatives?


Php - XML Schema version

I'm searching for a while for what version xsd support php (5.3.0) has, but I haven't found anything. :S I'm trying to use xsd:assert in a schema with php, but I haven't managed it yet. Can anybody help me?


Selenium error: UnicodeEncodeError

I am getting the following error when i execute the following command:

text = idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station
self.se.is_element_present("css=a[href]:contains('idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station')")

The title I am searching for on the website, is as follows:

idobi Radio: New. Music. Unfiltered. idobi.com - a SHOUTcast.com member station

The whole error i get is :

 UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 91: ordinal not in range(128)

could someone please help me with this issue?

thanks.


Double Buffering in F#: what is the deal with the flicker?

I am trying to implement double buffering in F#.  All of the examples I am running into are C#.

    let r = form.DisplayRectangle
    let buffer = new Bitmap(r.Width,r.Height)
    form.DrawToBitmap(buffer,r)
    form.BackgroundImage <-buffer
    form.Invalidate()

Although the problem is an "easy" fix, the private variables are not exposed in F#.  Instead, I have to initialize the form in C#.  There must be a way though (it seems like this is a trivial thing) to expose the private variables for the form in F#.


Parse request.object.existed() return false

I have problem with parse. I wrote cloud code

Parse.Cloud.afterSave(Parse.User, function(request) {
  var user = request.object;
  if( !user.existed() ) {
      //all the times !user.existed() is true when I save user object
      //also in signup is true
  }

})

how can I make the inside if block run only if the user is new user?


C# (or any language) DDD - Where to sanitize user input data?

I'm building a DDD app in C# and I have some doubts about where I should sanitize user input.

I already learned that business rules should be validated in domain layer and ID identities should be generated at repository layer.

Should I put this user input sanitizer on the application layer?

(The app it's a ASP.NET MVC with DDD architecture model).


100vh Doesn't seem to be working

I am trying to achieve a 100% height & width header image on my website, and I have been researching different ways to do this, and I came across the "100vh" method, however it only displays at 50% the width of my browser and 100% the height.

http://gyazo.com/07e4861fa3300c22ce7bafc265b15421

.headercontainer{
 background: #000;
 width: 100vh;
 height: 100vh;
}

<div class="headercontainer">
</div>

I've also tried 200vh and that is too wide.


What's the best way to authorize a back-end sever to use the google drive api?

I'm working on a an application where my back-end server will push and pull data over the google drive sdk.  So, the back-end will only ever need a authorization via a single admin user's set of credentials.

Is the best way to do the authorization for this use-case to do what's described here?
https://developers.google.com/drive/web/auth/web-server

It looks like I would manually authorize my back-end's user once and store the refresh token for later offline access, thereby not needing manual/human interaction ever again.

But is that actually the best way for this use case?  Is there another authorization workflow that I've overlooked?


jquery form validation in popup window

I am developing one application which is in codeigniter with smarty template and in that html pages are ready I have to just develop that pages. In that application there is one page which is open in like lightbox as a form and I want to put jquery validation in that I have trying with

<script>
    $(document).ready(function(){
        $("#frm_email").validate({
            rules: {
                email: {
                    required: true,
                    email : true
                }
            },
            messages: {
                email: {
                    required:  "Email is required.",
                    email : "Enter valid email."
                }
            },
            // the errorPlacement has to take the table layout into account
            errorPlacement: function(error, element) {
                if ( $(element).is(":radio") ){
                    $(error).insertAfter( $(element).parent() );
                } else if ( $(element).is(":checkbox") ){
                    $(error).insertAfter( $(element).next() );
                } else{
                    if($(element).is("textarea")){
                        $(error).insertAfter($(element).next());
                    } else {
                        $(error).insertAfter( $(element) );
                    }
                }
            },
            success: function(label ) {
                $(label).remove();
            },
            onkeyup: function(element) { $(element).valid(); },
            onfocusout: function(element) { $(element).valid(); }
        });
    });
 });

this code but its not working and I want form validation before form submit.

So please help me.


How to login as super user and execute the script

I have a script something like below:

Name of script : create_and_set_quota_alternative.sh

#!/bin/bash

while IFS=$'\t' read -r -a myOptions

do

 echo "directory: ${myOptions[0]}"

 echo "ownership: ${myOptions[1]}"

 echo "permissions: ${myOptions[2]}"

 echo "quota: ${myOptions[3]}"

  hdfs dfs -mkdir ${myOptions[0]}

  hdfs dfs -chown ${myOptions[1]} ${myOptions[0]}

  hdfs dfs -chmod ${myOptions[2]} ${myOptions[0]}

  hdfs dfsadmin -setSpaceQuota ${myOptions[3]} ${myOptions[0]}

done < myFile.txt

myFile.txt

/usr/t1 hive:hive       776     1T

/usr/t2 hdfs:hdfs       775     100G

Now I want login as super user and execute the script.
In my case super user is hdfs.
I want whenever I run the command sh create_and_set_quota_alternative.sh then it will login as super user that is hdfs and execute the script.
Please suggest how to implement it.


gtk+ without msys2 mingw

On Windows, trying something with gtk+. I have downloaded Msys2, along with gtk+3.0.

Successfully compiled all the gtk+3.0 examples in the msys2 mingw-w64 terminal.

Now I want to move a bit further to try work without the msys environment.

I opened up cmd and navigated to where the example executables are compiled. Then I fired them up by typing "example.exe".

libgio-2.0-0.dll missing, not surprised. I go back to check the PATH environment of the msys environment, PATH=/mingw64/bin/:/usr/local/bin:/usr/bin/:/bin:/c/Windows/System32:..blablabla

So in the cmd environment I did set PATH=%PATH%;pathto/mingw64/bin; and run example.exe again.

This time it gave a very strange error cannot find entrypoint inflateValidate (in dll libpng16-16.dll)

So I checked, indeed there was no inflateValidate function in the dll. it seemed to me that something thought the function is in the dll and tried to call it but because it doesn't exist so it failed. What I don't understand is that why did it not fail in the msys environment but failed in the windows environment. And does that bring any impact to me if I am going to ship any gtk application? I thought simply distributing the relevant dll would be enough.

I have tried instead of adding the mingw64/bin path to the PATH variable, but copying the required dll the the execute location 1 by 1, but at the end it still gave the same error.

I have also tried to search for other libpng*.dll in my computer, none of them contained the inflateValidate function.

If anyone know whats going on please shed some light to the question.


How can I duplicate Sass color functions in Sketch.app?

Is there a way to use the equivalent of Sass color functions, like lighten and darken, to create color swatches in Sketch.app?

For example, original color #02284B

with Sass, I can use darken(#02284B, 2%); which will render as #022341

Is there an extension or technique for translating Sass color functions to the Sketch color settings?


Runtime error: load of value 127, which is not a valid value for type 'bool'

I'm using g++ 4.9.2 on Debian 8, x86_64. I'm catching a Undefined Behavior sanitizer (UBsan) (-fsanitize=undefined) error:

algebra.cpp:206:8: runtime error: load of value 127,
    which is not a valid value for type 'bool'

The code is from the Crypto++ library. Here is the code at algebra.cpp:206 (and some related code):

206   struct WindowSlider
207   {
208     WindowSlider(const Integer &expIn, bool fastNegate, unsigned int windowSizeIn=0)
209         : m_exp(expIn), m_windowModulus(Integer::One()), m_windowSize(windowSizeIn), m_windowBegin(0), m_fastNegate(fastNegate), m_firstTime(true), m_finished(false)
210     {
            ...
249         Integer m_exp, m_windowModulus;
250         unsigned int m_windowSize, m_windowBegin;
251         word32 m_expWindow;
252         bool m_fastNegate, m_negateNext, m_firstTime, m_finished;
253     };

Its called in a couple of places, like:

$ grep -I WindowSlider *
...
algebra.cpp:    std::vector<WindowSlider> exponents;
algebra.cpp:        exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 0));
ecp.cpp:    std::vector<WindowSlider> exponents;
ecp.cpp:        exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 5));

InversionIsFast is a bool, so that should not be a problem. But I added !!InversionIsFast() just in case and the issue persists.

EDIT: Here is a grep for InversionIsFast. It appears it is initialized.

$ grep -I InversionIsFast *
algebra.cpp:        exponents.push_back(WindowSlider(*expBegin++, !!InversionIsFast(), 0));
algebra.h:  virtual bool InversionIsFast() const {return false;}
ec2n.h: bool InversionIsFast() const {return true;}
ecp.cpp:        exponents.push_back(WindowSlider(*expBegin++, !!InversionIsFast(), 5));
ecp.h:  bool InversionIsFast() const {return true;}

I also initialized m_negateNext in the ctor.

What is the issue, and how do I clear it?


OSX Vim :set laststatus=2 shows only the filename -- but I want to see everything that Ctrl-g provides

Like the title says -- and my google fu fails me as :set laststatus=2 shows only the filename, I'd like to see everything cntrl-g provides.

example:

<relative filename> line 28 of 285 --9%-- col 5

Pretty sure I remember pulling this off with a basic :set command a decade ago, any idea what's going on?  Again, all I'm seeing with :set laststatus=2 is the filename.

bar@baz:~/foo$ vim --version

VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Oct 23 2012 13:50:52)
Compiled by root@apple.com
Normal version without GUI.  Features included (+) or not (-):
-arabic +autocmd -balloon_eval -browse +builtin_terms +byte_offset +cindent
-clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
-conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con +diff +digraphs
-dnd -ebcdic -emacs_tags +eval +ex_extra +extra_search -farsi +file_in_path
+find_in_path +float +folding -footer +fork() -gettext -hangul_input +iconv
+insert_expand +jumplist -keymap -langmap +libcall +linebreak +lispindent
+listcmds +localmap -lua +menu +mksession +modify_fname +mouse -mouseshape
-mouse_dec -mouse_gpm -mouse_jsbterm -mouse_netterm -mouse_sysmouse
+mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg -osfiletype
+path_extra -perl +persistent_undo +postscript +printer -profile +python/dyn
-python3 +quickfix +reltime -rightleft +ruby/dyn +scrollbind +signs
+smartindent -sniff +startuptime +statusline -sun_workshop +syntax +tag_binary
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
 -toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo
+vreplace +wildignore +wildmenu +windows +writebackup -X11 -xfontset -xim -xsmp
 -xterm_clipboard -xterm_save
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -D_FORTIFY_SOURCE=0 -Iproto -DHAVE_CONFIG_H -arch i386 -arch x86_64 -g -Os -pipe
Linking: gcc -arch i386 -arch x86_64 -o vim -lncurses


Trigger an event when scroll to specific element and then stop it with jquery

First Step

I want to make a counter that when user load my page the counter starts from 0 and end on its end value (e.g. 75). So I search from net and found a jQuery code and i copy that code and paste it in my js file custom.js and made some changes as per required. Its working perfectly.

Here is my code:

HTML

<div class="top_div">
  Top Div
</div>
<div class="love_count">75%</div>
<div class="love_count">30%</div>

JS

jQuery(document).ready(function ($) {
function count($this){
  var current = parseInt($this.html(), 10);
  $this.html(++current + '%');
  if(current !== $this.data('count')){
    setTimeout(function(){count($this)}, 15);
  }
}

$(".love_count").each(function() {
  $(this).data('count', parseInt($(this).html(), 10));
  $(this).html('0');
  count($(this));
});
});

Demo

Second Step

Now my clients want that when user scroll down to this specific div then the counter starts. So I again Search from net and found some other codes. But its not working.

First When I scroll down to that specific div the counter first show me my end value (e.g. 75)

Second Then its starts from 0 and the counter never stops. Its goes to thousands, millions but never stops.

Here is my code:

HTML

<div class="top_div">
  Top Div
</div>
<div class="love_counter">
  <div class="love_count">75%</div>
  <div class="love_count">30%</div>
</div>

JS

$(window).scroll(function() {
    var hT = $('.love_counter').offset().top,
        hH = $('.love_counter').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    if (wS > (hT+hH-wH)){
        function count($this){
            var current = parseInt($this.html(), 10);
            $this.html(++current + '%');
            if(current !== $this.data('count')){
                setTimeout(function(){count($this)}, 15);
            }
        }

        $(".love_count").each(function() {
            $(this).data('count', parseInt($(this).html(), 10));
            $(this).html('0');
            count($(this));
        });
    }
});

Demo

What I want

So I want that When site scrolls down to that specific div, the counter starts from 0 and stop on its end value. But when I scroll up or down the counter should not be start again and still stop there end value.

But when user refresh the page and scroll down to that specific div the counter starts as usual and stop to there end value and not starts again when I scroll up or down.

I am very weak in jQuery so please help me out and guide me. I hope you understand my question.


We are trying to update an existing app which supports WatchKit for iOS 9.1.
After archiving the build in Xcode 7.1.1 and sending it through Application Loader, we get the e-mail stating:

Invalid WatchKit Support - The WatchKitSupport folder is missing. Rebuild your app using the current public (GM) version of Xcode and resubmit it.

Now we are already using the latest GM version of Xcode. Is there some build setting that needs to be done to sort this issue? Or is there some other solution?

Any help will be greatly appreciated...thanks!


How to read the Output Type in code

A common nuisance we have is having to switch this code below depending on whether we are testing locally or committing code for the build server.

    /// <summary>
    /// Main entry point to the application.
    /// </summary>
    public static void Main()
    {
        // Don't forget to uncomment this if committing (!)
        //var servicesToRun = new ServiceBase[] {new myservice()};
        //ServiceBase.Run(servicesToRun);

        // and re-comment this
        RunAsConsoleApp();

    }

It would be really useful if there was a way to test in the code to tell the output type i.e, and avoid all the 'oh-no I committed and broke the build' time wasting.

        if (IsConsoleApp)
        {
            Using(var host= new ServiceHost(typeof(myservice))
            {
               host.Open();
               etc....
            }
        }
        else
        {
            var servicesToRun = new ServiceBase[] {new myservice()};
            ServiceBase.Run(servicesToRun);
        }


Responding to concurrent requests with Flask and eventlet

I try to set up a minimal Flask application that uses eventlet to respond to concurrent requests instantly instead of blocking and responding to one request after the other (as the standard Flask debugging webserver does).

Prerequisites:

pip install Flask
pip install eventlet

From my understanding by what I found so far on the internet, it should work like this:

# activate eventlet
import eventlet
eventlet.monkey_patch()

from flask import Flask

import datetime
from time import sleep

# create a new Flask application
app = Flask(__name__)

# a short running task that returns immediately
@app.route('/shortTask')
def short_running_task():
  start = datetime.datetime.now()
  return 'Started at {0}, returned at {1}'.format(start, datetime.datetime.now())

# a long running tasks that returns after 30s
@app.route('/longTask')
def long_running_task():
  start = datetime.datetime.now()
  sleep(30)
  return 'Started at {0}, returned at {1}'.format(start, datetime.datetime.now())

# run the webserver
if __name__ == '__main__':
    app.run(debug=True)

When running this file, then opening http://localhost:5000/longTask in a webbrowser tab and while it is still processing opening another tab with http://localhost:5000/shortTask, I would expect the second tab to return immediately while the first tab is still loading. However, similar to when running this on the standard Werkzeug server, the second tab only returns just after the first one is finished after 30s.

What is wrong here?
By the way, would this be what is commonly referred to as a "production ready webserver" for Flask, given that there are only few concurrent users to be expected (5 at most)?

By the way, when I use the Flask-socketio library to run the webserver which, according to the documentation, automatically chooses eventlet if it is installed, then it works as expected.

Complete example with Flask-socketio:

# activate eventlet
import eventlet
eventlet.monkey_patch()

from flask import Flask
from flask_socketio import SocketIO

import datetime
from time import sleep

# create a new Flask application
app = Flask(__name__)

# activate Flask-socketio
socketio = SocketIO(app)

# a short running task that returns immediately
@app.route('/shortTask')
def short_running_task():
  start = datetime.datetime.now()
  return 'Started at {0}, returned at {1}'.format(start, datetime.datetime.now())

# a long running tasks that returns after 30s
@app.route('/longTask')
def long_running_task():
  start = datetime.datetime.now()
  sleep(30)
  return 'Started at {0}, returned at {1}'.format(start, datetime.datetime.now())

# run the webserver with socketio
if __name__ == '__main__':
    socketio.run(app, debug=True)


What to consider when looking at multiple methods to achieve the same result while coding?

I am currently coding in C++, creating an all rounded calculator that, when finished, will be capable of handling all major and common mathematical procedures.

The current wall I am hitting is from the fact I am still learning about to profession we call being a programmer.

I have several ways of achieving a single result. I am curious as to whether I should pick the method that has a clear breakdown of how it got to that point in the code; or the method that is much shorter - while not sacrificing any of the redability.

Below I have posted snippets from my class showing what I mean.

This function uses if statements to determine whether or not a common denominator is even needed, but is several lines long.

Fraction Fraction::addFraction(Fraction &AddInput)
{
    Fraction output;

    if (m_denominator != AddInput.m_denominator)
    {
        getCommonDenominator(AddInput);

        output.setWhole(m_whole + AddInput.m_whole);
        output.setNumerator((m_numerator * firstchange) + (AddInput.m_numerator * secondchange));
        output.setDenominator(commondenominator);
    }
    else
    {
        output.setWhole(m_whole + AddInput.m_whole);
        output.setNumerator(m_numerator + AddInput.m_numerator);
        output.setDenominator(m_denominator);
    }

    output.simplify();

    return output;
}

This function below, gets a common denominator; repeats the steps on the numerators; then simplifies to the lowest terms.

Fraction Fraction::addFraction(Fraction &AddInput)
{
    getCommonDenominator(AddInput);

    Fraction output(m_whole + AddInput.m_whole, (m_numerator * firstchange) + (AddInput.m_numerator * secondchange), commondenominator);

    output.simplify();

    return output;
}

Both functions have been tested and always return the accurate result. When it comes to coding standards... do we pick longer and asy to follow? or shorter and easy to understand?


How to provide braintree client token using python backend and web frontend?

I'm building a site with some simple backend functions, and are about to implement braintree using their python library and javascript frontend. Frontend is HTML bootstrap with some Javascript and Angular. I'm not using any Python/flask template engine/renderer.

However in their tutorial they are not very clear on how to obtain the client token, that needs to be generated for each session.

Right now I've done a regular GET-endpoint in flask for the python backend:

@app.route('/ctoken')
  def client:token():
    client_token = braintree.ClientToken.generate()
    return client_token

In the frontend I get the token using a regular jQuery get:

$.get( "ajax/test.html", function( data ) {
  braintree.setup(
  data,
  'dropin', {
    container: 'dropin'
  });
});

I wonder if this is the best way ? I'm using heroku and will use their HTTPS service, but is this best practice or is there another way to do this?

PS. the site is not live yet, only sandbox and local testing, want to get everything as secure as it should be.


How to get a label value into a div

This is my html code:

<div id="box">
    <div>
      <label for="text">Text 1</label>
    </div>
    <div>
      <label for="text">Text 2</label>
    </div>
    <div>
      <label for="text">Text 3</label>
    </div>
</div>

I need to get all label in a div with id="box" so I use Jquery:

var container=$('div[id="box"]');
container.find('label[for="text"]').each(function(index){
    console.log("INDEX "+index);
});

The problem is that the jquery function print only one time "INDEX" 0. Anyone can help to print all label value?


Unity GUIText on Collision c#

I'm writing a 3D maze program in C# and I need to have UI Text display "You Win!" When the player reaches the end of the maze.

I have a trigger set up in Unity as a cube, named FinishLine, and I have the UI text named winText

I'm getting an error on this line..

GUI.Box(New rect (10,10,100,90), winText);

the error is "The best overloaded method matfch for unityengine.gui.box (unityEngine rect, string)' has some invalid arguments

I also have no idea what those numbers are (10,10,100,90), so maybe that's messing something up? What are those values indicating...?

Here is my code..

public class TextTrigger : MonoBehaviour {

     public GUIText winText;
     private bool FinishLine = false;

     void Start () {
         FinishLine = false;
     }

     void OnTriggerEnter(Collider col){
         if (col.tag == "Player") {
             FinishLine = true;
         }
     }

     void OnGui() {
         GUI.Box(new Rect(10,10,100,90), winText);
     }
 }

EDIT - Updated my code, and I have a new error.
On line 21 it says: "UnityEngine.Texture does not contain a definition for text and no extension method 'text' accepting a first argument of type 'UnityEngine.Texture' could be found. Are you missing a using directive or an assembly refrence?

NEW CODE:

using System.Collections; using System.Collections.Generic; using
    UnityEngine; using UnityEngine.UI;

public class FinishLine : MonoBehaviour {

public Texture winText;     private bool FinishPlane = false;

// Use this for initialization  void Start () {         FinishPlane =

false;

}

void OnTriggerEnter(Collider col)   {       if (col.tag == "Player") {
        FinishPlane = true;             winText.text = "You Win!";      }   } }


SQL: Cannot delete or update parent row: a foreign key constraint fails

Whenever I try to delete a survey from table "survey" like this:

DELETE FROM surveys WHERE survey_id = 77

It prompts me an error stated below:

#1451 - Cannot delete or update a parent row: a foreign key constraint fails ('user_surveys_archive', CONSTRAINT
  'user_surveys_archive_ibfk_6' FOREIGN KEY ('user_access_level_id')
  REFERENCES 'user_surveys' ('user_access_level_id') ON DELETE NO ACTION
  )

First thing: I do not have any such table with this name "user_surveys_archive_ibfk_6"

2nd thing: There is no record of this survey in other tables.

Any idea on how can I delete this record of fix this issue?

Edit

This is the line I found when I export the table Constraints for table surveys

ALTER TABLE `surveys`
ADD CONSTRAINT `surveys_ibfk_1` FOREIGN KEY (`survey_type_id`) REFERENCES `survey_types` (`survey_type_id`) ON DELETE CASCADE ON UPDATE NO ACTION;`


SSRS cannot deploy

I am an db admin on the server. I have granted the user with "SYSTEM user" on site setting, "Content Manager" on the Home folder, and also "Content Manager" on the her folder XXX.

However, she cannot deploys her report on BIDS and get this error instead:

The permissions granted to user 'WMSERVICE\xxx' are insufficient for performing this operation

I have gone through many site and most of the suggestion is to run it back as Administrator, or give her a SYSTEM Administrator privilege for the SSRS (this is the last resort that I should consider).

Any ideas?


Test Activity onCreate Exception

I have the following Activity that throws an exception if something is configured wrong.

public class MyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        throw new IllegalStateException("something went wrong");
    }
}

I tried to write a test for this ActivityInstrumentationTestCase2

public void testException() throws Exception {
    try {
        getActivity().onCreate(null);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage()).contains("something went wrong");
    }
}

which throws the correct Exception but doesn't run in my catch block due to some internal Sandboxing of the ActivityInstrumentationTestCase2.

So I tried it with plain Java

public void testException() throws Exception {
    final MockNavigationDrawerActivity activity = Mockito.mock(MockNavigationDrawerActivity.class);
    Mockito.doCallRealMethod().when(activity).onCreate(null);
    try {
        activity.onCreate(null);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage()).contains("something went wrong");
    }
}

which does not work

java.lang.AbstractMethodError: abstract method "boolean org.mockito.internal.invocation.AbstractAwareMethod.isAbstract()"
at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:109)
at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)
at com.google.dexmaker.mockito.InvocationHandlerAdapter.invoke(InvocationHandlerAdapter.java:49)
at MockNavigationDrawerActivity_Proxy.onCreate(MockNavigationDrawerActivity_Proxy.generated)

Any idea how to test this simple case?

Update #1

I tried absolutely everything. I reduced it to the absolute minimum which doesn't work.

public void testUpdate1() throws Exception {
    try {
        getActivity();
        fail();
    } catch (Exception e) {
        assertThat(e.getMessage()).contains("something went wrong");
    }
}

stacktrace:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MyActivity}: java.lang.IllegalStateException: something went wrong
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        Caused by: java.lang.IllegalStateException: something went wrong
        at com.example.MyActivity.onCreate(MyActivity.java:28)
        at android.app.Activity.performCreate(Activity.java:5933)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:346)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
        ... 10 more

Update #2

I started from the beginning. Generated a new project, threw the Exception

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    throw new IllegalStateException("something");
}

an tried to catch it with a Throwable.

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    public MainActivityTest() {
        super(MainActivity.class);
    }

    public void testOnCreate() throws Exception {
        try {
            getActivity();
            fail();
        } catch (Throwable throwable) {
            assertTrue(throwable.getCause().getMessage().contains("something"));
        }

    }
}

I got this (complete) stacktrace which does not lead to my test. The system seems to call onCreate, perhaps from a different process, not my test.

Process: com.pascalwelsch.onccreatetest, PID: 3915    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pascalwelsch.onccreatetest/com.pascalwelsch.onccreatetest.MainActivity}: java.lang.IllegalStateException: something
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 Caused by: java.lang.IllegalStateException: something
        at com.pascalwelsch.onccreatetest.MainActivity.onCreate(MainActivity.java:15)
        at android.app.Activity.performCreate(Activity.java:5933)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)


Scroll events stop working in Safari

I am developing a website that has scrolling transitions on the "index" page and then normal scrolling with a sticky navigation bar on other pages. The site also uses ajax to transition from one page to the next. I have an if statement based on if the user is on the index page use the scrolling transitions, else use normal scrolling with the sticky navigation.

The problem I've found is that in safari when I click on a link from the index page, scroll on the new page and then go back to the index page, the scroll transitions are not activated again. In fact it seems that the scroll events I have set up stop working entirely.

However this problem does not occur in any other browser: Chrome, IE, Edge or Firefox.

I don't know if it's best for me to post the code for it on here because it is a bit long. But here is a link to the code: http://www.dreshaddev.dreamhosters.com/layout/js/scripts.js

Here is a link to the development site: http://www.dreshaddev.dreamhosters.com/layout/index.php

I have tried multiple solutions like reinstating the same code after an ajax call and removing event listeners and re-adding them back in. I'm not sure what to do. I am testing this on Safari 9.1.3.


Is it possible to detect if the selected item is the first in LINQ-to-SQL?

I wonder how I can build a query expression which understands the given item being selected is the first or not. Say I'm selecting 10 items from DB:

var query = db.Table.Take(10).Select(t => IsFirst ? t.Value1 : t.Value2);

There is an indexed variant of Select but that is not supported in LINQ-to-SQL. If it was supported my problems would be solved. Is there any other trick?

I could have used ROW_NUMBER() on T-SQL for instance, which LINQ-to-SQL uses but does not give access to.

I know I can Concat two queries and use the first expression in the first and so forth but I don't want to manipulate the rest of the query, just the select statement itself because the query is built at multiple places and this is where I want to behave differently on first row. I'll consider other options if that is not possible.


density curve plot in ggplot

I am new in ggplot and I am trying to draw a density curve.
This is a simplified version of the code that I am trying to use:

ggplot(data=ind1, aes(ind1$V1)) +
geom_density(fill = "red", colour = "black") + xlim(0, 30)

The density curve plot that I get looks like this:
enter image description here

I do not understand what is wrong here! does anyone have any idea what is wrong?


Download a file stored in database

I have file content in sql database as binary format and also saved the file with its extension .

I want to have pop up for save as ,so that client can save the file on her system in the same document format.

i.e if it .doc then it should get save in .doc format only.

Please provide the code for the same.


Why Preprocessor 's role is diminishing in C++?

In his book "C++ From The Ground Up" Herbert Schildt wrote that "However, the role of the preprocessor in C++ is much smaller than it is in C. One reason for this is that many of the chores that are performed by the preprocessor in C are performed by language elements in C++. Stroustrup has stated his desire to render the preprocessor redundant, so that,ultimately, it could be removed from the language entirely."

Best examples can be :

use of const keyword instead of #define

use of inline function instead of macro.

Why preprocessor isn't so important in C++?

I just want to know that is preprocessor is really evil? Because Marshall Cline said that preprocessor is evil in this link: http://www.parashift.com/c++-faq/preprocessor-is-evil.html


I am new to programming. I am working on one my school assignment and I have two Jquery files that I am using. One was provided to us from the school. However I am keep getting an error Uncaught TypeError: $(...).moveTo is not a function. I have spent few hours on google but still have not manage to resolve this. Not sure what I am missing. Any suggestion ?

<!doctype html>

<html>

  <head>
      <meta charset="utf-8">
      <meta name='viewport'content='width=device-width, intial-scale=1.0 , user-scaleable=no'/>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
      <script type="text/javascript" scr="./jquery-2.2.4.min.js"></script>
      <script type="text/javascript" scr="js/introtoapps.min.js"></script>

      <script>
        $(document).ready(function(){
        $("#balloon").moveTo(180);
        });
      </script>


Cross-compiling R for ARM (Raspberry Pi)

I need to build R (http://www.r-project.org/) for Arch Linux ARM running on Raspberry Pi.  I am having trouble running ./configure.  I have built my own toolchain using crosstool-ng and it does work, I've compiled other applications with it just fine.

The issue appears to be that I cannot link the Fortran libraries to C code.  Here is where configure fails:

checking for Fortran 77 libraries of gfortran...  -L/home/njackson/bcm2708rpi-toolchain/lib -L/home/njackson/bcm2708rpi-toolchain/lib/gcc/arm-rpi-linux-gnueabi/4.7.3 -L/home/njackson/bcm2708rpi-toolchain/arm-rpi-linux-gnueabi/lib -L/usr/lib/gcc/x86_64-linux-gnu/4.6 -L/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/4.6/../../.. -lgfortran -lm /home/njackson/bcm2708rpi-toolchain/arm-rpi-linux-gnueabi/lib/libgfortran.a /home/njackson/bcm2708rpi-toolchain/lib/gcc/arm-rpi-linux-gnueabi/4.7.3/libgcc.a
checking for dummy main to link with Fortran 77 libraries... unknown
configure: error: in `/home/njackson/R-2.15.3':
configure: error: linking to Fortran libraries from C fails
See `config.log' for more details

It fails here.

I used the following configure command:

./configure --host=arm-linux-gnueabihf CC=/home/njackson/bcm2708rpi-toolchain/bin/arm-rpi-linux-gnueabi-gcc CXX=/home/njackson/bcm2708rpi-toolchain/bin/arm-rpi-linux-gnueabi-g++ FC=/home/njackson/bcm2708rpi-toolchain/bin/arm-rpi-linux-gnueabi-gfortran MAIN_LD=/home/njackson/bcm2708rpi-toolchain/bin/arm-rpi-linux-gnueabi-ld --with-readline=no

I'd appreciate help getting this compiled.  Thanks.


How to hide multiple elements

I want to hide multiple elements when I press a button which get the value of checkboxs, and if the checkbox is checked it's hide.

I have the next code, but it just work with the first element

var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
    test += val.value+",";
});
test = test.substring(0,(test.length-1));
$("#numRow"+test).hide('slow'); // it should to hide multiple elements, but just work with the first value

I also tried with array, but it doen't work too.

var numMsj =[1, 2, 4, 22, 44,90, 100];
$.each(numMsg, function (ind, elem) {
    $("#numRow"+elem).hide('slow');
});


How can I edit an iframe with proxy?

I need to edit an iframe with jQuery but I'm unable to do it.

I tried with:

$(document).ready(function(){
    $("#iframe").on('load',function(){
        $(this).contents().find('body').html('a');
    });
});

This code doesn't work.

EDIT

The iframe is related to a different domain.


How to Install and configure Redis on ElasticBeanstalk

How do I install and configure Redis on AWS ElasticBeanstalk? Does anyone know how to write an .ebextension script to accomplish that?


Offsetting HTML anchors with a fixed header on page

I am currently working on a page that has a fixed header and multiple anchor tags to jump to different sections on the page. I have searched around and found one solution that seems to work the way I would like using CSS primarily, however despite having the the anchors relatively positioned it seems to keep going back to the same location on the page. I would like to have all the links scroll appropriately down to each respective section, and I tried making separate classes for each respective link, but that just took me back to the same location on the page.

Here is the page in question:
http://www.aticourses.com/scheduleNew.html

...and the accompanying css

.anchor{
display: block;
position: relative;
top: -200px;
visibility: hidden;

}

Am I going to have to create different anchors for each respective section?

Thanks.


What's the best way to get the directory from which an assembly is executing

For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose.

I found some quirk with ".\\" and Application.StartupPath.

I've been using

String configPath = ".\\config.xml";

It works fine until I called OpenFIleDialog to open some files in other folders, the statement above failed. Apparently ".\" is referring to "CurrentDirectory", which changes every time when we browse to another folder.

At some point, I was using

String configPath = Path.Combine(Application.StartupPath + "config.xml");

At some point, when I need to execute this assembly from another folder by using Process.Start(), things start to fall apart. Apparently the working directory is not set properly, and Application.StartupPath is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO.

So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned?

EDIT: I meant to get the directory which the assembly reside

EDIT: According to MSDN on AppDomain.BaseDirectory, it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed)

EDIT: I've notice that a related question was posted much earlier. What would cause the current directory of an executing app to change?

Thanks guys for the answer.


Converting a awk 2D array with counts into hashmap in java

I found this problem so interesting. I am using an awk 2D array that has a key,value,count of the same. and that is being printed to a file. This file is in the below format

A100|B100|3
A100|C100|2
A100|B100|5

Now I have a file like this .. My motive is to convert this file into a hash map so that the final output from the hash map is.

A100|B100|8
A100|C100|2

Just an aggregation

The challenge is, this one has 3 dimensions and not two. I did have an another file in the below format which is

D100|4
H100|5
D100|6

I easily aggregated the above as it is only 2D and I used the below code to do that

String[] fields= strLine.trim().split("\\|");
if(hashmap.containsKey(fields[0]))
{
//Update the value of the key here
hashmap.put(fields[0],hashmap.get(fields[0]) + Integer.parseInt(fields[1]));
}
else
{
//Inserting the key to the map
hashmap.put(fields[0],Integer.parseInt(fields[1]));
}

So this was quite simple for implementation.

But when it comes to 3D I have to have an another check inside.. My idea for this is to maintain a [B100,5(beanObject[5])]

  Map<String,beanClassObject> hashmap=new Map<String,beanClassObject>();

secongField hash map which has been used in the code that has a mapping relation between the created ben Object subscript and the key as the second field "For instance it is "

This bean class would have the getter and setter method for the 2nd and 3rd fields of the file. I hope I am clear with this point. So the implementation of this would be

if(hashmap.containsKey(fields[0]))
{
   **//Have to check whether the the particular key value pair already exists ... I dint find any method for this ... Just a normal iteration is there .. Could you ppl guide me regarding this**

    //Update the value of the key here
     secondFieldHashMap.get(fields[1]).COunt= secondFieldHashMap.get(fields[1]).getCOunt+ Integer.parseInt(fields[2]));
   }
   else
    {
     //Inserting the key to the map
     hashmap.put(fields[0],Integer.parseInt(fields[1]));
     secondFieldHashMap.get(fields[1]).COunt=  Integer.parseInt(fields[2]));
    }
else
{

 // This meands there is no key field
 // Hence insert the key field and also update the count of seconfFieldHashMap as done previously.
 }

COuld you ppl please throw some ideas regarding this. Thank you


AspNetCore 2.0 MVC / 'model' must appear at the start line

_Create.cshtml (snippet)

@model MC.Models.AdminViewModels.NewUserViewModel

@await Html.PartialAsync("_ModalHeader", new ModalHeader() { Title= "New User"})
<div class="modal-body">
<form asp-action="Create">
    <div class="form-horizontal">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="NewUser.FirstName" class="col-md-4 control-label">First Name</label>
            <div class="col-md-8">
                <input asp-for="NewUser.FirstName" class="form-control" />
                <span asp-validation-for="NewUser.FirstName" class="text-danger"></span>
            </div>
        </div>

Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException:
  One or more compilation failures occurred:
  C:\Projects\Webs\MC\Areas\Admin\Views\Shared_ModalFooter.cshtml(1,3):
  Error RZ9999: The 'model` directive must appear at the start of the
  line.    at
  Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(String
  relativePath)    at
  Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(String
  normalizedPath)

_ModalFooter.cshtml (example of nearly exactly what is in _ModalHeader)

@model MC.Models.ModalFooter

<div class="modal-footer">
    <button data-dismiss="modal" id="@Model.CancelButtonID" class="btn btn-default" type="button">@Model.CancelButtonText</button>
@if (!Model.OnlyCancelButton)
{
    <button class="btn btn-success" id="@Model.SubmitButtonID" type="submit">
        @Model.SubmitButtonText
    </button>
}
</div>

This has thrown me for a loop. Asp.net Core 2.0, works just fine in 1.1.2 but this is thrown for each and ever partial within partial, that is setup for modal use. Error RZ9999 hasn't been documented anywhere apparently. Of course taking out the the partial for straight html doesn't throw the error, but as can imagine that is 1 line verse 3-4 lines of code.  I figure I am missing something from Asp.net Core MVC 1.1 to 2.0 conversion somewhere.  Also this is partial within a partial.

NOTE: I am using the 'Microsoft.AspNetCore.All' package pull in the *.csproj, since release day NuGet didn't have the EF tools packages for v2.


Nginx server on Google App Engine stopped working suddenly

Starting yesterday, my google app engine app stopped working.

I have started seeing hundreds of these in the nginx.error log stream:

One of these, for example,

[error] 32#0: *506755 upstream prematurely closed connection while
  reading response header from upstream, client: 169.XXX.XXX.XXX, server:
  , request: "PUT /parse/classes/_Installation/Vt22FpBXIm HTTP/1.1",
  upstream:
  "http://172.XXX.XXX.XXX:8080/parse/classes/_Installation/Vt22FpBXIm", host:
  “my-project-id.appspot.com"

I have used XXXs to obfuscate ips.
I have absolutely no clue what’s happening, I barely know what nginx is.

No changes were made to clients nor server in the last week. These errors started yesterday. Requests fail with 502 Bad gateway.

Do you have any clue what might be happening, and why? Where should I look to debug this issue? I found no relevant information in logs whatsoever.


Warning in android xml file

when I add any element in android layout, compiler(eclipse) shows a warning on element's attribute android:text="Text"
What does mean of following warning.

"[118N]Hardcoded string "Text", should use @string resource"

when we add @ with string like "myString%" it gives error.


Use limit in sub query

I have 4 tables

product

status

orders

orders_products.

Using following query I get the proper result but it is not in correct order i.e. result gets by sub query.I want result order as sub query result.

SELECT
    p.products_id, p.products_image, p.products_tax_class_id,
    pd.products_name, if(s.status, s.specials_new_products_price,
    p.products_price) as products_price
FROM
    products p LEFT JOIN specials s
        ON p.products_id = s.products_id, products_description pd
WHERE
    p.products_status = '1'
    AND p.products_id = pd.products_id
    AND pd.language_id = '2'
    AND p.products_id in (
        SELECT * from (
            SELECT
                distinct(op.products_id)
            FROM
                orders_products op,orders o
            WHERE
                op.orders_id=o.orders_id
                AND o.customers_id='27'
            ORDER BY
                o.date_purchased
            DESC LIMIT 0,10
        ) AS temptable
    )


Django project on pythonanywhere

I uploaded my app that worked fine on my local machine to pythonanywhere. I got it to work but instead of showing the homepage of my blog it shows the "It worked, welcome to Django" page. Could someone please help me?


Error: 1408A0C1:ssl routines:ssl3_get_client_hello:no shared cipher

I create a DataSnap REST Server with the Wizard for a 3-Tier application having two connections:

One by TCP/IP Port: 211 and it works properly.

Second connection by HTTP Port 8080 and this not works.When I launch a simple https://localhost:8080/ from the Navigator, Launch a debugger error shown in the attached file.

The Wizard has created the Procedure:

procedure TForm1.FormCreate(Sender: TObject);
var
  LIOHandleSSL: TIdServerIOHandlerSSLOpenSSL;
begin
  FServer := TIdHTTPWebBrokerBridge.Create(Self);
  LIOHandleSSL := TIdServerIOHandlerSSLOpenSSL.Create(FServer);
  LIOHandleSSL.SSLOptions.CertFile := '';
  LIOHandleSSL.SSLOptions.RootCertFile := '';
  LIOHandleSSL.SSLOptions.KeyFile := '';
  LIOHandleSSL.OnGetPassword := OnGetSSLPassword;
  FServer.IOHandler := LIOHandleSSL;
end;


In a popup, change text in a span

I was trying to add an external JavaScript file to my HTML for a practice Chrome extension. It has a slider whose value needs to be taken and sent back to a span tag on the popup.html,
As I looked up I need to have a separate JavaScript file and create an onchange event listener to take the element and pass its value. But I cannot get the value to show on span tag. Please guide on what I am doing wrong.

This is the HTML (popup.html)

<!doctype html>

<html>
 <head>
   <title>Slide</title>
 </head>

 <body>
     <input type="range" min="0" max="50" value="0" step="5" id="slider" />
     <span id="range">0</span>
     <script type="text/javascript" src="popup.js"></script>
 </body>
</html>

And This is the JavaScript file (popup.js)

 document.getElementById("slider").onchange = function() {showValue()};

 function showValue()
 {
    var newValue = document.getElementById("slider");
    var rng = document.getElementById("range");
    rng.value = newValue.value;
 }


Selecting Dropdown fields with Selenium IDE

I am using the record and play option to record test scripts in my web app. I want to know the command that will be appropriate to use to enable me to click on a dropdown and select and  verify an element in the dropdown. Anyone knows how do it?


Multipart file upload in Swift

I have a problem in uploading file in a server called jetty.

I have this code for multipart file upload

   func post(url: String,ticketId: String, workLogDecs: String, status: String,img: UIImage){

    var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)\(url)")!)

    let imageData = UIImageJPEGRepresentation(img, 1)

    let parameters = ["workLogDesc":"\(workLogDecs)","requestId":"\(ticketId)","status":"\(status)"]

    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    request.HTTPBody = createBodyWithParameters(parameters, filePathKey: "files", imageDataKey: imageData, boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=\(error)")

            var userInfo = error.userInfo
            var errorString = userInfo?.description

            println("errorString \(errorString)")
            return

        }

        // You can print out response object
        println("******* response = \(response)")

        // Print out reponse body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("****** response data = \(responseString!)")
    }
    task.resume()
}

And here is my code for creating body with params:

    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

    var body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("–\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "test.jpg"

    let mimetype = "image/jpg"

    body.appendString("–\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.appendData(imageDataKey)
    body.appendString("\r\n")

    body.appendString("–\(boundary)–\r\n")

    return body
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

and I use extension :

extension NSMutableData {
func appendString(string: String) {
    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    appendData(data!)
}

My problem is the I'm getting an error and saying "Cannot parse Response"

here is my error log:

Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo=0x7ff43a74c850 {NSUnderlyingError=0x7ff43a6b4660 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1017.)", NSErrorFailingURLStringKey=http://192.168.137.160:8082/ws/worklog/new, NSErrorFailingURLKey=http://192.168.137.160:8082/ws/worklog/new, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response}

Is there wrong in my code. I am new with this multipart file upload. If there is another way to do this please do help me. Thanks.


Nginx - failed to open stream: Permission denied in /var/www/example.com

My website is running on nginx + php-fpm and running well but while uploading file it shows blank page.My log file shows

2016/06/08 14:44:40 [error] 22063#22063: *25 FastCGI sent in stderr: "PHP message: PHP Warning:  file_put_contents(up/propic/medium/5961465411480.jpg): failed to open stream: Permission denied in /var/www/example.com/saveimg.php on line 32" while reading response header from upstream, client:...

I tried most of answers from stackoverflow , even I changed the /var/www folder permissions to 777 but the results are same.

Few details about my server

/etc/php-fpm.d

 user=nginx
 group=nginx

ownership and group of /var/www/sites

drwxrwxrwx. 29 ec2-user root 4096 Jun  8 14:39 site1.com


Return a response and file via servicestack

I am working on a project where we have a database and a separate file system both stored on the same server and are accessed through service stack requests and responses.

The database contains the relevant metadata for a given file in the file system and as such we would like to be able to retrieve and store these files and documents simultaneously to prevent orphaned data.

Is is possible to return both a stream of data (file) and a response DTO in the same response? Similar to how JsonServiceClient.PostFileWithRequest allows for both a file and request DTO to be passed to the server. If it is possibly how would it be handled on both the server and client sides?

In my research so far most applications appear to just return either a response document or a stream and mostly through the use of HttpResult.

Thanks in advance!


Classic ASP - Regex - pattern is not replacing with string empty

Am trying to replace content with empty using this regular expression.

objRegExp.Pattern = "<(?>/?)(?!(p|strong)(>|\s))[^<]+?>"
sHtml = objRegExp.Replace(sHtml, "")

If I test this <(?>/?)(?!(p|strong)(>|\s))[^<]+?> regex on gskinner, it is working fine. But when I place this on Classic ASP page, it is not working.

When I debug error is shown as

Syntax error in regular expression

INPUT:

<h2>Regex testing</h2><br/><p>P Test</p><div>Div Test</div><strong>Strong Test</strong>

EXPECTED OUTPUT:

Regex testing<p>P Test</p>Div Test<strong>Strong Test</strong>

Please suggest, What's gone wrong here?


MongoDB database connection issue after first insert?

So I have a simple insert function for MongoDB which needs to insert data into the database.

(Multiple Inserts per Click) -> (MongoDB Database) -> (Return Value)

Here is the mongodb function:

mongo.connect(specificDatabaseURL, function(error, database){
   database.collection('user-data').insert({bob: 'bob'});
   database.close();
});

The first click, the data {bob: 'bob'} gets inserted. But when I click a second time, I get this error on Google Chrome.

"POST http://123.456.789:8080/users/insert/ net::ERR_CONNECTION_RESET"

Something with database.collection('user-data').insert({bob: 'bob'}); is causing the error but I dont know why it is refusing to connect after the first click?

Also I tried replacing {bob: 'bob'} to a user-inputted variable but still gives the same error.

The connection, "mongo.connect()" is not the one giving the error.

Please help. Thank you.


Populate submodel dependent on model id

first of all sorry if my title is incomprehensible. I'm still learning so please be forgiving. I searched StackOverflow but found nothing that I can clip into my problem.
So... I'm teaching myself MVC and C# and I decided to create small Blog App. I'm using N-Tier architecture which contains Blog.Back(admin panel front-end stuff and controllers that are using ModelProviders from Logic to manipulate data), Blog.DAL which contains EDMX, Blog.Logic which contains Models and ModelProviders. I've got this model:

    public class CategoryModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List Posts { get; set; }

        public CategoryModel()
        {
            Posts = new List();
        }
    }

which contains constructor that inits empty Posts, but I can't figure out how to populate it with data and for now if I loop through my CategoryModel to list Categories and in my views if I count(@Model.Posts.Count()) it always returns 0. Any ideas? Please be detailed with answers.

Sorry if it is duplicate. I tried searching but found nothing similar.


ADFS + OpenID Connect email claim and external ADFS

I'm having difficulties setting up ADFS with OpenID Connect on Windows Server 2016.

I've setup AD for testing and I can successfully authenticate, however the email claim is not in the id token.

Additionally I've setup an external ADFS in the Claims Provider trust. It is displayed as an option, however upon logging in I get the error:

    MSIS9642: The request cannot be completed because an id token is required but the server was unable to construct an id token for the current user.

Anybody have suggestions on how to fix this?


Combining SQL results using LINQ

I have a database of company registrants (for a search/directory functionality).  We've added a new table to hold "enhanced" information for registrants that pay for this feature (such as advertisements/additional images/logos etc).  Right now the new table just holds the registrants unique identifier, and a few additional fields (paths to images etc).  A user can search for users with specific criteria, and the enhanced listings should appear at the top of the list.  The results should not show any registrant twice (so if a user has an enhanced listing they should only appear in the top "enhanced listing" area).  How can I accomplish this?


HTML5 Canvas Drag and Drop with snap into position images

http://www.html5canvastutorials.com/labs/html5-canvas-animals-on-the-beach-game-with-kineticjs

I am wanting to have this for my HTML5 IOS Application. This requires the widget work offline. When I change line 16, I change the source to "../img/art/" as this is where the images are located. Upon doing this, the entire application disappears. Why?

If there is not a solution, is there a code that will allow me to do the same concept?


How to create a file in Linux from terminal window?

What's the easiest way to create a file in Linux?


Unable to open a newly created Maven project in eclipse

I created a new maven project using the following maven command

mvn archetype:generate -DgroupId=com.company.lib_name -DartifactId=lib_name -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

When I open this newly created project in eclipse it gives the following error:

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-  plugin:2.3.2 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-jar-plugin:jar:2.3.2
Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its    dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-jar-plugin:jar:2.3.2: Hostname cannot be null

I tried th following:

Deleted the .m2/repository and rebuilt the project

Verified that the artifact exists in the maven repo

Maven user settings point to the correct settings.xml

Project compiles on the command line

Cleaned the project

Forced updates n the project

Checked repo to see all the dependencies are downloaded

Change eclipse to use the external maven instead of embeded
Also I am using Kepler and Maven 3.

Any idea what 'hostname cannot be null' is pointing at?

THis is the pom content

  <project xmlns="http://maven.apache.org/POM/4.0.0"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0    http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.company.lib</groupId>
  <artifactId>liby</artifactId>
   <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
 <name>lib</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>jcl-over-slf4j</artifactId>
       <version>1.7.0</version>
       <scope>runtime</scope>
       </dependency>
       <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
   <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>runtime</scope>
   </dependency>
   <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
   </dependency>
   </dependencies>
 </project>

And the settings.xml

<settings>
<profiles>
    <profile>
        <id>Blah</id>
        <repositories>
            <repository>
                <id>inhouse</id>
                <url>http://mavenrepo/maven2_repositories/inhouse</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
            <repository>
                <id>inhouse_snapshot</id>
                <url>http://mavenrepo/maven2_repositories/inhouse_snapshot</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>inhouse</id>
                <url>http://mavenrepo/maven2_repositories/inhouse</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </pluginRepository>
            <pluginRepository>
                <id>inhouse_snapshot</id>
                <url>http://mavenrepo/maven2_repositories/inhouse_snapshot</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>
    </profile>
</profiles>
<activeProfiles>
    <activeProfile>company_name</activeProfile>
</activeProfiles>

<mirrors>
    <mirror>
        <id>central-to-nexus</id>
        <mirrorOf>*</mirrorOf>
        <url>http://mw_maven_repository_readonly/nexus/content/groups/cached</url>
    </mirror>
</mirrors>


mysql syntax error 1064 (42000)

I have a standard LAMP configuration (apache2, mysql, php5), running on ubuntu, and I'm just typing mysql commands into my terminal. I'm logged into the mysql command line as root. So far I've created a new database, but now trouble started.

I'm trying to create a simple table but am getting a mysql syntax error and can't figure out what I'm doing wrong.

This is the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10

And this is my query:

CREATE TABLE IF NOT EXISTS `customers` (
  `uid` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(100) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `created` datetime NOT NULL DEFAULT TIMESTAMP
);

No idea what's wrong honestly.


checking for URL validity in VB.net

I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}


How to accept mustUnderstand and other attributes on SOAP header parts?

I have a WSDL for a soap-based web service that contains a custom header:

<message name="Request">
    <part element="common:Request" name="Request"></part>
    <part element="common:myHeader" name="Header"></part>
</message>

<operation name="processRequest">
    <soap:operation soapAction=""/>
    <input>
        <soap:body parts="Request" use="literal"/>
        <soap:header message="tns:Request" part="Header" use="literal"></soap:header>
    </input>
    <output>
        <soap:body use="literal"/>
    </output>
</operation>

The header type is defined in a separate schema file:

<xs:element name="myHeader" nillable="false" type="tns:myHeaderType"/>

<xs:complexType name="myHeaderType">
    <xs:sequence minOccurs="1" maxOccurs="1">
        <xs:element name="JobID" type="tns:JobIDType" minOccurs="1" maxOccurs="1"/>
        <xs:element name="TransactionID" type="xs:string" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

Furthermore, I am validating against the definition of myHeaderType to make sure that the required elements are there, formatting constraints are met, etc.  This all appears to be working correctly, in that well-formed requests are accepted and incorrectly formatted requests are rejected.

My problem arises with a consumer who uses Apache Axis (hidden behind a proprietary tool) to generate their web-service client.  As described in another StackOverflow question here, Axis inserts some optional attributes on myHeader that are allowed by the SOAP standard (as nearly as I can tell):

<soapenv:Header>
    <com:myHeader soapenv:mustUnderstand="0" soapenv:actor="">
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
        <JobID>myJobId</JobID>
        <TransactionID>myTransactionId</TransactionID>
    </com:myHeader>
</soapenv:Header>

Because of the tool that my consumer is using, it is not feasible to modify the Axis-generated stubs to omit these attributes, as has been suggested elsewhere.  Furthermore, it seems these attributes should be allowed by my service, if I'm going to claim to be a soap service.  My question is, how can I modify my header definition to accommodate these optional attributes, and ideally plan for attributes that I might not be anticipating.  Is there a standard type that I can extend for my header type definition, or a general best practice for this situation?