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: 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: 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: 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: 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: 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: 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: 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: 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.


Q: Set branch permissions from Azure DevOps Pipeline with tf.exe I have a Powershell script that tries to set branch permissions that is getting called in a Build Pipeline. Unfortunately, I am getting an unauthorized error and I'm not sure why.
Code Snippet:
$tfExe = "$(split-path -parent $MyInvocation.MyCommand.Definition)\tf.exe"
& $tfExe git permission /deny:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /login:$username,$pat
& $tfExe git permission /allow:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /branch:feature /login:$username,$pat

Error Message:

TF30063: You are not authorized to access
  https://dev.azure.com/Company-DevOps. TF30063: You are not authorized
  to access https://dev.azure.com/Company-DevOps. TF30063: You are not
  authorized to access https://dev.azure.com/Company-DevOps.

Powershell Script in Build Pipeline:

Any thoughts?

A: The username & password in the /login is for Azure DevOps Server. for Azure DevOps you should use OAuth:
param ($oauth)
/loginType:OAuth /login:.,$auth

In the agent job options you need to enable the "Allow scripts to access the OAuth token":

And pass the $(System.AccessToken) as oauth parameter:

A: So I wasn't able to get this to work with tf.exe as Microsoft Docs advised us to, but I was able to figure it out with the help of a blog here.
Step 1
Get the $descriptor value for the Contributors group
$descriptor = az devops security group list --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json | select -expand graphGroups | where principalName -eq "[$project]\Contributors"

Step 2
Create your token values for the branches you want. Unfortunately, you cannot explicitly state which branch pattern you would like. Azure DevOps requires the Hex value (don't ask)
#Create the tokens
function hexify($string) {
    return ($string | Format-Hex -Encoding Unicode | Select-Object -Expand Bytes | ForEach-Object { '{0:x2}' -f $_ }) -join ''
}

$hexFeatureBranch = hexify -string  "feature"
$featureToken = "refs/heads/$hexFeatureBranch"

$hexSprintBranch = hexify -string  "sprint"
$sprintToken = "refs/heads/$hexSprintBranch"

$hexHotfixBranch = hexify -string  "hotfix"
$hotfixToken = "refs/heads/$hexHotfixBranch"

Step 3
Get the Namespace ID for your Git Repos
#Get the namespace ID for the organization's Git repos
$namespaceId = az devops security permission namespace list --org "https://dev.azure.com/$organization/" --query "[?@.name == 'Git Repositories'].namespaceId | [0]"

Step 4
Get the project's JSON object from the server
#Get the Project's JSON object
$projectObj = az devops project show --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json
$projectid = $projectObj.id

Step 5
Put a Deny on CreateBranch for every branch in your repo. The Azure CLI requires you to know which bits for allow and deny need to be. Luckily, I was able to do this by capturing the JSON response when I did it via the UI.
$denyBranch = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token "repoV2/" --deny-bit 16 --allow-bit 16494

Step 6
Put an Allow on CreateBranch for every branch that has the pattern feature/, sprint/ and hotfix/*
$featureTokenBuild = "repoV2/$projectid/$repoid/$featureToken"
$sprintTokenBuild = "repoV2/$projectid/$repoid/$sprintToken"
$hotfixTokenBuild = "repoV2/$projectid/$repoid/$hotfixToken"

$allowCreateBranchFeature = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $featureTokenBuild --deny-bit 0 --allow-bit 16
$allowCreateBranchSprint = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $sprintTokenBuild --deny-bit 0 --allow-bit 16
$allowCreateBranchHotfix = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $hotfixTokenBuild --deny-bit 0 --allow-bit 16

It wasn't easy but at least for anyone in the future looking to do the same, here is the solution!


Q: Blocked by Play Protect for a signed release APK I have a React Native (Android) app and for which I signed as per the instructions here;
https://reactnative.dev/docs/signed-apk-android
I generated a release APK which is also all fine (no errors).  I then downloaded the APK to my android device and when I clicked to install I got a message to say the below.

This app is not to be published to the Play Store but we will supply a URL to our customers to download the APK.  So I want users to be able to install the APK without getting this warning.
What I found so far

*

*Disabling the play protect on the device (We don't want our customers to do this)

*Publishing to the play store (We will supply a URL to download the APK)

*Play Protect Appeals Submission Form (Is this only for apps to be published to the play store? If not, how does it work once it is verified?)

Thanks all.

A: Play Protect Appeals Submission Form can solve your problem. Just send your apk details to Google and wait for appeal process. When you enter your apk's URL, Google will control your apk. Just enter your URL to URL to download your APK file section. You do not need publish your app.


Q: Ember inject function I have some function which i use in couple controllers
 App.AController=Ember.Controller.Extend({
    area:function(){}
});
App.BController=Ember.Controller.Extend({
    area:function(){}
});

cause i new in Ember i want something to write function in one place and then inject function in Controllers. I try something with services but doesn't work i got error that Ember.Service is not defined, so if someone can write example!
I use ember 1.10.

A: If you use ember-cli just create a file app/utils/area.js:
export default function () {...};

and then you can import it and use it:
import area from 'myapp/utils/area`;
import Ember from 'ember';

export default Ember.Controller.extend({
  area,
});

However if you'r not using ember-cli, this question is not ember specific. Then it depends how you organize your code. But you really should check out ember-cli!
But always remember, this is just javascript. This is valid code:
function area() {
    ...
}

App.AController=Ember.Controller.Extend({
    area
});
App.BController=Ember.Controller.Extend({
    area
});


Q: How to get JaCoCo instrumentation code coverage while executing webApplication on server I want to get a code coverage report (or tracking controller flow of an application) when I execute the some scenario on live application i.e. while application running in server, so I have refereed the official Jacoco documentation  and did as fallows
As a first step, I tried to bind the jacoco agent to the application running port
export MAVEN_OPTS=-javaagent:/home/user/.m2/repository/org/jacoco/org.jacoco.agent/0.7.4.201502262128/org.jacoco.agent-0.7.4.201502262128-runtime.jar=includes=*,output=tcpserver,port=6300,address=*,dumponexit=true

then I have started the server and executed some test scenarios by that time I have also requested jacoco to get the dump by executing following command
 mvn jacoco:dump

when I executed the above command first it showed like java.net.BindException: Address already in use then it printed as fallows
[INFO] Connecting to localhost/127.0.0.1:6300

When I stopped the server jacoco.exec has been generated to a known location there after I have requested to generate a jacoco report by executing the following command
mvn jacoco:report

Finally I got the report but when I open the index.html page it showed 0% coverage.
you can reproduce my difficulty with following sample Spring MVC project
please download Spring MVC project from https://github.com/mkyong/spring4-mvc-ajax-example from the Github
In my case I am using WildFly 8.x server to run the project and add the following dependencies to downloaded projects pom.xml
 maven-surefire-plugin of 2.19.1 version
 jacoco-maven-plugin of 0.7.4.201502262128 version
 junit of 4.12 version

Then clean and build the project by using following commands.
mvn clean install

once it is done get the .war file from target folder of the project and keep inside the wildfly serverwildfly-9.0.0.CR2/standalone/deployments/ folder
Once the .war is deployed go to /wildfly-9.0.0.CR2/bin/ folder and execute/run the ./standalone.sh file or depending on platform you can run the.dat/.sh file
once project is deployed and server is started execute the following command
mvn jacoco:dump

it displayed like listening/connected to localhost/127.0.0.1:6300
Then execute some test scenarios and execute following maven command
mvn jaococ:report

Finally report will be generated with 0% coverage!.
Downloaded project can be found in  MKyong website
Please help me to get the code coverage report and any help will be appreciated.

A: JaCoCo requires the exact same class files for report generation that were used at execution time, so

*

*if report is completely empty, then classes were not provided

*if report contains classes but their coverage is 0%, then they don't match classes that were used at runtime - this is described along with other related information in JaCoCo documentation on page http://www.jacoco.org/jacoco/trunk/doc/classids.html
and in either case check existence of warnings in log.
Update for updated question
Here is what I did:

*

*downloaded and unpacked JaCoCo 0.7.9 into /tmp/jacoco/jacoco-0.7.9

*downloaded and unpacked Wildfly 9.0.0.CR2 into /tmp/jacoco/wildfly-9.0.0.CR2

*cloned https://github.com/mkyong/spring4-mvc-ajax-example into /tmp/jacoco/spring4-mvc-ajax-example and built as mvn verify

*copied /tmp/jacoco/spring4-mvc-ajax-example/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT.war into /tmp/jacoco/wildfly-9.0.0.CR2/standalone/deployments

*Wildfly started as JAVA_OPTS=-javaagent:/tmp/jacoco/jacoco-0.7.9/lib/jacocoagent.jar=output=tcpserver ./standalone.sh and got enough time to deploy application

*in directory /tmp/jacoco/spring4-mvc-ajax-example executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report (note that version of used agent matches version of jacoco-maven-plugin) so that it created /tmp/jacoco/spring4-mvc-ajax-example/jacoco.exec and report /tmp/jacoco/spring4-mvc-ajax-example/site/jacoco:

*opened http://localhost:8080/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT/ and did some actions

*executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report again to get an updated report:


Q: How to add exclude data in Firebase rules on multiple levels? I have my rules set. Normally, all data can only be read by the person who is auth to do so. However, I want to make exceptions. These are my rules:
 "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid",
        "ForEveryone": {
        ".read": true,
          ".write": true
        }
        "NoWrite" : {
          ".read": true,
          ".write": false
        }
      }
    }

So I let's say I have 3 string. String 1 is called private and can the auth person can read and write. String 2 is ForEveryone, so everyone can change and write data. String 3 is NoWrite, for everyone but you can not write to it.
I get an error, saying:Expecting a ; or " at the line NoWrite. So what am I doing wrong? Is it a wrong placed }? Thank you.

A: The approach you're taking to your rule structure won't work. Firebase security rules cascade, meaning that a permission given to any node will apply to any of its children and on down the tree. You cannot grant read or write access on a node and then revoke it further down. (But you can grant permissions not granted above.) See the docs on rule cascading.
In your case, you want to have some user data that be can written to by anyone and some that cannot. It's not clear from your example whether you want NoWrite to be written only by the authenticated user, or by nobody. Depending on how you will be reading this data, you will need to either separate these data into different collections, or make $uid inaccessible and define your rules only for ForEveryone and NoWrite.
The first approach might look like this:
 "rules": {
    "users-public": {
      "$uid": {
        ".read": "true",
        ".write": "true",
      },
    "users-nowrite": {
      "$uid": {
        ".read": "true",
        ".write": "$uid === auth.uid"
      }
    }

Or the second, like this:
 "rules": {
    "users": {
      "$uid": {
        "ForEveryone": {
          ".read": "true",
          ".write": "true"
        },
        "NoWrite" : {
          ".read": "true",
          ".write": "$uid === auth.uid"
        }
      }
    }

As to your syntax error, you need a comma , after the closing brace before "NoWrite".

A: Here are your rules, properly spaced so you can see the relationship between the parent nodes and child nodes. It seems this is not what you want. So this isn't really an answer but will lead to a better question that we can answer. Will update once we know what the OP is after.
{
    "rules": {
        "users": {
           "$uid": {
               ".read": "$uid === auth.uid",
               ".write": "$uid === auth.uid",
               "ForEveryone": {
                   ".read": true,
                   ".write": true
               },
               "NoWrite" : {
                   ".read": true,
                   ".write": false
               }
           } //end uid
         } //end users
     } //end rules
} //outside closure


Q: Why the first if statement conditional is ignored and the last else is executed? When I type in John and 0 the "John is great" statement is not executed. I don't understand why.
I know that the question might be really simple but I checked the code in Java and it was working correctly.
print("Hello world")
myName = input("What is your name?\n")
myVar = input("Enter a number: ")

if(myName == "John" and myVar == 0):
    print("John is great")
elif(myName == "Bob"):
    print("You are ok")
else:
    print("Hello world")

A: myVar is str type. Not int type.
You should fix myVar = int(input("Enter a number: "))

A: 0 and "0" are two different values. 0 == 0 is true; 0 == "0" is false.
input always returns a str, so entering 0 sets myVar to "0", not 0.
if myName == "John" and myVar == "0":


Q: undefined attribute in use of $controllerProvider in Angular I'm a newbie in Angular, i whant to make use of $controllerProvider, i see an example like my code, but the attribute register got undefined:
var appTmw = angular.module('appTmw', ['ui.router']);

appTmw.config(function($stateProvider, $urlRouterProvider, $controllerProvider) {

    appTmw.register = {
        controller: $controllerProvider.register
    };
})

and here, a register of controller, the register attribute got undefined:
appTmw.register.controller('CustomersController', ['$scope', 'config', 'dataService',
   function ($scope, config, dataService) {

      //Controller code goes here
   }]);

what a problem with the code?

A: controllerProvider is the $controller service used by Angular to create new controllers:
https://docs.angularjs.org/api/ng/provider/$controllerProvider
If you are new to angular I suggest you to use the standard way to create a controller:
var appTmw = angular.module('appTmw', ['ui.router']);

appTmw.controller('controllerName', function($scope){

//your code for the controller here

});

I hope it helps.


Q: Catch if user presses enter key in textbox I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.
This is my Event code for the Textbox:
Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?
I tried changing the Textbox property to AcceptsReturn = True but no luck.
Extra info: The textbox is located on a UserControl and not a form control.

A: If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead.
It might work, but it all depends on where in the event chain that the parent intercepts the message.
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then
        'Do your stuff here.
        Return True 'We've handled the key press.
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

A: Try this:
Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both


Q: Adding Icons on TabBottomNavigation React Native I have This navigation, how can I add Icons on the bottomTabNavigator
const switchNavigator = createSwitchNavigator({
      mainFlow: createBottomTabNavigator({
        Home: createStackNavigator({
          Search: SearchScreen,
          Results: ResultsShowScreen
        }),
        Map: AccountScreen,
        Scanner: AccountScreen,
        Account: AccountScreen
      })
    });

A: U can add icons to tabs using defaultNavigationOptions, here is an example,
more information about tabs can be got from https://reactnavigation.org/docs/en/4.x/tab-based-navigation.html
export default createBottomTabNavigator(
  {
    Home: HomeScreen,
    Settings: SettingsScreen,
  },
  {
    defaultNavigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, horizontal, tintColor }) => {
        const { routeName } = navigation.state;
        let IconComponent = Ionicons;
        let iconName;
        if (routeName === 'Home') {
          iconName = focused
            ? 'ios-information-circle'
            : 'ios-information-circle-outline';
          // Sometimes we want to add badges to some icons.
          // You can check the implementation below.
          IconComponent = HomeIconWithBadge;
        } else if (routeName === 'Settings') {
          iconName = focused ? 'ios-list-box' : 'ios-list';
        }

        // You can return any component that you like here!
        return <IconComponent name={iconName} size={25} color={tintColor} />;
      },
    }),
    tabBarOptions: {
      activeTintColor: 'tomato',
      inactiveTintColor: 'gray',
    },
  }
);```


Q: Why do browsers have 3 characters as protocol separator? http:// vs http:
Either there is some historical reason or I'm missing something.

A: According to RFC 1738,

While the syntax for the rest of the URL may vary depending on the
particular scheme selected, URL schemes that involve the direct use
of an IP-based protocol to a specified host on the Internet use a
common syntax for the scheme-specific data:
//user:password@host:port/url-path
Some or all of the parts "user:password@", ":password",
":port", and "/url-path" may be excluded.  The scheme specific
data start with a double slash "//" to indicate that it complies with
the common Internet scheme syntax.

A: //                Indicates that a contact to a server is to be achieved. (For example, when sending email the notation 'mailto:<email address>...', without slashes, could be used). Note that this doesn't mean a connection between a browser and server. When a browser has sent a request, there is no connection between the browser and the server.


Q: Browsersync - How to choose which installation of browser to run? I've just installed Firefox Dev Edition, and I don't know how to tell browsersync to start with it when I launch it.
I know there is the browser option in which I can specify "firefox", but how can I differenciate one FF installation from one other ?
The issue would be the same if I had various regular FF installed (eg a 3.5, a 48.x and a 50.x).
I can always open manually the right FF and load the page after browsersync started, but I would like it to do it manually (and not to be opened in my regular non-dev FF).

A: In fact, it was quite easy: if you put the absolute path to an executable file in the browser option, it takes it smoothly.
So options should be something like :
{ port: 9000,
    server: {
      baseDir: [...
      ],
      routes: {
        '/bower_components': 'bower_components',
        '/node_modules': 'node_modules',
        '/temp': 'temp'
      }
    },
    logLevel: 'info',
    notify: true,
    browser: 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe',
    reloadDelay: 0 //1000
}


Q: Best way to inform user of an SQL Table Update? I have a desktop python application whose data backend is a MySQL database, but whose previous database was a network-accessed xml file(s). When it was xml-powered, I had a thread spawned at the launch of the application that would simply check the xml file for changes and whenever the date modified changed (due to any user updating it), the app would refresh itself so multiple users could use and see the changes of the app as they went about their business.
Now that the program has matured and is venturing toward an online presence so it can be used anywhere. Xml is out the window and I'm using MySQL with SQLAlchemy as the database access method. The plot thickens, however, because the information is no longer stored in one xml file but rather it is split into multiple tables in the SQL database. This complicates the idea of some sort of 'last modified' table value or structure. Thus the question, how do you inform the users that the data has changed and the app needs to refresh? Here are some of my thoughts:

*

*Each table needs a last-modified column (this seems like the worst option ever)

*A separate table that holds some last modified column?

*Some sort of push notification through a server?

*It should be mentioned that I have the capability of running perhaps a very small python script on the same server hosting the SQL db that perhaps the app could connect to and (through sockets?) it could pass information to and from all connected clients?

Some extra information:

*

*The information passed back and forth would be pretty low-bandwidth. Mostly text with the potential of some images (rarely over 50k).

*Number of clients at present is very small, in the tens. But the project could be picked up by some bigger companies with client numbers possibly getting into the hundreds. Even still the bandwidth shouldn't be a problem for the foreseeable future.

Anyway, somewhat new territory for me, so what would you do? Thanks in advance!

A: As I understand this is not a client-server application, but rather an application that has a common remote storage.
One idea would be to change to web services (this would solve most of your problems on the long run).
Another idea (if you don't want to switch to web) is to refresh periodically the data in your interface by using a timer.
Another way (and more complicated) would be to have a server that receives all the updates, stores them in the database and then pushes the changes to the other connected clients.
The first 2 ideas you mentioned will have maintenance, scalability and design uglyness issues.
The last 2 are a lot better in my opinion, but I still stick to web services as being the best.


Q: Is it possible for WebDriver to click an element with a mouseclick event that invokes a JavaScript file that includes a test tracker? This is a question I have that arises from another user's question. If you look at my answer there, you will get some context for this question. The URL for the web page I am going to is https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8 if you want to check it out for yourself.
Consider the python selenium script found at the bottom of the question.  Nothing happens when selenium tries to click on this element:
browser.find_element_by_xpath('//*[@id="cPageBtn"]').click()
Same thing with this element
browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click()

When debugging my selenium script for each element, I confirmed that selenium can find the element just fine;  it is not hidden, inside an iFrame, disabled, or any other oddity that I normally check for failed selenium actions.
However, it has a mouseclick event that invokes an interesting JavaScript file, and I was actually able to access it by navigating to URL shown here:

Hovering over the URL revealed that it is https://webresource.c-ctrip.com/ResUnionOnline/R3/float/floating_normal.min.js?20190306:2.
At the very beginning of the file I found
document.getElementById("ab_testing_tracker") && "abTestValue_Value" != h ?
document.getElementById("ab_testing_tracker").value

So I search (via CSS selector in the dev console) the webpage HTML for an element with an id of "ab_testing_tracker" and I am less than surprised that it returns nothing.  Then I unminified and searched through the file for all instances of "ab_testing_tracker".  That led me to this element:
document.getElementsByTagName("body")[0].insertAdjacentHTML("afterBegin","<input type='hidden' name='ab_testing_tracker' id='ab_testing_tracker' value='"+h.split("|")[1]+"'>")
Well, it appears there is a hidden input node inserted in the body of the document for the purpose of automation tracking.  Google searching revealed that automation tracking is often accomplished by looking at the navigator.userAgent property and finding userAgents that indicate automation.  But the script is using a random legitimate userAgent every time, so I don't think the userAgent is how the detection is finding selenium.
Summary and possible workarounds
Selenium can't click certain elements on the web page likely due to testing tracking by the website. There are a couple things I thought of to get around
it: maybe I can disable click events when using selenium? This I don't know how to do and couldn't find a way after searching online. Next, I tried to click on it with a Javascript executor, but that didn't work.
Does anyone know a way to get around the test tracker and click the desired element?
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By

# url
url = "https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8"

# User Agent
User_Agent_List = ["Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2",
                   "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
                   "Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)",
                   "Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11",
                   "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2",
                   "Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
                   "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25"]

# Define the related lists
Score = []
Travel_Types = []
Room_Types = []
Travel_Dates = []
Comments = []

DEFINE_PAGE = 10

def next_page():

    current_page = int(browser.find_element_by_css_selector('a.current').text)

    # First, clear the input box
    browser.find_element_by_id("cPageNum").clear()
    print('Clear the input page')

    # Second, input the next page
    nextPage = current_page + 1
    print('Next page ',nextPage)
    browser.find_element_by_id("cPageNum").send_keys(nextPage)

    # Third, press the goto button
    browser.find_element_by_xpath('//*[@id="cPageBtn"]').click()

def scrape_comments():
    """
    It is a function to scrape User comments, Score, Room types, Dates.
    """
    html = browser.page_source
    soup = BeautifulSoup(html, "lxml")
    scores_total = soup.find_all('span', attrs={"class":"n"})
    # We only want [0], [2], [4], ...
    travel_types = soup.find_all('span', attrs={"class":"type"})
    room_types = soup.find_all('a', attrs={"class":"room J_baseroom_link room_link"})
    travel_dates = soup.find_all('span', attrs={"class":"date"})
    comments = soup.find_all('div', attrs={"class":"J_commentDetail"})
    # Save score in the Score list
    for i in range(2,len(scores_total),2):
        Score.append(scores_total[i].string)
    Travel_Types.append(item.text for item in travel_types)
    Room_Types.append(item.text for item in room_types)
    Travel_Dates.append(item.text for item in travel_dates)
    Comments.append(item.text.replace('\n','') for item in comments)

if __name__ == '__main__':

    # Random choose a user-agent
    user_agent = random.choice(User_Agent_List)
    print('User-Agent: ', user_agent)

    # Browser options setting
    options = Options()
    options.add_argument(user_agent)
    options.add_argument("disable-infobars")

    # Open a Firefox browser
    browser = webdriver.Firefox(options=options)
    browser.get(url)

    browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click()

    page = 1
    while page <= DEFINE_PAGE:
        scrape_comments()
        next_page()

    browser.close()

A: The problem is not the tracking or the click event, the problem is timing and possibly browser size.
Maximize the browser window and add explicit wait when searching for the banner close button
browser = webdriver.Firefox(options=options)
browser.maximize_window()
browser.get(url)

wait = WebDriverWait(browser, 10)

wait.until(EC.element_to_be_clickable((By.ID, 'appd_wrap_close'))).click()
wait.until(EC.invisibility_of_element_located((By.ID, 'appd_wrap_default')))

current_page = int(browser.find_element_by_css_selector('a.current').text)
next_page = current_page + 1

page_number_field = wait.until(EC.visibility_of_element_located((By.ID, 'cPageNum')))
page_number_field.clear()
page_number_field.send_keys(next_page)
wait.until(EC.element_to_be_clickable((By.ID, 'cPageBtn'))).click()


Q: %0d%0a getting added behind the URL of a href attribute in an  tag In a helper plugin for WooCommerce for WordPress, I'm trying to create a custom message to be sent to a buyer.
I don't know why in all the emails that are sent out, %0d%0a is getting added behind the URL in the href attribute. I have tried several different combinations and nothing is working.
This is what I'm trying to do:
echo " Please click here to redeem the coupon";
But because %0d%0a is being added at the back of it the URL doesn't work properly for coupon codes.
This is what the URL looks like afterwards:
https://www.example.com/product-1/?couponCode=TDXGUA9G&utm_source=test&utm_medium=testt&utm_campaign=test&aff_code=TSJU89XYZ%0d%0a
The only thing that doesn't add %0d%0a is this:
 echo $cl;

But I want to be able to use the  tag so that the buyer doesn't have to click on a long URL link.

A: Try this
echo " Please click here to redeem the coupon";

If you still have the issue, check how $cl was created.

A: I really appreciate all the responses. But I just want to post the code that finally worked for me after 7 hours of work. I understand that it looks silly but this is the best I could do for now. Here's what worked for me:
    ?>
    <a href='<?php echo trim($cl); ?>'> Click here to take <?php echo ' '.$_product_name.'';

A: I just encountered the same issue, but I'm using ASP.NET. All I did was delete the single quote and type it again. Now it works.
<asp:HyperLink ... NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Name") %>' />

There were possibly some extra invisible characters which needed to be deleted.