Q: Multi-branching model currently I have a task about branching model I should use.
Right now I have master branch and I am branching release branches from time to time to release branches about new features. This is how it looks my branching model right now.
master
|
|---- release 1.0 branch
|   |
|   |
|   |
|   |----- *(1) needed branch
|   |    |
|   |    |
|   |    |
|   |    |
|----    |
|---------
|
|---- release 1.1
|   |
|   |----- needed branch
|   |    |
|   |    |
|   |

*(1) - Each time release branch is closed for features I make new feature branch and then merge this("needed branch") just before next
  release.

Few questions that might come up reading this.
I will edit this as questions are given so I can give the answers in the post

*

*Why you are closing release branch if you need more features? - The thing is I need to have stable branch(release) at any time after development is "over".

What I want to accomplish?
The problem with this branching model is that I might have a lot of features and each one of them for different client and many of the clients don't want to wait another 1 or 2 weeks until next deploy. I was thinking of making branch for every client and pushing features there and whenever client want to get given feature I can deploy from there without affecting other clients. Cause right now this is impossible. But this is really bad approach since as the clients grow the branches will too.
I want more elegant approach. I understand there will be a lot of questions in the comments so please ask them and lets see if I can answer them and come up with solution or at least an idea.

A: It sounds like your problem is not Git: your problem is people. Since these people are paying you, presumably, this seems like the right problem to have!
What I would do is this:
|
* tag:r1
|\______________________
|   \             \     \
|    * feature1   WIP2  WIP3
| __/              |
|/                 |
* tag:r2           * feature2
| ________________/
|/
* tag:r3
|
master

In words, I would do all my releases from master, and all my work on feature branches. When a feature is complete, tested, and a client wants it, only then would I merge to master, retest, and make another release. In this way, master is never in a development state; it's always "just released", or "just about to release" (or idle).
If WIP3 ("Work in progress 3") takes a long time to develop, the graph would evolve like this:
|
* tag:r1
|\__________
|           \
|           WIP3
* tag:r2     |
|\__________ |
|           \|
|            * merge
* tag:r3     |
|\__________ |
|           \|
|            * merge
|            |
|            * feature3
| __________/
|/
* tag:r4
|
master

(I've deleted the feature1 and feature2 branches, now they're merged, but you'd still see the multiple paths in the history.)
If you discover that a client wants a bug fix release to some old version (maybe they paid for support, but didn't pay for new features?), then you can always make a release branch from a tag:
|
* tag:r1
|
* tag:r2
|\_________
* tag:r3   \
|          * bugfix
* tag:r4   |
|          * tag:r2.1
master     |
           release2.x_branch


Q: Is iOS capable of accessing and manipulating files on a Windows network file share? I'm planning an app for work and venturing into potential features which I've not used before.
Essentially I need to be able to access files on a network share, read, write and delete files as well as amend the file names. As a pretty closed platform I'm not sure whether iOS is capable of such a thing and if it is, what features should I look for to begin researching?
My Google-Fu hasn't come up with anything thus far so hopefully looking for someone to point me in the right direction.
Thanks.

A: I know this isn't very secure, but I'd personally create an ASP.NET app on your target Windows Server, or a different Server on the domain. Create web services exposed, and make an iOS app with UIWebView. You can do RPC calls from the web service that do WMI/ADSI/File System manipulation. You can prompt for domain credentials, and do remote calls essentially is the gist.
You could expose the web app so that your app can access it from local network, or URL. If you were to access it from outside I'd suggest using some secure credentials in Windows/IIS.
Some years ago I created a "mobile-friendly" web app that allowed me to manage servers, perform RPC, and do basic Active Directory queries. Also allowed file listing and deletion/moving/copying with some creative scripting. It was essentially a ASP.NET/C# web app that loaded in a iPhone app. UIWebView in iOS was a able to load it, used AJAX and some other client side scripting that looked decent. You'd essentially have to make sure that your web app renders properly in Safari/UIWebView (which is bastardized safari).
Here's a link to a demo of what I created:
https://www.youtube.com/watch?v=czXmubijHwQ&t=12s
I ran it in a browser, but it'd run from my PSP, Android test devices, iPod Touch, Blackberry, etc.


Q: In google sheets, how do you use googlefinance to get the high price of a stock in a date range? I wrote the following formula, and it only returns the high of the starting date and not the high of the entire date range:  =INDEX(GoogleFinance(C7,"high", A7,B7,"DAILY"),2,2)
where C7 is the google sheet cell that contains the stock symbol and A7 contains the starting date and B7 contains the ending date.

A: The formula:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))
…will return the stock's high price between the dates A7 and B7 in your example.1
How does it work?
Using the formula:
=GOOGLEFINANCE(<symbol>, "high", <StartDate>, <EndDate>) or
=GOOGLEFINANCE(C7, "high", A7, B7) (in your example),
…will return an array which looks something like this:

Using the INDEX() function, you can convert that array to a single column of the high values:
=INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2)

Now you can pass that array into the MAX() function to get the highest value in a single cell:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))

1 Important Note:
If you include a date range in GOOGLEFINANCE's "high" function, it will not include today's price during the current trading day — so if you need to include today's high price in your range, you will need to compare today's high price to the historical data explicitly.
E.g., the function =GOOGLEFINANCE(symbol, "high") gives you today's high price, so:
=MAX(GOOGLEFINANCE(C7, "high"), MAX(INDEX(GOOGLEFINANCE(C7, "high", TODAY()-30, TODAY()), , 2)))
…will give you the high price over the last 30 days, including today.
If there's a possibility that your date range might include today only (i.e. no historical data where A7 and B7 both equal today), unfortunately, the formula above will return #NA. I have the ultimate solution to generate the correct array even if it does not contain historical data.
The Bullet-Proof Solution
The formula below traps the #NA condition and builds the array to include today's high no matter what date range is specified:
=MAX(INDEX({IFNA(GOOGLEFINANCE(E7, "high", A7, TODAY()), {"Date", "High"}); NOW(), GOOGLEFINANCE(E7, "high")}, , 2))
I've been bitten by this quirk a few times and this solution seems to be cover all scenarios. Enjoy!

A: Please try:
=max(INDEX(GoogleFinance(C7,"high",A7,B7,"DAILY"),0,2))

0,2 rather than 2,2 at the end to return the range rather than a cell from it and MAX for the maximum.


Q: How to reference a method on the object itself In java I can write
Arrays.asList("test  ").stream().map(String::trim);

If I try this in groovy
Arrays.asList("test  ").stream().map(String.&trim)

I get
    Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.trim() is applicable for argument types: (String) values: [test  ]
Possible solutions: trim(), wait(), grep(), wait(long), split(java.lang.String), print(java.io.PrintWriter)

What is the correct syntax or do I have to resort to
    Arrays.asList("test  ").stream().map({ x -> x.trim() })

?

A: you can use .map { it.trim() } too, but otherwise, groovy does not have method reference working like java one


Q: stripe.net - how to process subscriptionService.Get with no results The stripe.com API only returns active subscriptions. I want to verify when I delete a subscription.
So this is going to return an error. I am not sure how to code for it.
I would prefer to make this call based on the subscriptionId. Will this cause an exception or will it return an error code?
Retrieving a subscription
var subscriptionService = new StripeSubscriptionService();
StripeSubscription stripeSubscription = subscriptionService.Get(*subscriptionId*);

Another options which is somewhat of a hack is to return all the subscriptions for the given customer and test to see if the subscriptionId was returned.
List all subscriptions for a customer
var subscriptionService = new StripeSubscriptionService();
IEnumerable<StripeSubscription> responses = subscriptionService .List(*customerId*);
foreach( var response in responses )
{
     if (response.subscriptionId == subscriptionId)
     {
         // subscription exists and was not deleted
         exit;
     }
}

A: Per their documentation, https://stripe.com/docs/api they have 2 different APIs.  You're trying to use the RESTful API, which is for retrieving information on demand.
They also have a WebHooks API, which requires you have an endpoint listening on your site which can accept event notifications.  You configure these through your Dashboard with them.
The event type you're looking for specifically is probably the customer.subscription.deleted event, but there's a lot more you can do with them and I'd encourage you to explore all of those Webhooks.
I can't offer a code sample, as I don't use their service.

A: The strip.net example shows the subscriptionService.Cancel as a methed:
var subscriptionService = new StripeSubscriptionService();
subscriptionService.Cancel(*customerId*, *subscriptionId*);

But you can also use it as a function and it returns the subscription object.
var subscriptionService = new StripeSubscriptionService();
StripeSubscription stripeSubscription = subscriptionService.Cancel(*customerId*, *subscriptionId*);

If (stripeSubscription.Status != "canceled")
{
     //subscription not cancelled
     // take action
}

Per Stripe API docs:
Returns:
The canceled subscription object. Its subscription status will be set to "canceled" unless you've set at_period_end to true when canceling, in which case the status will remain "active" but the cancel_at_period_end attribute will change to true.One of the fiels is .status , witch is set to canceled.


Q: funny fish - etymology background? I am reading translated version of Haroun and the Sea of Stories by Salman Rushdie and I am not sure about the meaning of funny fish. It was translated to my mother language as a tricky thing.
I know that if something is fishy it means that it is not so good. It might be then that the translation of funny fish is following the same roots. Is that so?
Could someone explain the meaning and more importantly the etymology background of "funny fish"?
The text from the book goes like that

Mr Butt managed to make the Mail Coach go even faster. ' "Need to
  stop?" ' he bellowed over his shoulder. ' "Need to go so quickly?"
  Well, my sirs, I'll tell you this: Need's a slippery snake, that's
  what it is. The boy here says that you,sir, Need A View Before Sunset,
  and maybe it's so and maybe no. And some might say that the boy here
  Needs A Mother, and maybe it's so and maybe no. And it's been said of
  me that Butt Needs Speed, but but but it may be that my heart truly
  needs a Different Sort Of Thrill. O, Need's a funny fish: it makes
  people untruthful. They all suffer from it, but they will not always
  admit.

A: Funny in this case just means strange, or unusual; and, notwithstanding Rushdie's deft use of alliteration, a fish just means a thing, as in "a kettle of fish". So, a funny fish is just a strange thing:

Need's a strange thing: it makes people untruthful.

The use of fish brings to mind Shakespeare's phrase a cold fish, to indicate a heartless person:

it was thought she was a woman and was turned into a cold fish for she would not exchange flesh with one that loved her

A Winter's Tale, Act 4, Scene 4
Also, there is the phrase kettle of fish, where fish refers to some unspecified object. See: Origin of “kettle of fish”.

funny adjective (STRANGE)
strange, surprising, unexpected, or difficult to explain or understand:
The washing machine is making a funny noise again.

Cambridge Dictionary


Q: Which components do what when using Python with OpenCV? I'm quite puzzled about what to use or install, because there are a plethora of components old and new, and the relationship between them is quite unclear to me.
There is OpenCV, the C++ library that does the heavy lifting.
Then there are various packages that provide Python support, including:

*

*opencv-python - Python packages for OpenCV; also installs OpenCV itself. Available with import cv2.

*pyopencv - a very old library.

*python-opencv - a Debian package.

*libopencv, described in another question here as "only a metapackage", but its purpose remains unclear to me.

Possibly I have missed some...
For a modern Python 3 project, which of these components should be used?
Using import cv
I am trying to use OpenCV with a Django project, that expects to find the library with import cv.
That recommends installing python-opencv. It also mentions pyopencv which seems odd, given how old the latter is.
What package does make a cv module available?
System vs Python packages
It looks like python-opencv is a system-level package that also installs Python modules, whereas opencv-python is a Python package that also installs system-level modules.
Is that correct? In which case, am I right in thinking that one would install both system and Python libraries using one of these but not both?

A: in opencv3 the old cv or cv2.cv api was removed, to use opencv correctly in python is enough with import cv2.
another package would be opencv-contrib-python


Q: How to insert COUNT value of another table in column of a table Hey I have a two tables
Likes

And other table
Comments

I want to total likes  in comment table . How can i achieve this . I just write fake query in comments table just for understanding i want effect like that , any ideas please

A: INSERT INTO Destination(Col)
SELECT COUNT(1) FROM Source;

A: You can use triggers to automatically update comments tables based on likes table.
The following in an Insert After Trigger which will increment the value of total_likes of the corresponding comment_id by one in comments table when an insert in performed in likes table.
You have to give initial value of total_likes for comments as zero when inserting in comments table.
CREATE TRIGGER update_likes AFTER INSERT ON likes
FOR EACH ROW
  UPDATE comments
     SET total_likes = total_likes+1
   WHERE comment_id = NEW.comment_id;

A: If you want a query that resolve this.
I suggest some like this:
select comment_id,uploader,
(select count(*) from likes l where L.COMMENT_ID =CM.COMMENT_ID ) nlikes
from commments cm;


Q: Probability of having 2 cards in hand knowing the probability of having 1 Given (per player):
1 deck of 30 cards
15 different cards, so there are always 2 identical cards (let's name them ONE, TWO, ..., FIFTEEN)
1 hand of 5 cards (drawn from the deck)
I was wondering the following:
At one point, I know that there is a probability p (this is given, don't try to compute it) that my opponent has at least one of the two cards ONE in his hand. I cheat and try to look at his hand, and I can only see one card, which is a ONE. What is the probability that he has the second ONE in hand too at this moment?

Is it possible to solve this problem? If yes, how and what is the solution? If no, what information is missing?
Thank you in advance for your help,
Valentin

A: The opponent has $4$ more cards out of $29$ possible cards.
The probability that he has the second ONE-card is $\frac{4}{29}$. This can be calculated by $$\binom{28}{3}/\binom{29}{4}$$ ($\binom{29}{4}$ possible distributions and $\binom{28}{3}$ possible distributions , if the opponent has both ONE-cards of his deck).


Q: C, Fast way to limit a number to <= 64 Which is the fastest way to limit a number to 64 inclusive (ie. <= 64)
len = len > 64 ? 64 : len; /* limit to 64 */

Thanks!

A: Don't bother. The compiler optimizes better than you could.
You might perhaps try
len = ((len - 1) & 0x3f) + 1;

(but when len is 0 -or 65, etc...- this might not give what you want)
If that is so important for you, benchmark!

A: I created a program
#include <stdio.h>

int main(void) {
    unsigned int len;
    scanf("%u", &len);
    len = len > 64 ? 64 : len;
    printf("%u\n", len);
}

and compiled with gcc -O3 and it generated this assembly:
cmpl    $64, 4(%rsp)
movl    $64, %edx
leaq    .LC1(%rip), %rsi
cmovbe  4(%rsp), %edx

the leaq there loads the "%u\n" string in between - I presume it is because the timing of the instructions. The generated code seems pretty efficient. There are no jumps, just a conditional move. No branch prediction failure.
So the best way to optimize your executable is to get a good compiler.


Q: how to display json data using ng-repeat? I am trying to Json data using ng-repeat. But the web page is either showing as white page or a blank page.
The Json:
{
    "questions": {
            "q1": {
                "qText": " question1",
                "result":"result1",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            "q2": {
                "qText": " question2",
                "result":"result2",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            "q3": {
                "qText": " question3",
                "result":"result3",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            "q4": {
                "qText": " question4",
                "result":"result4",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            "q5": {
                "qText": " question5",
                "result":"result5",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            "q6": {
                "qText": " question6",
                "result":"result6",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            }

        }
    }
}

The HTML:

{{question.qText}}

        <input type="radio"  ng-model="qobj.q1" ng-value="'A'" >{{question.options.A}}
        <input type="radio"  ng-model="qobj.q1" ng-value="'N'" >{{question.options.N}}
        <input type="radio"  ng-model="qobj.q1" ng-value="'D'" >{{question.options.D}}
        <input type="radio"  ng-model="qobj.q1" ng-value="'NA'" >{{question.options.NA}}

A:
Check whether your questions object is in scope.

angular.module("test", [])
  .controller('ctr1', function($scope) {
    $scope.save = function(ques){
      $scope.showAnswer=true;
    }
    $scope.ques = {
      "q1": {
        "qText": " question1",
        "result": "",
        "options": {
          "A": "option1",
          "N": "option2",
          "D": "otpion3",
          "NA": "option4"
        }
      },
      "q2": {
        "qText": " question2",
        "result": "",
        "options": {
          "A": "option1",
          "N": "option2",
          "D": "otpion3",
          "NA": "option4"
        }
      },
      "q3": {
        "qText": " question3",
        "result": "",
        "options": {
          "A": "option1",
          "N": "option2",
          "D": "otpion3",
          "NA": "option4"
        }
      }
    }
  })

  <form name="testForm">

        {{q.qText}}
        <input type="radio" ng-model="q.result" ng-value="q.options.A" />{{q.options.A}}
        <input type="radio" ng-model="q.result" ng-value="q.options.N" />{{q.options.N}}
        <input type="radio" ng-model="q.result" ng-value="q.options.D" />{{q.options.D}}

    <input type="submit" ng-click="save(ques)" value="Submit" />
  </form>

        {{q.qText}}== {{q.result}}

A: Your json does not contain an array, but an object with other objects. Therefore you must let angular know to iterate through its keys:

A: I see what you are trying to do!
Your model says :
`"questions": {
            "q1": {...}
            },
            "q2": {...},
            ...
}`

so, questions should be an Array for ng-repeat to work with it!
Just a guess, I don't think you will need "q1", "q2" tags at all..
Modify your "questions" model to this:
`"questions": [
             {
                "qText": " question1",
                "result":"result1",
                "options":{
                    "A":"option1",
                    "N":"option2",
                    "D":"otpion3",
                    "NA":"option4"
                }
            },
            {...},
            {...},
            {...}
]`

Remember: ng-repeat is well suited for Collections, and is not meant for Objects.
Hope this serves your purpose!


Q: Extremely low HDD read/write speed I have built myself a small Ubuntu home server to store all my files, but one of my HDD has extremely low write speed (between 1 and 3 MB/s) and it's killing me because it's a 4TB drive and I have almost 2.5TB of data to put on it. Let me explain :
I bought my server with the following specs :

*

*CPU : Intel Pentium G3440

*MB  : Asus H87M-E C2

*RAM : Corsair 2 x 2GB DDR3

And with the following drives (one partition on each drive) :

*

*SSD (sda) : Kingston HyperX 120GB SATA3

*HDD (sdb) : WD Green 4TB SATA3

*HDD (sdc) : Seagate ST4000 4TB SATA3

*HDD (sdd) : WD Green 3TB SATA3

I installed Ubuntu 14.04 (with GNOME) on the SSD, and "salvaged" the Seagate 4TB drive from my Windows 7 x64 computer and it was full of data. It was partitionned in NTFS, and had Compression active (gained a couple of GB with this).
When I moved it to my server, I emptied it into the other drives (took me around 3 weeks, at an average speed of 2MB/s). I thought the low read speed was due to the fact that I was transferring from (compressed) NTFS to Ext4. Now that I have emptied the drive, and reformated it to Ext4 I assumed it would be much better, but when I tried to copy back some of the files, I saw that the average speed was still similar (around 2MB/s). So tried some other copies to test the speeds between the other drives, and all copies I try doing between the 3 large capacity drives (sdb, sdc, sdd) go slower than 2.7MB/s (sometimes as slow as 1MB/s).
Is there something I'm missing here ? Either Ubuntu configuration, partition settings, fstab parameters...
Please comment if you need me to post the result of some command. Here are the few I could think of (will edit if/when I have some new informations) :
/etc/fstab contents
#sdb1
/dev/sdb1 /media/tv         ext4    user,sync,auto,rw   0   0

#sdc1
/dev/sdc1 /media/tvarchive  ext4    user,sync,auto,rw   0   0

#sdd1
/dev/sdd1 /media/medias     ext4    user,sync,auto,rw   0   0

smartctl -H -i /dev/sdc
rgo@ATLAS:~$ sudo smartctl -H -i /dev/sdc
smartctl 6.2 2013-07-26 r3841 [i686-linux-3.13.0-44-generic] (local build)
Copyright (C) 2002-13, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Family:     Seagate Desktop HDD.15
Device Model:     ST4000DM000-1F2168
Serial Number:    Z300RC7R
LU WWN Device Id: 5 000c50 0647493a8
Firmware Version: CC52
User Capacity:    4 000 787 030 016 bytes [4,00 TB]
Sector Sizes:     512 bytes logical, 4096 bytes physical
Rotation Rate:    5900 rpm
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   ATA8-ACS T13/1699-D revision 4
SATA Version is:  SATA 3.1, 6.0 Gb/s (current: 6.0 Gb/s)
Local Time is:    Sun Jan 25 13:39:15 2015 CET
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

hdparm -Tt
rgo@ATLAS:~$ sudo hdparm -Tt /dev/sdc
[sudo] password for rgo:

/dev/sdc:
 Timing cached reads:   16144 MB in  2.00 seconds = 8080.82 MB/sec
 Timing buffered disk reads: 446 MB in  3.00 seconds = 148.67 MB/sec

hdparm -v
rgo@ATLAS:~$ sudo hdparm -v /dev/sdc

/dev/sdc:
 multcount     = 16 (on)
 IO_support    =  1 (32-bit)
 readonly      =  0 (off)
 readahead     = 256 (on)
 geometry      = 486401/255/63, sectors = 7814037168, start = 0

A: Excuse me if my question is stupid, but did you connect your HDDs to motherboard via SATA cables, not USB, right?
The next question is why you have 'sync' in /etc/fstab? I dont have one in mine. Please try without this.


Q: Grant user permission to create new schema but not view existing schema Is there a way to allow the user to create new schemas (and acquire privileges to schemas he created), but not view existing schemas (or a way to blacklist a list of schemas that the user is not able to see)?
The CREATE privilege will allow the user to create new schemas, as well as viewing all the existing schemas (though not altering them), which is undesirable.


Q: ways to run external shell commands in sbt How can I run external shell commands once I am in sbt interactive shell?
That is, after I type sbt and see the prompt showing up, how can I do things like ls, or cd etc.? There should be a way to do this, correct?
Thank you.

A: On http://www.scala-sbt.org/release/docs/Community/Community-Plugins.html is a list of SBT plugins.
A plugin for your purpose can be https://github.com/steppenwells/sbt-sh .


Q: Doctrine many-to-one association keeps pulling all rows from associated table I'm attempting to set up a many-to-one relationship between a series of sales memos and transaction records.
/**
 * @var TransactionInterface
 *
 * @ORM\ManyToOne(targetEntity="Twb\Common\Model\Broker\TransactionInterface")
 * @ORM\JoinColumn(name="FormNoSeller", referencedColumnName="Form")
 */
private $formnoseller;

/**
 * @var TransactionInterface
 *
 * @ORM\ManyToOne(targetEntity="Twb\Common\Model\Broker\TransactionInterface")
 * @ORM\JoinColumn(name="FormNoBuyer", referencedColumnName="Form")
 */
private $formnobuyer;

They are split between two different bundles at the moment ('SalesBundle' and 'BrokerBundle'), and with that in mind I am using interfaces from the SalesMemo entity in SalesBundle to the Transaction entity in BrokerBundle.
For some reason, when I reference either or both of $formnoseller and $formnobuyer in my forms, I notice in dev.log that, after selecting all Transaction rows matching the $formnoseller and/or $formnobuyer fields in the SalesMemos, Doctrine tries to SELECT all rows in the Transaction table (the entity for which TransactionInterface references). This is a bit of a problem, since there is an innumerable amount of rows in the DB, which takes up a lot of memory.
Is there any way to have Doctrine avoid selecting all rows with associations? Or am I even understanding properly how Doctrine does associations? Many thanks for any help.

A: My understanding of your problem is that you're using an Entity Field Type for $formnoseller and $formnobuyer (or you don't specify the type). Giving the choice to select any élément from the underlying table is the expected behaviour for the Entity Field Type (Used by default for OneToMany relationships)
If you don't whant a select list of all the elements of your table for those Fields, you should use an other form field type. You should also have a look at data transformers in the documentation.

A: If it were me, I would write a stored procedure and do an inner or outer join as appropriate.
Once upon a time, they called this "client server" code.  About 15 years ago, it created such a mess the whole industry moved to n-tier development.  I'd like to know how the table joins got placed back into the presentation tier again?  ORMs and LINQ-to-SQL are a return to client/server".
If you have to do it this way, do the join in LINQ on the Models.  Do not do it with the ORM language.


Q: WPF Scale Transform and ScrollViewer - When Zoomed can't scroll beyond original size I have a StackPanel inside of a ScrollViewer.
I have a slider that does a scale transform on the stackpanel to allow zoom-in and zoom-out functionality.  The problem is that when I zoom in, the scrollviewer doesn't treat the content as being 'bigger'.
So, if I scroll in a little and scroll as far right as I can go - it stops me before I get to the end of the content.  If I zoom back out to the untransformed level, I see that it's stopping exactly at that point.  If I zoom in a lot, I can only see a small fraction of my total content when I scroll all the way over.
I can change the TransformOrigin to control which side loses the most content; but I figure there should be some way for the scrollviewer (or another control?) to take care of it for me.

A: Are you doing render transform, or layout transform? You should be doing the latter.


Q: jRuby on Rails vs Grails I'm looking to develop a greenfield web application which will reuse a lot of Java components.  To me, the obvious options for this are Grails or jRuby on Rails, but I'm having trouble finding objective comparisons of the two.  Are there any clear reasons to pick one over the other with respect to:

*ease of integration with existing Java components (outside the persistent domain), e.g. JMS, EIP

*support for functional testing frameworks

*performance on a single machine

*scalability

I am not looking for answers relating to the availability of developers or activity of communities.

(I've checked Grails vs. Rails, and it's not relevant to me)

A: I know Grails very well (right now I'm working on a Grails project), but not JRuby, so take this as a probably biased opinion: looking at the JRuby documentation, it looks that JRubys integration with Java is a bit more cumbersome, since Java is more native in Groovy than it is in Ruby; therefore, in JRuby, you have a lot of java-specific keywords and methods (e.g. java_import, java_send). Put simply, Groovy is a language targeted specifically at the Java world, while JRuby is, well, Ruby put on the JVM.
Grails has JUnit tests built in.
Can't say much about performance and scalability, but given the good integration with Java, one can always write performance-critical parts in Java when Groovy is too slow.

A: *

*ease of integration with existing Java components:

it's easier with groovy, cause groovy is basically java. you do not have big context-switches

*

*support for functional testing frameworks

ruby has it's own pile of testing frameworks like rspec/shoulda/cucumber/steak and tons more. since i like ruby syntax i would prefer those

*

*performance on a single machine

as far as i know, grails is better in multithreading, because rails did not fokus too much on that in the past. they are currently catching up, so it might be tie.

*

*scalability

both scale with the jvm environement. if you have a running infrastructure for java, grails is easier to integrate.

A: *

*As phoet said, Grails has first-class Spring support, so it's typically very easy to integrate Spring libraries - that's what many plugins do, including the JMS plugin.
Java code can either be provided in JARs or put in to the project's src/java directory. Groovy classes can reference Java classes which can reference Groovy classes. It's pretty seamless.

*Grails has support for HtmlUnit, Selenium-rc & WebDriver through various plugins. Geb has a lot of interest at the moment, especially when combined with Spock.

*Test them. I don't know if there are any recent comparisons, but performance typically depends heavily on your application. http://grails.org/ and http://beta.grails.org/ are both running on a single machine - and both are Grails applications.

*I gather it's pretty easy to cluster Grails via Terracotta. You can also do it with plain Tomcat if you want. There are options for distributed caching - SpringSource has its own (commercial) offering in the form of GemFire.
Hope that helps, and in the interests of full disclosure I'm a member of the Grails team.

A: In the end, you are going to make a decision on personal choice, comfort with the two languages and the availability of resources, but in the end, the fact that Grails is based on Spring led me to the conclusion that it was the right choice for me. I knew that if all else failed I could fall back to utilizing the tried and true Spring Framework

A: Try both, and pick the language and environment that suits you best. It's true that the Grails stack out of the box is more suited towards Java integration, but many components are just a few lines of Ruby code away from integration with Rails. Rails 3 is a great release that doesn't require you to use ActiveRecord, in fact it would be trivial to use Hibernate for your models instead. See also DataMapper, MongoMapper and a whole host of database adapters for SQL and NoSQL databases alike.
Also, JUnit != functional testing. Instead, have a look at Cucumber + Cucumber-Rails + Capybara + Selenium for an integrated browser automation testing experience. Take a look at https://github.com/elabs/front_end_testing for an example application that demonstrates this stack.
I'll suggest that Ruby is better suited as a web integration language, and JRuby hits the sweet spot of making integration with Java easy as well as pleasing while making a wealth of non-Java libraries available to you. Don't think that Groovy automatically wins because it's "closer" to Java. Sometimes you need to step into a refreshingly different environment in order to have a new look at how to solve a problem.
Disclosure: as a member of the JRuby team my bias is evident in my answer.

A: For newcomers interested in this question in 2012...
"With the @CompileStatic, the performance of Groovy is about 1-2 times slower than Java, and without Groovy, it's about 3-5 times slower. (...) This means to me that Groovy is ready for applications where performance has to be somewhat comparable to Java."
Performance Test: Groovy 2.0 vs. Java http://java.dzone.com/articles/groovy-20-performance-compared
And besides the autor, I've used Groovy since 2008 with great success, not only for CV, just to make job done in time business need. Performance is ever relative to what you want to do.
About integration, Grails is really "that good". I've never needed to make one step further to integrate it with existing libraries. On the contrary, the Spring-based nature of Grails made the job even easier.
For those who could complain about micro-benchmarks and real use cases, here is a somewhat old (Grails 1.8) but good one with web frameworks (Grails 1.3.7): http://www.jtict.com/blog/rails-wicket-grails-play-lift-jsp/
Hope this helps!
PS.: I would like to see recent benckmarks with JRuby and other really dynamic JVM languages.


Q: Downcast of function call failing in Swift I have a dictionary that contains function calls plus a generic method for adding functions to that dictionary. The moment I downcast that generic function so that I can add it to the dictionary, the compiler crashes.
You can see that when you put the following code in a playground:
import Cocoa

class Email:NSObject {
    var Subject:String = ""
}
class SMS:NSObject {
    var Message:String = ""
}

var allfunc = Dictionary<String, (item: NSObject) -> Void>()

func test<T:NSObject>(type:T, myfunc:(item: T) -> Void) {
    allfunc[NSStringFromClass(type.dynamicType)] = myfunc as? (item:NSObject) -> Void
}

test(Email(), {item in NSLog("\(item.Subject)")})
test(SMS(), {item in NSLog("\(item.Message)")})

for (key: String, value: (item: NSObject) -> Void) in allfunc {
    if key == NSStringFromClass(Email().dynamicType) {
        var mail = Email()
        mail.Subject = "testing mail"
        value(item: mail)
    } else {
        var sms = SMS()
        sms.Message = "testing SMS"
        value(item: sms)
    }
}

When I change the test function to this then I't won't crash, but I will lose autocomplete:
func test<T:NSObject>(type:T, myfunc:(item: NSObject) -> Void) {
    allfunc[NSStringFromClass(type.dynamicType)] = myfunc
}

Is this a compiler bug that you cannot downcast functions, or shouldn't it be possible anyway?
Is there an alternative that I can use to create similar functionality?
Maybe the code in the playground looks a little strange. It's a modified extract from my project. If you want to see the complete project with the same crash, then have a look at https://github.com/evermeer/EVCloudKitDao

A: You can not cast functions. In the current Xcode version 6.2 you will get the following run time exception: Swift dynamic cast failure
There is however a workaround for this problem which I implemented in my connect function of https://github.com/evermeer/EVCloudKitDao The solution is to wrap the function instead of casting it. The code will look like this :
public var insertedHandlers = Dictionary<String, (item: EVCloudKitDataObject) -> Void>()
public var updateHandlers = Dictionary<String, (item: EVCloudKitDataObject, dataIndex:Int) -> Void>()

public func connect<T:EVCloudKitDataObject>(
    type:T,
    completionHandler: (results: [T]) -> Void,
    insertedHandler:(item: T) -> Void,
    updatedHandler:(item: T, dataIndex:Int) -> Void,
    deletedHandler:(recordId: String, dataIndex:Int) -> Void,
    errorHandler:(error: NSError) -> Void
    ) -> Void {
        func insertedHandlerWrapper(item:EVCloudKitDataObject) -> Void {
            insertedHandler(item: item as T)
        }
        func updatedHandlerWrapper(item:EVCloudKitDataObject, dataIndex:Int) -> Void {
            updatedHandler(item: item as T, dataIndex: dataIndex)
        }
        self.insertedHandlers[filterId] = insertedHandlerWrapper
        self.updateHandlers[filterId] = updatedHandlerWrapper
        ...

Now the updateHandler still uses the T instead of the EVCloudKitDataObject and in the handler itself you can use the original type and does not need to cast it.


Q: Access 2007 Encrypted BackEnd Slow Only With New ACCDB I have encrypted back-end ACCDB on Win/2003 network.
Front-end on user workstations.  Link tables and make copies.  All works perfectly.
I open a fresh blank database and link to same back-end.  It is extremely slow, but only from a new front-end.  Clicking on any tables takes forever to launch.
It appears to be a problem only if other users have the front-end application open.
I have tried renaming the blank DB to match the one that works; no difference.
It appears that if you open one front-end to a back-end ACCDB then another front-end (such as a blank ACCDB with fresh links) to the same back-end experiences serious latency.
Any ideas on what might be going on here?

A: The solution is to maintain a persistent connection.
You want to open a table that is very small (maybe just one record) and keep that open.  Then everything else responds quickly.
You can also open a form that has a small table as its recordset, as long as it keep the connection open/persistent.


Q: Context menu not working on CSS table I have a table on my webpage. I recently changed this from a HTML table to a CSS one. I have a context menu that displays on each row of my table. The context menu was working on the HTML table but not the CSS one.
HTML: (sample of CSS table)

<%= products[i].productOwner %>

<%= products[i].engineeringOwner %>

<%= products[i].engineeringLead %>

    ...

#contextMenu:

Edit

Delete

jQuery:
$(document).bind('contextmenu', function (e) {
    e.preventDefault();
    e.stopPropagation();
    recordID = $(e.target).parent().attr('id');
    if ($(e.target).hasClass('td')) {
        $('#contextMenu').css({
            left: e.pageX + 'px',
            top: e.pageY + 'px'
        }).show().fadeIn(500, startFocusOut());
    }
    return false;
});

I have debugged and confirmed that $(e.target) does have td class so the if statement should be entered


Q: Authorization architecture in microservice cluster I have a project with microservice architecture (on Docker and Kubernetes), and 2 main apps are written in Python using AIOHTTP and Django (also there are and Ingress proxy, static files server, a couple more made with NginX). I'd like to split these Python apps into separate smaller microservices, but to accomplish this probably I also should move authentication in a separate app. But how can I do this?
Probably I should also add that I'm asking not about specific authentication methods like OAuth, JWT, etc, but about dependencies and responsibilities splitting inside cluster architecture.
To my mind, a nice solution would be some plugin to Ingress NginX proxy server, or a microservice before it, so that my Python authenticating proxy won't care about methods destination, like some middleware, just read headers/cookies, check access token or sessionId, then set userId if the access is valid, and pass the request further.
A brief and simplified architecture is presented below:

And here is what I imagine, mention fewer complicated connections:

But I'm not sure if this is reasonable. In addition, such approach would reduce advantages of K8s Ingress, which provides amazing interface for updating path table from the bash, but, as far as I know, doesn't allow to run any request handler before it, so I'll have to run custom NginX proxy without nice K8s integration.
Thus, what are other possible architectural solutions?
I could only imagine creation of a single request handler, that performs all the authorisation and passes requests to other microservices (or by RPC), which don't care about authentication, but I don't think this is a generally perfect solution.

A: Theory
Well, I found a lot of info after digging on the Internet and one and a half of consultations. There is an architectural pattern named API Gateway, which describes an entry point in a cluster, and this is just what Kubernetes Ingress does, and what I imagined in my question. In a general case, it is proxy server, which is the only entry point to the cluster microservices, and it may perform caching, DDoS protection, it may support different API protocols, manipulate URIs, manage API throttling, monetisation, and perform the authentication I need. Therefore, there is no authentication during microservices communication inside the cluster, because all the required arguments, identifiers will be presented in the requests.
Implementation
In Kubernetes, NginX Ingress is quite popular, it also supports Basic Auth and OAuth2, which is not a perfect solution, but at least something. There are alternative Ingress solutions for Kubernetes: Kong, Ambassador, Traefik, which provide much more features (though Kong is based on NginX too).
In the world of Java and Spring the Spring Cloud Gateway exists to solve such problems, which, just like K8s Ingress, allows to describe path tables with YAML, yet it is extendable, allows to easily embed your custom code for any authentication method.
Besides, most of cloud platforms provide their own API gateway services with more or less features, including Google Cloud, Red Hat, AWS, Yandex Cloud. However, it seems they lack authentication methods just like opportunity to be extended, though they aren't much relevant in this question.
To read
You can find more about API Gateway pattern and it's implementations here:

*

*microservices.io: API Gateway pattern

*RedHat: What does an API gateway do?

*kubernetes.github.io: NginX Ingress External OAUTH
Authentication

*learnK8S.io: Kubernetes API Gateway

*cloud.spring.io: Spring Cloud Gateway

A: With microservices, JWT are preferred way of authentication & authorization.
You can use cloud resources like GCP IAM or OKTA. OR you can run Keycloak in your cluster as a microservice.

*

*User is created in one of these resources.

*Once the user has authenticated, a JWT token is returned (to
frontend).

*Token contains authentication & authorization related info for that
user.

*This token is again sent from frontend to backend services in each
request.

*Backend service will check authentication and authorization and
respond accordingly.

Also token is normally valid for fixed amount of time. So frontend app should refresh the token periodically.


Q: Imagemagick issues with Ruby I'm trying to run a ruby script from the command line, and getting the following error:
/Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require': dlopen(/Users/.../.rvm/gems/ruby-1.9.2-p320@stitching_cron/gems/rmagick-2.13.2/lib/RMagick2.bundle, 9): Library not loaded: /opt/local/lib/libMagickCore.6.dylib (LoadError)
I've installed ImageMagick using
brew install imagemagick

and the command line utilities are available as expected. Not sure what's happening here.
I tried running
sudo find / -type f -name "libMagickCore.6.dylib"

to see if I can perhaps symlink the file into the location Ruby is looking for the library, but couldn't find it...
Any idea how to fix?

A: try this:
rvm get head
rvm pkg remove
rvm reinstall 1.9.2-p320 --with-opt-dir=$(brew --prefix imagemagick)


Q: Fastest solution to use FTP/Aspera/MediaShuttle with SAN network At my postpro studio we have a SAN Network (Stornext 6). There is also a MediaShuttle and FTP server in a VM on the firewall (I know, I know... Not my fault, really xD).
The VM is sharing SAN over CIFS so everytime we need to send some files we need to upload them to the MediaShuttle or FTP server at 1Gbps Ethernet speed, witch is awful when u try to upload for example 200Gb. It takes 5h or so if the VM doesn't hang in the process.
My ABSOLUTLY TEMPORAL solution to this mess is using a Windows SAN client with a Storage Server for Mediashuttle. This put the transfer process to an affordable 45 mins.
This is just temporal because something like MediaShuttle/FTP/Aspera needs to go to the DMZ and never directly connected to the SAN network. Also Netflix, HBO and the TPN (Trusted Partner Network) forbids you to do that.
I was thinking about having a server on the DMZ connected to the Firewall thought a 10Gb cards and then another 10Gb card to our SAN. It won't be as fast as directly connected to the SAN but... I cannot think on a better solution for this.
Am I missing something?
Thank you all!

A: Dedicated, fully utilized 1 gigabit link should be getting better than quarter terabyte (250 GB) per hour. If not, you have a bottleneck.
Check link speed and utilization of all IP and storage network links. Both physical and virtual. Plus disk, CPU, and firewall utilization. Sample a small packet capture to check that IP is performing optimally.

Consider 25 Gbit Ethernet from workstations all the way to the storage array. Adapters may only a little more expensive than 10 Gbit.

A: Concerning Aspera transfer, IBM provides a proxy server Aspera Proxy Server that allows external users to securely get the files directly but securely from the storage without a copy.


Q: Как настроить приём платежей на сайте через qiwi Уже два дня ищу, пробую и толку ноль.
Пробовал этот класс https://github.com/atnartur/php-qiwi, но выдаёт ошибку: Ошибка: Прием платежа для данного провайдера запрещен.
Если посылаю просто get запрос, как показано на сайте qiwi, то выдаёт: Ошибка: Провайдер не поддерживается.
Уже не хватает слов, популярный сервис не может дать нормальное и понятное api, нет никаких примеров.
Подскажите кто в курсе, как можно настроить или где посмотреть?


Q: jQueryUI droppable and sortable - cant change the order and few bugs i cant fix I have put most of the code together, just cant get few things working: -

*

*Items in the "Selected DVD's" area I need to be able to change the order of these DVDs in this list only, so i can change the order from 1,2,3 to 3,1,2.

*Items in the "Un-selected" area wont drag up into the selected dvds area

*If i click on the link at the top "add all unselected dvd's" and then click on the link "Remove all selected dvds" it doesnt add them into the correct area at the bottom. However if you click the "Remove all selected dvds" link first... it works

*Following #3 if i then add a new dvd at the top right, sometimes it adds loads of the same dvd?
Here is a working demo of what i have so far:
http://jsfiddle.net/BFWzS/1/
There is more code in the fiddle above ^
// let the gallery items be draggable
$( "li", $gallery ).draggable({
  cancel: "a.ui-icon", // clicking an icon won't initiate dragging
  revert: "invalid", // when not dropped, the item will revert back to its initial position
  containment: "document",
  helper: "clone",
  cursor: "move"
});

// let the trash be droppable, accepting the gallery items
$trash.droppable({
  accept: "#gallery > li",
  activeClass: "ui-state-highlight",
  drop: function( event, ui ) {
    deleteImage( ui.draggable );
  }
});

Hope someone can help us out,
Cheers

A: As my comments have suggested, you should break this down into more specific problems and ask them as separate questions. But here is some information to help you out:

*

*Check out JQuery Sortable

*Check out the Connect Lists option [EDIT] In your JSFIddle, your problem doesn't exist for me (in Chrome)

*This should be a separate question (although you can probably find a duplicate of this already)

*If not solved by your answer to 3, then should be an additional question

For the purposes of a more meaningful answer, here is some sample code showing the use of JQuery Sortable:

Selected DVDs

DVD 1

DVD 2

DVD 3

Un-selected DVDs

DVD 4

DVD 5

DVD 6

$("#gallery").sortable({
    connectWith: "#trash"
});
$("#trash").sortable({
    connectWith: "#gallery"
});

You can see this in action here.


Q: Is it possible to delete or invalidate gecko / firefox session without closing browser? Is it possible, using the gecko / firefox XPCOM interfaces, to delete or invalidate a user's active session without closing the browser? I am using Gecko embedded (specifically GeckoFX) in an application where it is possible that multiple users might use the browser component across the lifetime of the application.
The application packages web browsing with various other functionality, and when the web browser is 'closed', the app remains open. It seems that as far as the gecko engine is concerned, as the process hasn't closed, the active session is still active. If a user is to log into Gmail or Facebook, for instance, and then close the browser, upon reopening the browser and navigating back to one of those pages, that user is determined to still be logged in. As multiple users can use the application without the application actually exiting, this raises privacy issues.
I have tried calling NS_InitXPCOM2 and NS_ShutdownXPCOM within the constructor / dispose method of the browser control, however NS_InitXPCOM2 cannot be called after NS_ShutdownXPCOM within the lifetime of the process, so this simply crashes.
I have also used the PurgeHistory method of nsISHistory and the evictEntries method of nsICacheService - none of these appear to have an immediate effect within the life of the process.
Does anyone know of any XPCOM interfaces that can achieve this? Alternatively, any pointers in direction of similar functionality, be it through XPCOM interfaces or Firefox extensions would be greatly appreciated (are there any extensions that allow you to clear your current browsing session without reopening the browser? or that provide you a different session between each Firefox window / tab?)
The program is written in C#, however answers in any language are appreciated.
Many thanks

A: I finally found the interface that seems to allow this: nsICookieManager removeAll()
Relevant C# interfaces / code for those using GeckoFX:
[Guid("AAAB6710-0F2C-11d5-A53B-0010A401EB10"),
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface nsICookieManager
{
    void removeAll();
    void remove(string aDomain, string aName, string aPath, bool aBlocked);
}

and Xpcom.GetService<nsICookieManager>("@mozilla.org/cookiemanager;1").removeAll(); in appropriate location.


Q: Can cURL use a keyring for client certificates? I'm using cURL to fetch from an HTTPS location, which requires a client certificate.  I have my .curlrc set up to tell cURL where it is, but I don't want to leave my unencrypted private key just lying around.  So every time I use it, cURL prompts me for the certificate  password.
A lot of other utilities hook into some kind of platform-specific keyring (the native one in OSX, gnome-keyring in Linux, etc) -- is there a hook like this for cURL?  Is there any other way to have cURL get my private key on a per-shell / per-session basis rather than prompting every time?

A: Private keys stored in GNOME Keyring (not key passwords, but the keys themselves) can be accessed using a standard PKCS#11 interface, preferably through p11-kit (pkcs11 module libp11-kit.so). This can be used from various programs.
However, curl unfortunately does not appear to support PKCS11 modules, even though the OpenSSL library itself is able to use them. This might have something to do with some distros building curl with GnuTLS or NSS instead...


Q: How to send an email with attachment in C# I created a button that changes the name of fields on a word document.
Now I'd like to send that document in an email with the same button. I looked at many tutorials but none of them were successful
private void button2_Click(object sender, EventArgs e)
{

    var application = new Microsoft.Office.Interop.Word.Application();
    var document = new Microsoft.Office.Interop.Word.Document();

    document = application.Documents.Add(Template: @"D:\test\test.docx");

    application.Visible = true;

    foreach (Microsoft.Office.Interop.Word.Field fush in document.Fields)
    {
        if (fush.Code.Text.Contains("Name"))
        {
            fush.Select();
            application.Selection.TypeText(txtE.Text);

        }
        else if (fush.Code.Text.Contains("LastName"))
        {

            fush.Select();
            application.Selection.TypeText(txtM.Text);
        }

        document.SaveAs(FileName: @"D:\test\testsave.docx");

    }
}

A: Straight from the horses mouth:
public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
                    ex.ToString() );
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }


Q: Apache shows blank white page after 2 to 10 hours I am using ubuntu 12.04, it has to network cards, A = internal 10.0.0.0 and B public Ip , I have only apache2 installed, after 2 to 10 hours the website shows as a blank white page on the public network but continues to appear normally on the private 10.0.0.0 network, if I login or sometimes restart apache or the server the site comes back on the public network, but after 2 to 10 hours will become a blank white page and in chrome sometimes err_empty_response. the apache logs show no problems, the external firewall is setup and working properly, there is no port forwarding and the gateway on the server is correct. this is driving me crazy now, I have reinattled multiple times, removing php on the next install, I have 3 seperate servers all doing the same thing, I have a 4th email server which is fine, no problems, and 2 nameservers with no problems, all ubuntu 12.04, this problem appeared about 3 months ago after the servers were working fine for 6 months, it just started, i had posted a similar post and closed it assuming it wasnt an ubuntu problem bu this has to be. not sure if it could be a security issue. I have performed the following security on all 3.
Secure shared memory
vi /etc/fstab
tmpfs     /dev/shm     tmpfs     defaults,noexec,nosuid     0     0
SSH Hardening
vi /etc/ssh/sshd_config
PermitRootLogin no
Protect su by limiting access only to admin group.
sudo groupadd admin
sudo usermod -a -G admin my-username
sudo dpkg-statoverride --update --add root admin 4750 /bin/su
Harden network with sysctl settings
IP Spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts = 1
Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
Block SYN attacks
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5
Log Martians
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
Prevent IP Spoofing
vi /etc/host.conf
order bind,hosts
nospoof on
Then in apache I performed the following
installed it
apt-get install apache2
Disable Directory Listings
/etc/apache2/conf.d/security
ServerToken Prod
ServerSignature Off
Disabling unnecessary modules
a2dismod status
a2dismod autoindex
rm -f /etc/apache2/mods-enabled/autoindex.load
rm -f /etc/apache2/mods-enabled/autoindex.conf
rm -f /etc/apache2/mods-enabled/dav.load
rm -f /etc/apache2/mods-enabled/dav_fs.conf
rm -f /etc/apache2/mods-enabled/dav_fs.load
rm -f /etc/apache2/mods-enabled/dav_lock.load
Also I have webmin installed on port 10000.
if I login to webmin or ssh into the server using putty the site appers again sometimes on the public network, keep in mind the site appears normally the entire time on the private network and also if I'm on the same subnet at the public network. it only across the net that this problem occurs, I have verizon fios with 10 public ip's.
this is my configuration, not sure if anything is creating an issue. any help would be greatly appreciated


Q: Effective way to cache GameObjects including meshes/textures? Problem:
If possible, I want to cache full GameObjects including meshes that don't exist in the assets, in a way such that I can load them roughly equally quickly as if they were just one of the assets. Even on closing and reopening the app.
Context:
I'm working on an app where I get arbitrary 3D objects from the backend like this:

*

*Download data for 3D meshes from the backend in a byte array

*Convert byte[] to GameObjects with Meshes and Texture2D etc. using a plugin (https://github.com/atteneder/glTFast).

Step 2 can take about 2 seconds per asset and uses blocking methods, so the screen freezes.
I could probably pretty easily cache the byte[] to skip the downloading step for repeated assets, but then it still freezes the entire screen, potentially for a pretty long time if there are a lot of assets.
Is there a more effective way to store the entire GameObject that the plugin creates, including meshes and textures etc. that loads (close to) as quickly as a normal asset?


Q: Formula for the curvature of a curve
Find a formula (provide your answer in terms of $f$ and its derivatives) for the curvature of a curve in $\mathbb{R}^3$ given by
  $\{(x,y,z)\ | \ x=y, f(x)=z\}$.

How will I be able to do this problem?
I know that a regular parametrization of a curve then the curvature at $\mu(t)$ is given
by: $$\kappa(t) = \left|\left|\left(\frac{\mu'(t)}{||\mu'(t)||}\right)'\frac{1}{||\mu'(t)||}\right|\right|.$$
But since $f$ is not a parametrization I don't know how to continue this problem.
Since $x=y$ and there exists a function $f$ such that $f(x)=z$ and $f(y)=z$ is it safe to assume that it is a one to one function?

A: You were given a parametric curve, but it's slightly disguised. Let $\mu(x) = (x,x,f(x))$ and then apply the formula you gave in your question, but with $t=x$. To get you started, note that $\mu'(x) = (1,1,f'(x))$. Can you take it from there?

A: Your curve lies in the plane $x=y$; therefore it is  a plane curve. Denoting the length along the first main diagonal in the $(x,y)$-plane by $s$ the curve can be written as a graph in the form
$$z(s)=f\left({s\over\sqrt{2}}\right)\qquad (s_0\leq s\leq s_1)\ .$$
For such graphs the formula for the curvature reads
$$\kappa(s)={|z''(s)|\over\bigl(1+z'^2(s)\bigr)^{3/2}}={\sqrt{2}|f''(s/\sqrt{2})| \over\bigl(2+f'^2(s/\sqrt{2})\bigr)^{3/2}}\ .$$
This means that at the point $P=\bigl(x,x,f(x)\bigr)$ the curvature is given by
$$\kappa={\sqrt{2}|f''(x)|\over\bigl(2+f'^2(x)\bigr)^{3/2}}\ .$$

A: Wikipedia gives the following for a curve $(x(t),y(t),z(t))$:
$$\kappa=\frac{\sqrt{(z''y'-y''z')^2+(x''z'-z''x')^2+(y''x'-x''y')^2}}{(x'^2+y'^2+z'^2)^{3/2}}$$

A: For a unit speed curve, the  curvature can be  simply $$  \kappa = || \ddot\gamma || $$
Or if it is regular, then $$ \kappa = \dfrac{||\ddot\gamma \times \dot\gamma ||}{||\dot\gamma||^3} $$


Q: Number of iterators depending of a variable with np.nditer I have to iterate over numpy arrays whose the number can be different at each iteration of the program. The goal is to calculate the variance between the same element of these arrays. Here is the code I wrote :
for a,s,m  in np.nditer([cost_surfaceS[i].ravel() for i in range(0,len(cost_surfaceS),1)]):
arr = [a, s, m]
    if(float(arr[0]) != float("-inf")):
        variance = np.var(arr,dtype = np.float32)
        variances.append(variance)
    else:
        variances.append(float("-inf"))

where cost_surfaceS is a list that contains all my numpy arrays. The issue is that this piece of code works for 3 numpy arrays created and I want to change the "a,s,m" in order to have a number of iterators that depends of the number of numpy arrays created (i.e. len(cost_surfaceS)) . Is it a way to do it ?

A: I agree with @Bickknght that the unpacking is unnecessary.  Don't use unpacking when dealing with an unknown or variable number of elements.
In [57]: alist = [np.arange(10), np.arange(10,20), np.arange(20,30)]

Making a list of arrays where the we don't need the ravel.
In [58]: for arr  in np.nditer(alist):
    ...:     print(arr)
    ...:
(array(0), array(10), array(20))
(array(1), array(11), array(21))
(array(2), array(12), array(22))
(array(3), array(13), array(23))
(array(4), array(14), array(24))
(array(5), array(15), array(25))
(array(6), array(16), array(26))
(array(7), array(17), array(27))
(array(8), array(18), array(28))
(array(9), array(19), array(29))

Compare this with a straight forward list zip iteration:
In [59]: for arr in zip(*alist):
    ...:     print(arr)
    ...:
(0, 10, 20)
(1, 11, 21)
(2, 12, 22)
(3, 13, 23)
(4, 14, 24)
(5, 15, 25)
(6, 16, 26)
(7, 17, 27)
(8, 18, 28)
(9, 19, 29)

The difference is that nditer makes 0d arrays rather than scalars.  So the elements have a shape ((0,)) and dtype.  Or in some cases where you want to modify the arrays (but they have to be defined as read/write.  Otherwise nditer does not offer any real advantages.
In [62]: %%timeit
    ...: ll = []
    ...: for arr  in np.nditer(alist):
    ...:     ll.append(np.var(arr))
    ...:
539 µs ± 17.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [63]: %%timeit
    ...: ll = []
    ...: for arr  in zip(*alist):
    ...:     ll.append(np.var(arr))
    ...:
524 µs ± 3.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

If you can avoid the Python level loops, things will be lot faster:
In [65]: np.stack(alist,1)
Out[65]:
array([[ 0, 10, 20],
       [ 1, 11, 21],
       [ 2, 12, 22],
       [ 3, 13, 23],
       [ 4, 14, 24],
       [ 5, 15, 25],
       [ 6, 16, 26],
       [ 7, 17, 27],
       [ 8, 18, 28],
       [ 9, 19, 29]])
In [66]: np.var(np.stack(alist,1),axis=1)
Out[66]:
array([66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667,
       66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667])
In [67]: timeit np.var(np.stack(alist,1),axis=1)
66.7 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

I've not attempted to test for -inf.
===
Another important difference with nditer.  It iterates on all elements in a flat sense - in effect it is do the ravel:
Make a list of 2d arrays.
In [81]: alist = [np.arange(10.).reshape(2,5), np.arange(10,20.).reshape(2,5), np.arange(20,30.).reshape(2,5)]

PLain iteration operates on the first dimension - in this case the 2, so zipped elements are arrays:
In [82]: for arr in zip(*alist):
    ...:     print(arr)
    ...:
(array([0., 1., 2., 3., 4.]), array([10., 11., 12., 13., 14.]), array([20., 21., 22., 23., 24.]))
(array([5., 6., 7., 8., 9.]), array([15., 16., 17., 18., 19.]), array([25., 26., 27., 28., 29.]))

nditer generates the same tuples as in the 1d array case.  Some cases that's fine, but it's hard to avoid if if you don't want it.
In [83]: for arr  in np.nditer(alist):
    ...:     print(arr)
    ...:
(array(0.), array(10.), array(20.))
(array(1.), array(11.), array(21.))
(array(2.), array(12.), array(22.))
(array(3.), array(13.), array(23.))
(array(4.), array(14.), array(24.))
(array(5.), array(15.), array(25.))
(array(6.), array(16.), array(26.))
(array(7.), array(17.), array(27.))
(array(8.), array(18.), array(28.))
(array(9.), array(19.), array(29.))

A: The zip function is a solution here, as explained by @hpaulj. Working with 2d arrays instead of 1d simply requires to use two times this function, as the following code shows :
variances = []
for arr in zip(*cost_surfaceS):
    for element in zip(*arr):
        if(float("-inf") not in element):
            variance = np.var(element, dtype=np.float32)
            variances.append(variance)
        else:
            variances.append(float("-inf"))

The -inf values are handled by the if condition that avoids computing the variance of arrays containing at least one infinity value.


Q: How to reformat dataframe using pandas? I have the following dataframe:
data = {'Names':['Abbey','English','Maths','Billy','English','Maths','Charlie','English','Maths'],'Subject Grade':['Student Name',85,91,'Student Name',82,74,'Student Name',83,96]}

df = pd.DataFrame(data, columns = ['Names','Subject Grade'])

I would like to reformat the dataframe in order for the names, subject and grades to all be in their respective columns as follows:
data2 = {'Names':['Abbey','Abbey','Billy','Billy','Charlie','Charlie'],'Subject':['English','Maths','English','Maths','English','Maths'],'Grade':[85,91,82,74,83,96]}

df2 = pd.DataFrame(data2, columns = ['Names','Subject','Grade'])

A: Hi you can use those instructions :
  df['name'] = df['Names'].mask(df['Subject Grade'] != "Student Name")
  df['name'] = df['name'].fillna(method='ffill')
  df = df.query('`Subject Grade`!="Student Name"')
  df = df.rename(columns={'Names':'Subject', 'Subject Grade':'Grade', 'name':'Names'})


Q: Best way to store long binary (up to 512 bit) in C# I'm trying to figure out the best way to store large binary (more than 96 bit) numbers in C#
I'm building application that will automatically allocate workers for shifts. Shifts can be as short as 15 minutes (but this might be even smaller in the future). To avoid double-booking of workers, I plan to have binary map of their daily time: 24 hours separated in equal chunks (15 minutes) and every chunk has a flag (0 for free, 1 for busy)
So when we try to give another shift to a worker, we can do binary comparison of workers daily availability with shift's time. Simple and easy to decide.
But C# long only allows to have up to 64 bit, and with the current set up I need at least 96 bits (24 hours * 60 minutes / 15 minutes per period).
This representation must be memory friendly, as there will be about a million objects operated at a time.
Few other options i considered:

*

*String. Memory-hungry, not simple to implement bit-wise operations

*Array of bits. But as far as I know C# does not have bit type

*Array of unsigned integers. Each array represents only part of a day. The best I can think of

Any other suggestions??
Thanks in advance!

A: Have you looked at the BitArray class? It should be pretty much exactly what you're looking for.

A: Try following,
.Net 4 has inbuilt BigInteger type
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
.Net 2 project on code project
http://www.codeproject.com/KB/cs/biginteger.
Another alternative,
http://www.codeplex.com/IntX/

A: Unless you have millions of employees that all need to be scheduled at the same time, I'd be tempted to store your 96 booleans as a char array with 0 meaning "free" and 1 meaning "busy".  Simple to index/access/update.  The rest of the employees schedules can sit in their database rows on disk where you simply don't care about "96 megabytes".
If you can find a class which implements a bit array, you could use that. (You could code one easily, too). But does it really matter spacewise?
Frankly, if your organization really has a million employees to schedule, surely you can afford a machine which has space for a 96 mB array as well as the rest of your code?
The one good excuse I can see for using bit vectors has to do with execution time cost.  If you scheduling algorithm essentially ANDs one employee bit vector against another looking for conflicts, and does that on large scale, bit vectors might reduce the computation time to do this by a factor of roughly 10 (use a two *long*s per employee to get your 96 bits).    I'd wait till my algorithm worked before I worried about this.

A: You could use and array of bytes. I don't think any language supports an array of bits, as a byte is the smallest addressable piece of memory.  Other options are an array of booleans, but each boolean I believe is stored as a byte anyway, so there would be wasted memory, but it might be easier to work with.  It really depends on how many days you are going to work with.  You could also just store the start and end of the shift and use other means to figure out if there are overlapping schedules.  This would probably make the most sense, and be the easiest to debug.

A: BitArray has already been mentioned, it uses an array of ints much like you planned to do anyway.
That also means that it adds an extra layer of indirection (and some extra bytes); it also does a lot of checking everywhere to make sure that eg the lengths of two bitarrays is the same when operating on them. So I would be careful with them. They're easy, but slower than necessary - the difference is especially big (compared to handling the array yourself) for smallish bitarrays.


Q: How to add css of a div when checkbox checked? The Code:

#menu-open:checked ~ .logoib {
  -webkit-filter: invert(100%);
  filter: invert(100%);
}

<input type="checkbox" id="menu-open">

  Home
  My Works
  Contact

I want to add some CSS of #logo when the checkbox of menu is checked.

A: css cant affect anything before it, it can only affect stuff after the targeted element change like below

#menu-open + #logo {
  color: #ccc;
  font-style: italic;
}
#menu-open:checked + #logo {
  color: #f00;
  font-style: normal;
}
<input type="checkbox" id="menu-open">

  my logo here

  Home
  My Works
  Contact

A: You could use pure JS, JQuery or CSS.
Here is a pure JS solution. If you want to set it also on load, you could call myFunction when the DOM is ready.

function myFunction() {
  var cb = document.getElementById('menu-open');
  var logo = document.getElementById('logo');

  if (cb.checked) {
    logo.setAttribute("class", "newClass");
  } else {
    logo.removeAttribute("class");
  }
}
#menu-open:checked~.logoib {
  -webkit-filter: invert(100%);
  filter: invert(100%);
}
.newClass {
  color: red;
}

Logo

<input type="checkbox" id="menu-open" onchange="myFunction()">

  Home
  My Works
  Contact


Q: How to include github html file in html with php ? Suppose I have a HTML file as --
https://raw.github.com/USER/PROJECT/master/file.html
How do I make it available in my website. One method will be using the rawgithub service and then using something like iframe but I want the HTML to be inherited in my website so that Google shows it in the searches.
php's include function looks like doing the trick but I don't get it to work. I simply use
include "<file_full_URL>";

A: In PHP you can use the file_get_contents() function to grab files over the internet.
$html = file_get_contents('https://raw.github.com/USER/PROJECT/master/file.html');
echo $html;

Your pages will be slower if you do this, though. Setting up a cronjob that downloads the file to your server periodically, and then serving it from your server, is a much better idea.

A: $url = "http://www.example.com"; //write your raw.github.com URL
$gethtml = file_get_contents($url);
echo $gethtml; //output the content in the page

A: if you want to show it as code you can use this jquery plugin for that


Q: TypeError: trace(): argument 'input' (position 1) must be Tensor, not method I get this weird error when I start my script I really don't know why this error is caused or by what it's caused. It would be very very nice if some of you guy's could help me out with this error:)
Error message:
  File "c:/Users/supre/Documents/Python Programs/neuralnet/optimize_graph.py", line 11, in trace
    traced = torch.trace(model.forward)(xample_inputs=(x, hidden))
TypeError: trace(): argument 'input' (position 1) must be Tensor, not method

This is my code:
import argparse
import torch
from model import SpeechRecognition
from collections import OrderedDict

def trace(model):
    model.eval()
    x = torch.rand(1, 81, 300)
    hidden = model._init_hidden(1)
    traced = torch.trace(model.forward)(xample_inputs=(x, hidden))
    return traced

def main(args):
    print("loading model from", args.model_checkpoint)
    checkpoint = torch.load(args.model_checkpoint, map_location=torch.device('cpu'))
    h_params = SpeechRecognition.hyper_parameters
    model = SpeechRecognition(**h_params)
    model_state_dict = checkpoint['state_dict']
    new_state_dict = OrderedDict()
    for k, v in model_state_dict.items():
        name = k.replace("model.", "") # remove `model.`
        new_state_dict[name] = v

    model.load_state_dict(new_state_dict)

    print("tracing model...")
    traced_model = trace(model)
    #print(type(traced_model))
    print("saving to", args.save_path)
    traced_model.save(args.save_path)
    print("Done!")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="testing the wakeword engine")
    parser.add_argument('--model_checkpoint', type=str, default='NameOfYourCheckpoint', required=False,
                        help='Checkpoint of model to optimize')
    parser.add_argument('--save_path', type=str, default='path/where/you/want/to/save/the/optimized/model', required=False,
                        help='path to save optmized model')

    args = parser.parse_args()
    main(args)

Thank's for every help in advance

A: In traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) you are passing a method i.e model.forward you should be using something like this
traced = torch.trace(model.forward(x)) if your model is already had an instance with parameters


Q: How are constants/functions named after their discoverer? In general, when a paper references an object discovered/defined in another paper by author X, it goes something along the lines of:
"Let $\tau$ be the constant defined by X in 1999 [1]$\ldots$",
or
"Let $f_{\mu}$ denote the function that generalizes the case $\ldots$ (X, [1])".
At what point does the literature start talking about "X's constant" or "The X function"?
Who/what determines that an object discovered by somebody deserves to take his name?

A: This is determined by informal consensus of researchers in an area. Anyone can propose a name for a mathematical object, just by using this name in a paper. Then the proposed name either sticks to the object or not. This depends on the opinions of other people working in the area. Eventually the name of the object becomes established.
Sometimes several names for the same object become established, and all of them popular.
For example Fatou set is the same as the set of normality. The name Fatou set
was proposed in two influential surveys in 1980s, and many people in the area use it.
The name does not have to be the name of the discoverer of the object.
For example, Drinfeld introduced an object which he named Yangian,
in honor of Chen-Ning Yang.
M. Lyubich and I gave the name "Baker's domain" to an object that we defined.
Unlike some other "personal names" we proposed in the same paper, this one is used by everyone who writes on the subject. Arnold once stated a principle that
"If the thing is named after someone, this indicates that the person had nothing to do with the thing". M. Berry remarked that "Arnold Principle applies to itself".
Sometimes a multitude of names reflects a priority dispute or nationalistic feelings (Young diagram vs Ferrers diagram, Schwarz inequality vs Cauchy or
Bouniakowski etc.) The name Casorati–Sokhotski–Weierstrass theorem reflects
some priority research, but the theorem in question was earlier stated by Briot and Bouquet. Same happened with "Gauss-Manin connection" which was in fact discovered by Legendre.
Sometimes the accepted name is changed ($\pi$ used to be "Archimedes number" and
$e$ used to be "Euler's number").
A funny story happened with "Koebe constant". It turned out that it is equal to $1/4$, so one mathematician wrote "Now it cannot be called Koebe constant anymore,
because it turns out that it already has a name, namely $1/4$").
Sometimes a name is based on a mistake. For example Abel's equation
is the accepted name for $f(x+1)=g(f(x))$. It is based on a manuscript of Abel, but the manuscript itself turns out to be just Abel's personal notes on
the work of Napier, where the equation was introduced.
People usually do not give their own names to mathematical objects. However,
in his influential book on functional analysis, Banach introduces
"spaces of type H", "spaces of type F" and "spaces of type "B". As his "spaces of type H and F" are nothing but Hilbert and Frechet spaces, people probably understood the hint:-)
G. Julia intensively lobbied (not publicly, in private correspondence, which is now published) that the "irregular set" be called Julia set. He succeeded.
Remark. I just found the paper, arXix:1204.4716v1 (Bernard Ycart, A case of mathematical eponimy: the Vandermonde determinant), which shows that there is a whole research area related to this question: it is called "mathematical eponimy". The paper cites several other publications on this subject.


Q: Does the EclEmma coverage tool perform node or edge or condition or path coverage? I have a question about EclEmma coverage tool,
Does the EclEmma coverage tool perform node or edge or condition or path
coverage? Explain
Thank you

A: EclEmma - is Eclipse plugin based on Java Code Coverage Library called JaCoCo that performs analysis of Java bytecode. Description of coverage counters provided by JaCoCo can be found in its documentation. As you can see in it - JaCoCo and hence EclEmma provide

*

*instructions coverage

*branch coverage

*line coverage

*and cyclomatic complexity

Don't know what you call node coverage, and I'm guessing that what you call edge coverage - is branch coverage.
Regarding condition coverage - Wikipedia says

if (a && b) { /* ... */ }

condition coverage can be satisfied by two tests a=true, b=false, a=false, b=true

what seems a bit weird in case of Java where && is a short-circuit operator - second test can't trigger retrieval of value of "b".
Regarding path coverage - JaCoCo does not provide it, what can be demonstrated using following example:
void fun(boolean a, boolean b) {
  if (a) { /* ... */ }
  if (b) { /* ... */ }
}

Not counting exception there are 4 paths thru this method. And so for full path coverage 4 tests will be required - a = true, b = true, a = true, b = false, a = false, b = true and a = false, b = false. However JaCoCo and EclEmma would report 100% coverage after just 2 tests - a = true, b = true and a = false, b = false.


Q: How can I use my backup of Thunderbird I read "How do I back up Thunderbird emails?" from here.
How can I use it again when the account will be deleted from Thunderbird or change the operating system?

A: The folder ~/.thunderbird includes everything you need. It includes emails, accounts, settings, (email-) passwords etc. If you simply backup the folder regularly, you can simply copy it back to your newly installed system, into ~/ (which is your home directory, /home/yourname).
Even the installed extensions, add-ons etc. will be available instantly in most cases, with no other action but simply copying back the (whole) backed-up ~/.thunderbird -folder into ~/.
Couldn't be easier :)


Q: Nested Jasmine Spies on SpyObj I have a constructor that receives a spyObj called TestService:
constructor(private testService: TestService) {
    testService.getTestData().subscribe((settings) => {
        this.settings = settings;
    }
}

Using Jasmine, how can I create spies for subscribe() and getTestData() on TestService?
Thanks in advance!
Mike


Q: Image size is too small while uploading from local storage, Microsoft Face API I m calling Microsoft Face API for detecting the face in an image.
While loading an image from local , I always get an error as below
{ code: 'InvalidImageSize',
  message: 'Image size is too small.' }

But using the same image via URL , its working fine.
const fs = require("fs");
const axios = require("axios");

axios({
    method : "post",
    url : " https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true",
    headers : {
        'Content-Type': 'application/octet-stream',
        "Ocp-Apim-Subscription-Key" : "2da8e41a647c4079b2f9a6XXXXXXXXX"
    },
    body : fs.readFileSync("./photos/shiva3.jpeg").toString("base64")
}).then((res)=>{
    console.log("Response");
    console.log(res.data);
}).catch((err)=>{
    console.log(err.response.data.error);
})

A: I have fixed the issue by calling default function in the axios.
const axios = require("axios").default;


Q: How to iterate through a directory and sub-directories using a URL I'm trying to iterate through files in a directory and files in sub-directories within:
<?php

$dir = get_stylesheet_directory_uri() . '/js';

echo $dir;

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );

foreach ( $iterator as $path ) {
    if ($path->isDir()) {
        print('
 DIR : ' . $path . PHP_EOL . "
");
    } else {
        $path_parts = pathinfo($path);
        $file_parts = $path_parts['extension'];
        if ($file_parts == "js")
        {
            $array = explode("/opt/lampp/htdocs", $path);
            unset($array[0]);
            echo $path = implode("/", $array);
            print("
http://localhost$path" . PHP_EOL . "
");
            echo("");
        } else if ($file_parts == "css") {
            echo("");
            echo("<link rel='stylesheet' href='http://localhost/$path'>");
        }
    }
}

?>

I, however, get the error:
Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40

echo $dir; gives:

http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js

The StackTrace:
Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40 Stack trace: #0 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php(40): RecursiveDirectoryIterator->__construct('http://localhos...') #1 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(684): require_once('/opt/lampp/htdo...') #2 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(643): load_template('/opt/lampp/htdo...', true) #3 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/general-template.php(45): locate_template(Array, true) #4 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/index.php(18): get_header() #5 /opt/lampp/htdocs/pro in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php on line 40

How can I fix it and make it work right?
Thank you all in advance.

A: RecursiveDirectoryIterator::__construct expects a path not a uri. To fix this try:
$dir = get_stylesheet_directory() . '/js'; // This gives you a path instead

A: You are passing an URL, while you have to pass a path.
Check it here: http://php.net/manual/en/class.recursivedirectoryiterator.php


Q: Django manually fail transaction after done with for loop I'm trying to run over a for loop that validates objects and saves them, and I want to fail it all if at least one have failed, but only after going over all the objects. I've tried different approaches, but on all of them - even if there was an exception, at least one object was saved to DB. In the latest version, see below, I'm trying to set
transaction.set_rollback(True)

if at least on exception was raised.
try:
    is_failed = False
    with transaction.atomic():
        for identifier, spec in spec_dict.items():
            try:
                spec_data = {'title':my_title,
                             'identifier': identifier,
                             'updated_by': user_id,
                             'created_by': user_id
                }
                serializer = SpecSerializer(data=spec_data)
                serializer.is_valid(raise_exception=True)
                serializer.save()

            except DataError as DE:
                print("** in DataError")
                is_failed = True
                pass

            except ValidationError as VE:
                print("** in ValidationError")
                print(str(VE))
                is_failed = True
                pass

            except Exception as Exc:
                print("** inside Exception: " + str(Exc))
                is_failed = True
                pass

        if is_failed:
            transaction.set_rollback(True)
except IntegrityError:
    print("** inside integrity error")
    pass

Seems like the 'set_rollback' doesn't affect the transaction. Worth to mention that all our http requests are wrapped in transaction.
EDIT:
Should transaction.atomic() work for non view functions? Couldn't find answer for that

A: So, apparently -
transaction.atomic():

is managing the transaction for the 'default' DB by default, unless other DB is mentioned:
transaction.atomic(using='otherDB'):

Since we use more than one DB and the one that I worked on was not set as the default, I was missing the 'using'.


Q: Product management System Tracking with Google Tag Manager I am working on Product Management system site in which on the enquiry of a product i fill a contact us form which has the info of that product as follows

as soon as the form is submitted it leads me on the thank you page where I have added the following code in order to track it using GTM
<?php
$enquiry_id = "";
$enquiry_id = $this->session->userdata('enq_id');
$product_data = "";
$product_data = $this->session->userdata('enq');
echo "<!--<pre>";
print_r($product_data);
echo "<pre>-->";
if (!empty($product_data) && !empty($enquiry_id) && isset($product_data)){
    ?>

<script>
 <?php
    foreach($product_data as $value){
    ?>
dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': '<?php echo $enquiry_id?>'                      // Transaction ID.

      },
      'products': [{
        'name': '<?php echo $value ?>',
        'id': '<?php echo $enquiry_id?>',
        'price': '0.0',
        'quantity': 1

       }]
    }
  }
});

<?php } ?>

</script>

<?php
$this->session->unset_userdata('enq_id');
$this->session->unset_userdata('enq');
}
?>
<script>

Now the thing is I am able to get the values in the GTM debugger as well as i can see them in view source but the values dont show up in Google Analytics , So is there any other way to get the values in the Conversion->Ecommerce section of GA.I have set the track type as Transaction in GTM.
Thanking you in advance


Q: Combining the duality principle and the graphical method I am trying to minimize this linear program by combining the duality principle and the graphical method:

I can't seem to find an example of how to approach this, can anyone show me how I would go about this?

A: The dual problem is:
objective function
$\text{max} \ -y_1+y_2$
constraints
$2y_1+y_2 \leq 2$
$y_1+3y_2 \leq 3$
$-2y_1+y_2 \leq 3$
$3y_1+2y_2 \leq 6$
$-2y_1+y_2 \leq 4$
$y_1,y_2$ are unrestricted.
You have to solve every constraint for $y_2$. Then you can draw the constraints in a $y_1-y_2$-coordinate system. If you consider the inequality-signs you will get a solution space.
Now you set the objective function equal to zero and solve the equation for $y_2$. After you have drawn it in the coordinate system you have to move it parallel till you just touch the solution space.


Q: JOIN inside a SELECT MAX in Postgres I have the following query that returns these two elements.
SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
  FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id;

This result is okay.
id |         created_at         | user_id | id | payment_method
----+----------------------------+---------+----+----------------
  1 | 2017-05-26 04:29:22.189628 |       4 |  4 |
  2 | 2017-05-26 04:33:00.721404 |       4 |  4 | some_payment_method

When I try to filter the query to display the last record created per user it also works okay using SELECT MAX.
SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
  FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id
WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id);

And the result
 id |         created_at         | user_id | id | payment_method
----+----------------------------+---------+----+----------------
  2 | 2017-05-26 04:33:00.721404 |       4 |  4 | some_payment_method
(1 row)

However, when Im trying to filter to only select items without a payment_method I get no results.
SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
  FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id
WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id AND charges.payment_method IS NULL);

(Notice the AND charges.payment_method IS NULL) and the end of the query)
This is what I get instead
 id | created_at | user_id | id | payment_method
----+------------+---------+----+----------------
(0 rows)

Any idea how can I retrieve the elements with no payment method, in this case would be the record with id 1?

A: As per discussion on chat. i think below query will help you to get required result.
with data as ( SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id
where charges.payment_method is null

)
select * from data d1
where d1.created_at = (select max(created_at) from data d2
where d1.users_id = d2.user_id
)

There are few points while writing an sub query in where clause. Join your table carefully as in your case you are not utilizing any column for joining.


Q: WPF vs Win App battery usage We want to use wpf application on tablet and looking for difference battery usage impacts between win app and wpf application?
Is there any comparision battery usage or document?

A: I doubt there is any type of documentation on what you want, but as suggested above, running your own tests shouldn't be too hard. I don't recall the APIs, but on any mobile device, there are going to be battery state objects you can access giving, at the very least, remaining battery energy. Write two test apps, each using the different paradigms. Run each, one at a time and for a long duration. Check on the energy usage at the beginning and end.

A: This is late for an answer but one aspect to remember about battery consumption is the use of the radios (Bluetooth and WiFi).
For tablet apps try to manage your app by stepping back and analyzing what data you'll need from the database and try to get the data in one shot so the OS can turn off the radio. If you make an sql call each time the user presses a button then the radio is on more and drains the battery. The OS might also leave the radio on "a little longer" in case you make another query.
For the rest of the UI of the app, you're safe to count on an 8 hr shift and then they dock it for recharge.
You can watch for the battery notifications as well so you can save the info in the app before the OS shuts you down.
Other than that, each app is unique and you'll need to run these tests during your QA cycle.