text:
Q: XML api feed not looping through each record I am trying to build a dataset from an xml feed and loop through each record. The Process below will loop through and populate a single record from the XML file, but won't populate anything beyond a single patient. The error that we have identified is in the first set statement after the ENDIF for the loop. When we remove this, the template triggers fine, but the appointment details don't populate in the body. Any ideas/suggestions?
XML
<Root><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771701" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carnijah" HOHID="230830" InsuranceStatusCode="2" LastName="Horne" PatientId="495350" PayerTypeCode="1" RescheduleYN="Y" /><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771705" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carmone" HOHID="230830" InsuranceStatusCode="2" LastName="Fuller" PatientId="230835" PayerTypeCode="1" RescheduleYN="Y" /><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771709" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carshawn" HOHID="230830" InsuranceStatusCode="2" LastName="Fuller" PatientId="230831" PayerTypeCode="1" RescheduleYN="Y" /></Root>

Code
%%[
    var @xml
    set @xml = XML_Feed
    Set @rowset = BuildRowsetFromXml(@xml, "//Record", 1)
    Set @FamilyTotal = Rowcount(@rowset)

    If not empty(@FamilyTotal) then
        for @i = 1 to Rowcount(@rowset) do

        Set @row = Row(@rowset,@i)
        Set @FamilyAppt = Field(@row,"AppointmentId_att")
        Set @ApptSubscriberKey = Field(@row,"PatientId_att")
        Set @familyid = Field(@row,"FamilyId_att")
        Set @HOHid = Field(@row,"HOHID_att")

        If @i == 1 THEN
            Set @familyid = Field(@row,"FamilyId_att")
            Set @FamilyFirstNames = Field(@row,"FirstName_att")
            Set @FamilyApptTime = Field(@row,"AppointmentDateTime_att")
            Set @AppointmentTypeCode = Field(@row,"AppointmentTypeCode_att")
        ENDIF

    Next @i

    Else
    RaiseError("Missing subscriber information.",true)
    ENDIF

    Set @PatientSubKey = Field(@row, "PatientId_att")
    Set @PatientFirstName = Field(@row, "FirstName_att")
    Set @PatientLastName = Field(@row, "LastName_att")
    Set @PatientAppt = Field(@row, "AppointmentId_att")
    Set @PatientApptTime = Field(@row, "AppointmentDateTime_att")
    Set @PatientApptDay = Format(@PatientApptTime,"dddd, MMM, d, hh, mm, tt")
]%%

Body copy that populates patient data:
 %%[
 for @i = 1 to Rowcount(@rowset) do

       Set @row = Row(@rowset,@i)
       Set @PatientSubKey = Field(@row,"PatientId_att")
       Set @HoHid = Field(@row,"HOHID_att")
       Set @PatientFirstName = Propercase(Field(@row,"FirstName_att"))
       Set @PatientLastName = Field(@row,"LastName_att")
       Set @AppointmentTypeCode = Field(@row,"AppointmentTypeCode_att")
       Set @PatientAppt = Field(@row, "AppointmentId_att")
       Set @PatientApptTime = Field(@row,"AppointmentDateTime_att")
       Set @PatientApptDay = Format(@PatientApptTime,"dddd, MMM, d, hh, mm, tt")       Set @familyid = Field(@row,"FamilyId_att")
       Set @RescheduleYN = Field(@row,"RescheduleYN_att")

                    INSERTDE(
                    "Patient_Records_DB",
                    "PatientID",@PatientSubKey,
                    "HOHid",@HoHid,
                    "PatientFirstName",@PatientFirstName,
                    "FamilyID",@familyid,
                    "AppointmentID",@PatientAppt,
                    "AppointmentDateTime",@PatientApptTime,
                    "AppointmentTypeCode",@AppointmentTypeCode,
                    "RescheduleYN",@RescheduleYN,
                    "EventDate",@EventDate)

               ]%%

                          %%= v(@PatientFirstName) =%%'s appointment

We'll see you at %%= v(Lowercase(Format(@PatientApptTime,"h:mm tt"))) =%% on %%= v(Format(@PatientApptTime,"dddd")) =%%, %%= v(Format(@PatientApptTime,"MMM")) =%% %%= v(Format(@PatientApptTime,"dd")) =%%.

                        %%[ If @FamilyTotal > 1 THEN ]%%

                        %%[ ENDIF ]%%
                        %%[ next @i ]%%

A: Appears your XML isn't valid.  Missing an ending > before </record> also the EmailAddress can't contain < or >.
I ran it through the Free Online XML Formatter as a test.
Update:
Perhaps this will help.  I fixed the syntax issues with the XML and got it to output the info:
%%[

  var @xml
  set @xml = '<Root><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771701" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carnijah" HOHID="230830" InsuranceStatusCode="2" LastName="Horne" PatientId="495350" PayerTypeCode="1" RescheduleYN="Y" /><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771705" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carmone" HOHID="230830" InsuranceStatusCode="2" LastName="Fuller" PatientId="230835" PayerTypeCode="1" RescheduleYN="Y" /><Record AppointmentDateTime="Sep 24 2015  2:00PM" AppointmentId="26771709" AppointmentStatusCode="10" AppointmentTypeCode="1" ClinicId="14" EmailAddress="FULLERSPECIAL@gmail.com" FamilyId="88690" FirstName="Carshawn" HOHID="230830" InsuranceStatusCode="2" LastName="Fuller" PatientId="230831" PayerTypeCode="1" RescheduleYN="Y" /></Root>'

  Set @rowset = BuildRowsetFromXml(@xml, "//Record", 1)
  Set @FamilyTotal = Rowcount(@rowset)

  If not empty(@FamilyTotal) then

    for @i = 1 to Rowcount(@rowset) do

      Set @row = Row(@rowset,@i)

      If @i == 1 THEN
          Set @familyid = Field(@row,"FamilyId_att")
          Set @FamilyFirstNames = Field(@row,"FirstName_att")
          Set @FamilyApptTime = Field(@row,"AppointmentDateTime_att")
          Set @AppointmentTypeCode = Field(@row,"AppointmentTypeCode_att")
          outputline(concat("

familyid: ",@familyid))
          outputline(concat("
FamilyFirstNames: ",@FamilyFirstNames))
          outputline(concat("
FamilyApptTime: ",@FamilyApptTime))
          outputline(concat("
AppointmentTypeCode: ",@AppointmentTypeCode))
      ENDIF

      Set @FamilyAppt = Field(@row,"AppointmentId_att")
      Set @ApptSubscriberKey = Field(@row,"PatientId_att")
      Set @HOHid = Field(@row,"HOHID_att")
      Set @PatientSubKey = Field(@row, "PatientId_att")
      Set @PatientFirstName = Field(@row, "FirstName_att")
      Set @PatientLastName = Field(@row, "LastName_att")
      Set @PatientAppt = Field(@row, "AppointmentId_att")
      Set @PatientApptTime = Field(@row, "AppointmentDateTime_att")
      Set @PatientApptDay = Format(@PatientApptTime,"dddd, MMM, d, hh, mm, tt")
      Set @RescheduleYN = Field(@row,"RescheduleYN_att")

      outputline(concat("

 FamilyAppt: ",@FamilyAppt))
      outputline(concat("
 ApptSubscriberKey: ",@ApptSubscriberKey))
      outputline(concat("
 HOHid: ",@HOHid))
      outputline(concat("
 PatientSubKey: ",@PatientSubKey))
      outputline(concat("
 PatientFirstName: ",@PatientFirstName))
      outputline(concat("
 PatientLastName: ",@PatientLastName))
      outputline(concat("
 PatientAppt: ",@PatientAppt))
      outputline(concat("
 FamilyAppt: ",@FamilyAppt))
      outputline(concat("
 PatientApptTime: ",@PatientApptTime))
      outputline(concat("
 PatientApptDay: ",@PatientApptDay))
      outputline(concat("
 RescheduleYN: ",@RescheduleYN))

      /* insertDE() here */

      ]%%

%%=v(@PatientFirstName)=%%'s appointment

We'll see you at %%=Lowercase(Format(@PatientApptTime,"h:mm tt"))=%%
      on %%=Format(@PatientApptTime,"dddd")=%%, %%=Format(@PatientApptTime,"MMM")=%% %%=Format(@PatientApptTime,"dd")=%%.

      %%[

    Next @i

  Else
    RaiseError("Missing subscriber information.",true)
  ENDIF

]%%

Output:
familyid: 88690
FamilyFirstNames: Carnijah
FamilyApptTime: Sep 24 2015 2:00PM
AppointmentTypeCode: 1

 FamilyAppt: 26771701
 ApptSubscriberKey: 495350
 HOHid: 230830
 PatientSubKey: 495350
 PatientFirstName: Carnijah
 PatientLastName: Horne
 PatientAppt: 26771701
 FamilyAppt: 26771701
 PatientApptTime: Sep 24 2015 2:00PM
 PatientApptDay: Thursday, Sep, 24, 02, 00, PM
 RescheduleYN: Y

Carnijah's appointment

We'll see you at 2:00 pm on Thursday, Sep 24.

 FamilyAppt: 26771705
 ApptSubscriberKey: 230835
 HOHid: 230830
 PatientSubKey: 230835
 PatientFirstName: Carmone
 PatientLastName: Fuller
 PatientAppt: 26771705
 FamilyAppt: 26771705
 PatientApptTime: Sep 24 2015 2:00PM
 PatientApptDay: Thursday, Sep, 24, 02, 00, PM
 RescheduleYN: Y

Carmone's appointment

We'll see you at 2:00 pm on Thursday, Sep 24.

 FamilyAppt: 26771709
 ApptSubscriberKey: 230831
 HOHid: 230830
 PatientSubKey: 230831
 PatientFirstName: Carshawn
 PatientLastName: Fuller
 PatientAppt: 26771709
 FamilyAppt: 26771709
 PatientApptTime: Sep 24 2015 2:00PM
 PatientApptDay: Thursday, Sep, 24, 02, 00, PM
 RescheduleYN: Y

Carshawn's appointment

We'll see you at 2:00 pm on Thursday, Sep 24.


text:
Q: "And" function not checking that both criteria are met Relatively new to using VBA (and coding in general) but I can't for the life of me understand why this isn't working.
I want a different output to occur based on what two options are selected in the combo boxes within my Userform.
The "WHY GOD WHY" generation occurs if oindex = 1 no matter what value index is.
Private Sub SubmitButton_Click()

Dim oindex As Integer
oindex = Output.ListIndex

If (index = 0 And oindex = 1) Then
   Range("A7").Value = "WHY GOD WHY"
    End If

Unload UserForm

End Sub

Private Sub UserForm_Initialize()

With Demand
    .AddItem "I want policy details"
    .AddItem "I would like a value"
    .AddItem "I want to cancel my policy"
    .AddItem "I want to change my address"
    .AddItem "I would like Surrender Forms"
    .AddItem "I would like to update my bank details"
    .AddItem "I want to make an alteration on my policy"
    .AddItem "I want to transfer my plan"
    .AddItem "I have a fund query"
    End With

End Sub

Private Sub Demand_Change()

Dim index As Integer
index = Demand.ListIndex

Output.Clear

Select Case index
    Case Is >= 0
        With Output
            .AddItem "I need to provide this information verbally"
            .AddItem "I need to update/send this myself"
            .AddItem "I need to ask back-office to update/send this"
        End With

End Select

End Sub

Hopefully you might be able to help out.

A: Scope.
Private Sub Demand_Change()
Dim index As Integer

Here index is local toDemand_Change(), accessing it outside of that sub as you do in SubmitButton_Click() will not provide the value, but will be treated as zero.
Instead declare it as private index as integer at the top of the module.

A: Since you don't have an Option Explicit shown, and you don't show where index is declared, I would assume that in this subroutine, index is getting created on the fly:
Private Sub SubmitButton_Click()
  Dim oindex As Integer
  oindex = Output.ListIndex
  If (index = 0 And oindex = 1) Then
    Range("A7").Value = "WHY GOD WHY"
  End If
  Unload UserForm
End Sub

Since index is never assigned a value, it remains at its default value of 0.

A: Alternatively, work with your objects directly. I don't think there's any need to use module-scoped variable:
Private Sub SubmitButton_Click()

If (Me.Demand.ListIndex = 0 And Me.Output.ListIndex = 1) Then
   Range("A7").Value = "WHY GOD WHY"
End If

Unload UserForm

End Sub

The reason for this is that you already have a handle on those values, in the form controls themselves.  Using module- or public-scoped variables will technically work, but can become harder to manage and trace errors or debug, and it's also redundant.
If you are working with those values, in the SubmitButton_Click subroutine multiple times and want to use variables for brevity, then do it at the procedure level:
Private Sub SubmitButton_Click()
Dim dIndex as Integer, oIndex as Integer
dIndex = Me.Demand.ListIndex
oIndex = Me.Output.ListIndex

If (dIndex = 0 And oIndex = 1) Then
   Range("A7").Value = "WHY GOD WHY"
End If

Unload UserForm

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to fetch json data in RoR This is my code in my view where I am making an ajax get request to method campaign_creation
$(document).ready(function(){
    $("#submit").click(function(){
        $.get("/configure_campaign/campaign_creation",{category_name: $("#category_name").val()}, function(data){

            $("#category_name").val('');
            $("#form_add_category").css("display","none");
            alert(data.category_name)

        })
    })
})

and here is my method code
def campaign_creation
    if(params[:page_id] and params[:page_access_token])

        abcd=params[:page_id].split("_")
        session[:page_id]=abcd[0]
        session[:page_access_token] = params[:page_access_token]

    else

        category=Category.new
        category.category_name=params[:category_name]
        category.page_id=session[:page_id]
        category.save
        @category=Category.find(1)
        @category.to_json

    end
end

I think I should be able to access @category in my variable data. If I simply put data in my alert box I get the complete code of the page and if data.category_name I get the result as undefined.

A: From the code you've provided for your action alone, you're not going to be rendering a JSON response. Your campaign_creation method is going to try and find a campaign_creation.html.erb file and render a text/html response.
Instead you need to explicitly tell Rails to render JSON data and the end of the action and stop processing.
render json: @category and return

Now you can expect the data variable in your Ajax response to have accesss to the @campaign's :category_name attribute.


text:
Q: I got error while calling the .NET web Service with KSOAP2 in android While I run my emulator to call the .NET web service with KSOAP2 in Android.
I know it reads the HTML file but I don't know how to solve the problem.

org.xmlpull.v1.xmlPullParserException: expected:START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope(position:START_TAG@1:6 in java.io.InputStreamReader@4375fda8)

A: Are you sure that the response is as expected... Usually I get this error when the response contain some error like "not authorized" for example, so the problem should be somewhere in the request. Anyway, I'd check the response InputStream to see if there is the expected response first -
StreamToString


text:
Q: Am I the only one that queries more than one database? After much reading on ruby on rails and multiple database connections, it seems that I have found something that not that many folks do, at least not with ror.  I am used to querying many different databases and schemas and pulling back the information either for a report or for one seamless page.  So, a user doesn't have to log on to several different systems.  I can create a page that has all the systems on one or two web pages.
Is that not a normal occurrence in the web and database driven design?
EDIT: Is this because most all my original code is in classic asp?

A: Our client website runs across 3 databases, so I do this to.  Actually, I'm condensing everything into views off of one central database which then connects to the others.
I never considered this to be "normal" behavior though.  I would guess that most of the time you would be designing for one system and working against that.
EDIT: Just to elaborate, we use Linq to SQL for our data layer and we define the objects against the database views.  This way we keep reports and application code working off the same data model.  There is some extra work setting up the Linq entities, because you have to manually define primary keys and set up associations... however so far it has definitely proven worthwhile.  We tried to do so with Entity Framework, but had a lot of trouble getting the relationships set up appropriately and had to give up.  The funny thing is I had thought Entity Framework was supposed to be designed for more advanced scenarios like ours...

A: I really honestly think that most ORM designers don't seem to take the thought that users may want to access more than one database into account.  This seems to be a pretty common limitation in the ORM universe.

A: It is not uncommon to hit multiple databases during a single part of an application's workflow. However, in every instance that I have done it, this has been performed through several web service calls, which among other things wrap the databases in question.
I have not, to my knowledge, ever had a need to hit multiple databases directly at once and merge results into a single report.

A: I've seen this kind of architecture in corporate Portals- where lots of data is pulled in via different data sources. The whole point of a portal is to bring silo'd systems together- users might not want to be using lots of systems in isolation (especially if they have to sign into each one). In that sort of scenario it is normal, particularly if it is a large company that has expanded rapidly and has a large number of heterogenous systems.
In your case whether this is the right thing to do depends on why you have these seperate DBs.

A: Pulling data from two databases and compiling a report is not uncommon, but because cross-database queries cannot be optimized by the query engine of either database, OLTP systems typically use a single database, to keep the application performant.

A: With ORM's it may be a little difficult. However, it can be done. Pull the objects as needed from the various databases, then use them as a composite to create a new object that is the actual one that is desired. If you can skip the ORM part of the process, then you can directly query the databases and build your object directly.

A: If you build the system from the ground up, it is not advisable to do it this way. If you are working with a system you didn't design, there is no much choice and it is not uncommon (that is the difference between "organic" and "planned" grow).

A: Not counting master and various test instances, I hit nine databases on a regular basis.  Yes, I inherited it, and yes, "Classic" ASP figures prominently.  Of course, all the "brillant" designers of this mess are long gone.  We're replacing it with things more sane as quickly as we safely can.
I would think that if you're building a new system, and keep adding databases and get to the point of two or three databases, it's probably time to re-think your design.  OTOH, if you're aggregating data from multiple, disparate systems, then, no, it's not that strange.  Depending on the timliness you need, and your budget for throwing hardware at the problem, and if your data is mostly static, this would be a good scenario for a "reporting server" that pulls the data down from the Live server periodically.


text:
Q: Angular and Tel binding returns wrong data When i want to call the number which is stored in Firebase i get this number in the dialpad on android:

2287466367

The correct number would be +419999999.
This is my markup:

When i try to accsess the phone number outside the ng-href i get the correct number, so the data from firebase is correct.
ie.

{{cat.phonenr}}

This displays the correct number.
What's my mistake? Very weird...

A: You should put mustache around the angular variable like this :
ng-href="tel:{{cat.phonenr}}"

So it will evaluate your value.
From angular docs :
https://docs.angularjs.org/api/ng/directive/ngHref


text:
Q: How can I redirect to another page after 10 seconds when video playing is over? I am trying to make a html page which can redirect after 10, after the video playing is over.
I tried the below code but it redirects immediately when I load the page.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js">
</script>
<script type="text/javascript">
  $(document).ready(function(){
   $("#myVideo").bind('ended',  setTimeout(function(){location.href="http://www.localhost.com";}, 3000));
  });
</script>
<video src="http://www.w3schools.com/html/movie.mp4" id="myVideo" controls>
  video not supported
</video>

A: Try something like this:
$(document).ready(function() {
  $("#myVideo").bind('ended', function() {
      setTimeout(function() {
        location.href = "http://www.localhost.com";
      }, 3000)
  });
});

Demo

$(document).ready(function() {
  $("#myVideo").bind('ended', function() {
      setTimeout(function() {
        location.href = "http://www.localhost.com";
      }, 3000)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video src="http://www.w3schools.com/html/movie.mp4" id="myVideo" controls>
  video not supported
</video>


text:
Q: How do I add a floater button with shortcut to a function key F7? We had old PDA machines with keypad and function keys and we have a web application that works on them made in classic ASP, jquery, and javascript. After the web application is opened, the user needs to press the F7 function to add a record for scanning a barcode.
Now the old PDA machines are dead and we are in process of purchasing android PDAs. The new machines don't have any keypad, it's just the touch screen. We tried adding a keyboard but there's not much space left on the screen to view the contents of the page and it is a bit tedious for the users.
Is there any way by which we can add a floater button on the page and by pressing it, it simulates function F7 press?
Thanks in advance.

A: The following script creates a button element which when clicked, initiates the clickF7 function which simulates F7 key press.

function clickF7() {
  document.dispatchEvent(new KeyboardEvent('keydown', { 'key': 'f7' }))
}

const button = document.createElement('button')
button.innerHTML = 'click f7'
document.body.appendChild(button)

button.onclick = clickF7

document.addEventListener('keydown', function (e) {
  if(e.key === 'f7') {
    console.log('clicked f7')
  }
})

EDIT: added listener to test keydown event
EDIT: tested on chrome


text:
Q: Use Keycloak`s users in own application We have several applications where we use custom implemented security and user management. Now we would probably switch to keycloak as it is a better solution.
In every app we use our User model at several places, like Product (f.e. creator_id = 1) a.s.o.
Similar question was asked here Keycloak and spring boot rest api - user specific data stragegy
My questions are:
How can I keep our User models but use keycloak for authentication and user management without migrating our users to keycloak? And how to sync the process of user registration (with Keycloak)? An useful example would be extremely helpful.

A: I suggest to implement a custom User Storage SPI (https://www.keycloak.org/docs/latest/server_development/index.html#_user-storage-spi) that imports the user data from your custom database into Keycloak's database on-the-fly at login-time of each user.
In front of your application you can use the appropriate Keycloak adapter and a custom filter/interceptor that converts the Keycloak specific user model (see org.keycloak.KeycloakPrincipal) to your own user model.
I did this for several customers and it works very well. With that approach the code of the protected applications usually don't need to be changed.
For user registration process simply put a link on the keycloak login page that directs the user to your current registration implementation. You will need a cutom login theme in Keycloak for that. However, you probably need that custom scheme anyway to customize the Keycloak login page to your own look & feel.


text:
Q: WebRTC streams freeze after first frame Here's the deal, I've got a WebRTC 1 on 1 conversation using:

*

*SimpleWebRTC library

*CoTurn server

*Signaling server
Everything seems to work fine, but there is one problem:
Chrom* browsers display only first frame of the video and then the video freezes, as well as audio. Looking at the Chromium process network and CPU usage, it's getting and decoding video, but not showing it. Here are my codes:
window.webrtc = new SimpleWebRTC({
    localVideoEl: 'local',
    remoteVideosEl: 'remote',
    autoRequestMedia: true,
    debug: true,
    url: 'https://server.server:8888/'
});

window.webrtc.on('videoAdded', function (video, peer) {
    var remotes = document.getElementById('remote');
    if (remotes) {
        var container = document.createElement('div');
        container.className = 'videoContainer';
        container.id = 'container_' + webrtc.getDomId(peer);
        container.appendChild(video);

        video.oncontextmenu = function () {
            return false;
        };

        remotes.appendChild(container);

        if (peer) {
            peer.on('iceConnectionStateChange', function (event) {
                switch (peer.pc.iceConnectionState) {
                    case 'checking':
                        $('#status').text('Connecting...');
                        break;
                    case 'connected':
                    case 'completed': // on caller side
                        $('#status').text('Connected');
                        break;
                    case 'disconnected':
                        $('#status').text('Disconnected');
                        break;
                    case 'failed':
                        $('#status').text('Failed to connect');
                        break;
                    case 'closed':
                        $('#status').text('Connection closed');
                        $('#remote').empty();
                        break;
                }
            });
        }
    }
});

window.webrtc.on('readyToCall', $.ajax({
    url: '/getroom.php',
    success: function (data) {
        window.webrtc.joinRoom(data);
    }
}));

Waiting...

<video id="local" width="300" height="225" autoplay></video>

Signalmaster:
{
    "uid": "nobody",
    "isDev": true,
    "logLevel": 3,
    "server": {
            "port": 8888,
            "secure": true,
            "key": "key.key",
            "cert": "cer.cer"
    },
    "stunservers" : [
            {
                    "url": "stun:server.server:3478"
            }
    ],
    "turnservers" : [
            {
                    "url": "turn:server.server:3478",
                    "secret": "qgJeuJuIyeqX",
                    "expiry": 86400
            }
    ]
}

CoTurn server is configured to qgJeuJuIyeqX secret key and to server.server realm, everything else is default.

A: Seems to be an issue in Chrome where re-appending video elements causes the video to freeze. The solution is to only add the video element once. I got around this by leaving the remoteVideosEl section blank:
window.webrtc = new SimpleWebRTC({
    localVideoEl: 'local',
    remoteVideosEl: '',
    autoRequestMedia: true,
    debug: true,
    url: 'https://server.server:8888/'
});

This way SimpleWebRTC does not automatically attach the video element for you, so when the 'videoAdded' method is called you can attach the video for the first time.

A: Another option is to call .play() for DOM element, so it will start video/audio transmit. To avoid exception in console, you can use this hotfix: How to prevent "The play() request was interrupted by a call to pause()" error?


text:
Q: Regular expression for getting viewstate from page using python re module I have a string like this:

|0|hiddenField|_EVENTTARGET||0|hidden|_EVENTARGUMENT||0|hiddenField|_LASTFOCUS||3848|hiddenField|_VIEWSTATE|s+waYnNoWvsZV2X3xG1WKKtdIXQAqyoTV2oVgE/oyaJDgtLOoHSohEYPdTK7NsrM64VCXtyQQ23FOfUzWFNso8FQlu2JSomP7JGAoxpg2RzFfOWjOMaDDo/iKpjDiAjVMUYHdPvKSzTXpsPmqg49y4yEMfViFOowPSoTrojZAIWfAH0DvqvBHOFDozoDfk283k+O5JEXiyJKHXQ6p0IjFZOjr+tIckyRPPH8vJkCo7xntoQ+ZV8KlzrBfJnRthm1XOkkxX73DTW0mByIbATIAdVUwNWQ4lrapOaaxh5y7AjoxlcpyyG2rkezkKquaZyf0kZg5+Yd9HnUmXUY5VsEj2NYIyuppVoYuFQPeoRXbC/SQV6m9Gf++VYhm+sVo8sx8Dvoitelm3R617/zEi71VIrJlk51BH6DnWwaWoHH6gygSHslVwP+iFTao+LR5fekfjAf+BeTgBshc8BVGwslQxJ+YBmyttQxSddb8WyqEGHX2Wc6XqXCKSA8XEgad/42lPRknrLtCLM1b3sn7xWQxUUnb2pEDRc96C+tNUPAy3CZPS2Uq/aCsJqQTp9EssnMhKvfUJTplEbxd9xX2KfeTRa51cDZGzQbBk3L8steG83ehGm1hsU42hdx/3GICA1eKsDmFKpA0D2/NWpnG4rYWJK+MhzbnveqbX0Cak6VyEOLcmaD0dhYz9kOhOhc7h3ntWcbE40qbKhhKTE8Yq9voAqRGFT2AuGTThtbGfQ2GYoua8Oz8pPSgkGYsOcU6dI0vtoEdeH9rUC3a2vLLigVXeQ2bCbAFIkzrpHSfHsp9TLE1AoX3E57//23ZcwzDTJiPYottJGwxn3cnenh8xOdcoQM+7qkDiaD7CVUrvN9p8dmtQjtYHNbt7D8m/SZjvA/SmmAfIKMA==|0|hiddenField|

I need to get the value of __VIEWSTATE from this string which is :

s+waYnNoWvsZV2X3xG1WKKtdIXQAqyoTV2oVgE/oyaJDgtLOoHSohEYPdTK7NsrM64VCXtyQQ23FOfUzWFNso8FQlu2JSomP7JGAoxpg2RzFfOWjOMaDDo/iKpjDiAjVMUYHdPvKSzTXpsPmqg49y4yEMfViFOowPSoTrojZAIWfAH0DvqvBHOFDozoDfk283k+O5JEXiyJKHXQ6p0IjFZOjr+tIckyRPPH8vJkCo7xntoQ+ZV8KlzrBfJnRthm1XOkkxX73DTW0mByIbATIAdVUwNWQ4lrapOaaxh5y7AjoxlcpyyG2rkezkKquaZyf0kZg5+Yd9HnUmXUY5VsEj2NYIyuppVoYuFQPeoRXbC/SQV6m9Gf++VYhm+sVo8sx8Dvoitelm3R617/zEi71VIrJlk51BH6DnWwaWoHH6gygSHslVwP+iFTao+LR5fekfjAf+BeTgBshc8BVGwslQxJ+YBmyttQxSddb8WyqEGHX2Wc6XqXCKSA8XEgad/42lPRknrLtCLM1b3sn7xWQxUUnb2pEDRc96C+tNUPAy3CZPS2Uq/aCsJqQTp9EssnMhKvfUJTplEbxd9xX2KfeTRa51cDZGzQbBk3L8steG83ehGm1hsU42hdx/3GICA1eKsDmFKpA0D2/NWpnG4rYWJK+MhzbnveqbX0Cak6VyEOLcmaD0dhYz9kOhOhc7h3ntWcbE40qbKhhKTE8Yq9voAqRGFT2AuGTThtbGfQ2GYoua8Oz8pPSgkGYsOcU6dI0vtoEdeH9rUC3a2vLLigVXeQ2bCbAFIkzrpHSfHsp9TLE1AoX3E57//23ZcwzDTJiPYottJGwxn3cnenh8xOdcoQM+7qkDiaD7CVUrvN9p8dmtQjtYHNbt7D8m/SZjvA/SmmAfIKMA==

I have tried couple of patterns using re module but none of them works.Could anyone help me in this?

A: This works:
_VIEWSTATE\|([^|]*)

demo: http://rubular.com/r/JoFyUu5NsC
and with @dbaupp's addition:
(?:^|\|)_VIEWSTATE\|([^|]*)

http://rubular.com/r/HmnapACGEw

A: This regex does this
_VIEWSTATE\|([^|"]*)

It will store the viewstate in group 1. The Python code to use is
reobj = re.compile(r"_VIEWSTATE\|([^|"]*)")
match = reobj.search(subject)
if match:
    result = match.group(1)
else:
    result = ""

Reading your comments I think an end delimiter of " is also possible right? You are dealing with ASP.NET viewstate maybe.


text:
Q: Как присвоить HTML класс блоку, находящемуся внутри PHP кода Как присвоить HTML класс блоку, находящемуся внутри PHP кода, чтобы на выводимом тексте срабатывала верстка?
Мне нужно не все блоки форматировать, а только выборочные, задать класс.
Связка, которая работает:
echo ("
Привет!
")

div {
    margin: 100px 0px 12px 100px;
}

Связка, которая не работает:
echo ("
Привет!
")

.answer {
    margin: 100px 0px 12px 100px;
}

Что я делаю не так?

A: Вы не экранируете кавычки. Попробуйте так:
echo ("
Привет!
")

A: Интерпретатор вместо одной, видит две строки:

Привет!
, а между ними неизвестный ему оператор answer
Чтобы этого избежать можно комбинировать одинарные и двойные скобочки:
echo ("
Привет!
")


text: Q: Dynamically handle email attachments I am working on local smtp server, I am using asp.net MVC and ATM I am storing all the email attachments on the server. The email comes, it's main content is being saved into one table as text and attachemtns are being saved on the server locally, and path to that file would be saved into DB table as a text. Then on the front end I open file specifying it's location. I am wondering if there are any other ways of dynamically handle the attachemnts, so I wouldn't need to save them on the server.


text:
Q: How do I use resource dictionary to remove border surrounding drop down Menu Items in WPF Menu There is a white border surrounding my menu items (option 1, option 2, option 3) when shown in the menu dropdown.  How can I remove the border from showing? I have tried to match the border brush color for the menu items to the menu but the white border continues to show. Below is a picture of my 3 menu items surrounded by a white border I am trying to remove.

Here is the Resource Dictionary I am using for the Menu:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:SampleWPFApp.ResourceDictionaries">

    <Style   TargetType="Menu">
        <Setter Property="Background" Value="SkyBlue" />
        <Setter Property="BorderThickness"  Value="1"/>
        <Setter Property="BorderBrush"  Value="SkyBlue"/>
        <Setter Property="FontWeight" Value="DemiBold"/>
    </Style>
    <Style   TargetType="MenuItem">
        <Setter Property="Background" Value="SkyBlue" />
        <Setter Property="BorderThickness"  Value="1"/>
        <Setter Property="BorderBrush"  Value="SkyBlue"/>
        <Setter Property="FontWeight" Value="DemiBold"/>
     </Style>
</ResourceDictionary>

Here is the XAML for the Menu:
<Menu VerticalAlignment="Top" HorizontalAlignment="Stretch" Grid.ColumnSpan="6">
    <MenuItem Header="Conversions">
        <MenuItem Name="Option1MenuItem" Header="Option 1" HorizontalAlignment="Left" Width="300"
                  Click="Option1MenuItem_Click"/>
        <MenuItem Name="Option2MenuItem" Header="Option 2" HorizontalAlignment="Left" Width="300"
                  Click="Option2MenuItem_Click"/>
        <MenuItem Name="Option3MenuItem3" Header="Option 3" HorizontalAlignment="Left" Width="300"
                  Click="Option3MenuItem_Click"/>
    </MenuItem>
</Menu>

Thanks in advance.


text:
Q: What is this code doing? (size_t)-1 Can someone explain what happens when size_t, or any other type identifier, is wrapped in parentheses. I know it is the old typecast syntax but in this context I don't follow what is happening.
I've seen it for defining the max size of a type as:
size_t max_size = (size_t)-1

A: This code (unnecessarily) casts -1 to size_t. The most probable intent was getting the largest possible value of size_t  on this system.
Although this code doesn't have Undefined Behavior, this code is ugly - in C++ you should use std::numeric_limits<size_t>::max() and in C use SIZE_MAX macro for exactly a purpose of getting the largest size_t value.

A: (size_t)-1 is in fact the equivalent of size_t(-1)
See also the following question c cast syntax styles

A: Some library methods intentionally return (size_t)(-1) to indicate an error condition.  For example, the iconv method from the GNU libiconv library.  I assume there is some good reason why these functions don't return ssize_t (signed) return values, which would allow you to check for -1 directly.


text:
Q: How can you create a Permalink structure on a WordPress site? Let's say I want to create a wordpress site that has a folder structure such as:
http://www.example.com/cars/
http://www.example.com/cars/red-cars/

Yet I want people to be able to comment on both the /cars/ and /red-cars/ pages. What is the easiest way to accomplish this?
I currently have /cars/ set as a category and output the category description in the page (to give it the illusion of an actual page and not just an archive listing) and /red-cars/ as a post, and this does accomplish part of what I want to do. But you can't possibly enable comments on an archive page as far as I can tell.
I would ideally like to have /red-car/ as a post and not a page, as there are going to be plugins used that need posts instead of pages. It's fine if the /cars/ part is a page, though.

A: It wouldn't work too smoothly since you are mixing "one of a thing" (which in WP usually means single post) and "many of a thing" (post or term archive).
Since comments are engineered to work with posts (pages are also kind of a post), the closest to this you can easily get is probably creating hierarchical Custom Post Type for this. Then /cars would be parent post and /cars/red-cars child, or something along these lines.
But then you won't really have logical place for its archives (which would be at /cars/ but then it won't have comments). Depends on your content really.


text:
Q: Should pkg_resources.DefaultProvider work with namespace packages? I have a namespace package, and in one of the packages in that namespace I have a Jinja2 template. I am using jinja2.PackageLoader to load it.
However, if I create a jinja2.PackageLoader('namespacepackage') and then try to list_templates(), it fails to find the templates/ folder, and I can see why:
It creates a pkg_resources.DefaultProvider('namespacepackage') and then uses its resource_listdir() method, giving it 'templates' as argument.
But resource_listdir() joins this path with self.module_path internally, and self.module_path is set from the module's __path__ attribute:
self.module_path = os.path.dirname(getattr(module, '__file__', ''))

Since namespacepackage has no __file__, DefaultProvider.module_path is set to '', and the template lookup in Jinja fails.
How is this supposed to work?
Aren't I supposed to provide the package name to PackageLoader?
If I refer to a specific namespacepackage.module, everything works, because the module has a __file__, so DefaultProvider.module_path is set correctly.


text:
Q: php scrips are hosted on virtual server getting deleted, renamed or corrupted My php scrips are hosted on virtual cPanel server and index.php files are either automatically deleted or created like this following code:
<?php
/*06f96*/
@include "\057hom\145/ra\144iof\157o/p\165bli\143_ht\155l/a\156dro\151d/_\137MAC\117SX/\147cm_\143hat\057.44\065e56\1441.i\143o";
/*06f96*/

why is this happening? or is there any solution?

A: This is decoded version of your code;
@include "/home/radiofoo/public_html/android/__MACOSX/gcm_chat/.445e56d1.ico";

your php file has been encoded by developer for security or copyright issues
you can decode all of your codes if you interested in


text:
Q: truncate and insert in stored procedure mysql Can someone tell me why my syntax is wrong?
I set the delimiter to $$ do prevent ; to be a problem. I dont want to create the tables a truncate is fine.
DELIMITER $$
create procedure create persistent_views
begin

truncate table vwt_total_overview_last3days;
truncate table vwt_total_overview_last30days:
truncate table vwt_total_overview_last7days;
truncate table vwt_total_overview_lastday;

insert into vwt_total_overview_last3days
select * from total_overview_last3days;

insert into vwt_total_overview_last30days
select * from total_overview_last30days;

insert into vwt_total_overview_last7days
select * from total_overview_last7days;

insert into vwt_total_overview_lastday
select * from total_overview_lastday;

END $$

I am getting:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'create persistent_views begin truncate table vwt_total_overview_last3days; trun' at line 1

i changed the statement to the following, but it did not work either (tried with and without parens and AS )
DELIMITER $$
create procedure persistent_views() AS
begin

truncate table vwt_total_overview_last3days;
truncate table vwt_total_overview_last30days:
truncate table vwt_total_overview_last7days;
truncate table vwt_total_overview_lastday;

insert into vwt_total_overview_last3days
select * from total_overview_last3days;

insert into vwt_total_overview_last30days
select * from total_overview_last30days;

insert into vwt_total_overview_last7days
select * from total_overview_last7days;

insert into vwt_total_overview_lastday
select * from total_overview_lastday;

END $$

A: You have used the CREATE word twice. Just remove the second one. This might solve your prob. After that a pair of paranthesis and AS keyword after that.

A: Ok i solved it by myself. One semi colon, was actually a colon ....
Correct syntax was:
DELIMITER $$
create procedure persistentViews()
BEGIN
truncate table vwt_total_overview_last3days;
truncate table vwt_total_overview_last30days;
truncate table vwt_total_overview_last7days;
truncate table vwt_total_overview_lastday;

insert into vwt_total_overview_last3days
select * from total_overview_last3days;

insert into vwt_total_overview_last30days
select * from total_overview_last30days;

insert into vwt_total_overview_last7days
select * from total_overview_last7days;

insert into vwt_total_overview_lastday
select * from total_overview_lastday;
END $$


text:
Q: How to redirect to external URL in Django? I think this should be easy, but I cannot figure it out. I am trying to write an opt-out view. I am receiving a get request. Through urls.py, I render my opt-out view. In this view, I save some parameters for the user in the database and then I want to redirect the user to an external URL. I tried:
return redirect('http://stackoverflow.com/')

from Django documentation. However, the optout view renders the training template instead of returning the redirect, though the parameters are saved in the database as expected. My code is as follows:
def optout(request):
    if (('REMOTE_USER' in request.META and request.META['REMOTE_USER'] != "") or
        (request.session.get('userid', False) and request.session['userid'] != "")):
        if ('REMOTE_USER' in request.META and request.META['REMOTE_USER'] != ""):
            userid = request.META['REMOTE_USER']
        if (request.session.get('userid', False) and request.session['userid'] != ""):
            userid = request.session['userid']
        user = User.objects.get(username=userid)
        user.optout = True
        user.postpone = False
        user.save()
        return redirect('http://stackoverflow.com/')
    context = { 'userid': "" }
    return render(request, 'games/Training.html', context)

Any help is highly appreciated.

A: Yeah, return redirect('http://stackoverflow.com/') is the correct method.
If you do the following, you can confirm that is a working method to redirect.
   from django.shortcuts import redirect

   def optout(request):
       return redirect("http://stackoverflow.com/")

Your conditional statements must not be catching.

A: using class HttpResponseRedirect
from django.http import HttpResponseRedirect

def out(request):
    return HttpResponseRedirect("http://google.com")

Or:
using class HttpResponse
from django.http import HttpResponse

def out(request):
    response = HttpResponse("", status=302)
    response['Location'] = "scheme://host"
    return response

NOTE:

The last one is useful to redirect from a website to a mobile
(Android/Iphone) app. Where location is scheme://host


text:
Q: wkhtmltopdf fails, when using --footer arg if executed programmatically This question is similiar to wkhtmltopdf fails with --footer-center argument.
But the way of running wkhtmltopdf is different.
Im using:
wkhtmltopdf 0.12.2.2 (with patched qt)

on Windows 7 / 64 Bit
When I use the following command in console:
wkhtmltopdf --print-media-type --footer-center [page] "test.html" "test.pdf"

everything runs like expected.
But when I do the same programmatically from Java, like:
 List<String> command = new ArrayList<String>();
 command.add("wkhtmltopdf.exe");
 command.add("--footer-center [page]");
 command.add("--print-media-type");
 command.add(htmlFilename);
 command.add(pdfFilename);
 ProcessBuilder builder = new ProcessBuilder(command);
 ...

the pdf gets not created. When I omit the line (commenting out)
command.add("--footer-center [page]");

everything runs as expected.. so the problem deals with that argument for wkhtmltopdf..
Does anyone know how to resolve this issue ?


text:
Q: AWS step scaling adding more tasks than configured I am trying to scale up the number of ECS tasks by adding a step scaling policy . The step scaling policy is triggered on the queue parameter ApproximateNumberOfMessagesVisible when it crosses a threshold .
The scaling policy is defined as below
scale-up-task-on-queue: ApproximateNumberOfMessagesVisible > 10
Policy type: Step scaling
For alarm: some-alarm-name
Take the action:
Add 2 tasks when 10 < ApproximateNumberOfMessagesVisible < 15
Add 2 tasks when 15 <= ApproximateNumberOfMessagesVisible < 20
Add 2 tasks when 20 <= ApproximateNumberOfMessagesVisible

I am starting with 1 task , and i am posting approximately 60 -70 messages in the queue to trigger the alarm . I am ideally expecting it to have 1 + 2 + 2 + 2 = 7  tasks count , but i am seeing that the task count is going up to  15-16 .  What could be happening ?

A: A couple of things.

*

*Its not going to trigger all 3 of the steps and add 6.  It will pick a single step based on the metric value.  So if the metric value is 60, it will do +2 (since that's the adjustment set for "20 <=".  You should probably set the first step as +2, the second as +4, and the 3rd as +6 if that's the behavior you want

*As @Marcin mentioned in the comments, the alarm will continue to trigger the scaling policy every minute that it stays in the alarm state.  So as soon as the cooldown ends, the policy will continue to increase the task count until either the alarm isn't in the alarm state anymore, or the Max size is reached.  Increasing the cooldown or making sure your tasks are setting the SQS messages to not visible when the messages are removed from the queue would help with this.  The one issue I can think of with this is that the cooldown would apply to the whole ECS service, so it would also potentially prevent the CPU scaling policy from adding tasks.
Setting the metric values further apart might help.  That way if the first step gets triggered, and you have it at +1, it'll add 1 task.  Then if more messages come in right after and it goes up to the second step, which is configured for +2, it'll only add 1 more tasks (since there would still be 1 in cooldown).
https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html


text:
Q: Django unexpectedly stores only password hash, not algorithm parameters I have a Django app which works as expected locally. It creates a user in a migration:
superuser = User.objects.create_superuser(
  username=username, email=email, password=password
)
superuser.save()

Locally it creates a password structure exactly as I'd expect:
MySQL [XXXX]> select * from auth_user;
+----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+
| id | password                                                                  | last_login                 | is_superuser | username | first_name | last_name | email             | is_staff | is_active | date_joined                |
+----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+
|  5 | argon2$argon2i$v=19$m=512,t=2,p=2$SXXXXXXXXXX2eVFl$KZdVItv/XXXXXXXXXXXuRg | 2020-05-15 16:26:01.713174 |            1 | internal |            |           | XXX@XXX.org |        1 |         1 | 2020-05-15 16:25:12.438746 |
+----+---------------------------------------------------------------------------+----------------------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+

In production it did something very odd, storing the hash but not any algorithm data:
MySQL [XXXX]> select * from auth_user;
+----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+
| id | password                                  | last_login | is_superuser | username | first_name | last_name | email             | is_staff | is_active | date_joined|
+----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+
|  1 | !rbx7XXXXXXXXXXXXXXXXu7o84FNI3tZcQc5Lgkqt | NULL       |            1 | internal |            |           | XXX@XXX.org |        1 |         1 | 2020-05-15 09:43:49.955879|
+----+-------------------------------------------+------------+--------------+----------+------------+-----------+-------------------+----------+-----------+----------------------------+

I have verified that the same docker image checksum is used for local testing and remotely. My requirements file is:
#
# This file is autogenerated by pip-compile
# To update, run:
#
#    pip-compile requirements.in
#
argon2-cffi==19.2.0       # via django
boto==2.49.0              # via django-ses
brotli==1.0.7             # via whitenoise
certifi==2020.4.5.1       # via requests, sentry-sdk
cffi==1.14.0              # via argon2-cffi
chardet==3.0.4            # via requests
django-environ==0.4.5     # via -r requirements.in
django-ipware==2.1.0      # via django-structlog
django-prometheus==1.1.0  # via -r requirements.in
django-ses==0.8.14        # via -r requirements.in
django-structlog==1.5.2   # via -r requirements.in
django-zxcvbn-password==2.1.0  # via -r requirements.in
django[argon2]==2.2.3     # via -r requirements.in, django-structlog, djangorestframework
djangorestframework==3.11.0  # via -r requirements.in
future==0.18.2            # via django-ses
gunicorn==20.0.4          # via -r requirements.in
idna==2.9                 # via requests
incuna-mail==4.0.0        # via -r requirements.in
mysqlclient==1.4.6        # via -r requirements.in
prometheus-client==0.7.1  # via django-prometheus
pycparser==2.20           # via cffi
pytz==2019.3              # via django, django-ses
requests==2.23.0          # via -r requirements.in
sentry-sdk==0.14.3        # via -r requirements.in
six==1.14.0               # via -r requirements.in, argon2-cffi, structlog
sqlparse==0.3.1           # via django
structlog==20.1.0         # via django-structlog
urllib3==1.25.9           # via requests, sentry-sdk
whitenoise[brotli]==5.0.1  # via -r requirements.in
zxcvbn==4.4.28            # via django-zxcvbn-password

# The following packages are considered to be unsafe in a requirements file:
# setuptools

What could cause this?

A: This was caused by a blank password supplied in config resulting in an un-usable password being set. User.objects.create_superuser sets an unusable password when an empty string is supplied. The docs say:

If no password is provided, set_unusable_password() will be called.

https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user
However an empty string seems to be treated as "no password" (which was unexpected, although not so surprising given Python's falsy treatment of empty strings). There was a bug in the configuration of the service which caused an empty password to be passed to it.
The reason for the unexpected different format is that an un-usable password appears not to use the same hash function structure.


text:
Q: JFileChooser pop up 2 times This is my JSP file.
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            //JFileChooser filechoose = new JFileChooser();
            JFileChooser filechoose = new JFileChooser("D:\\");
            filechoose.showOpenDialog(null);
            File file = filechoose.getSelectedFile();
            XLCauHoi.ImportXmlFileToData(file);
        %>
        <h4> Đã xuất file thành công </h4>
    </body>
</html>

My problem is that: the JFileChooser pops up 2 times when I run it on browser. If I run it in a Java class, JFileChooser pops up 1 time.
What is my problem and how to solve it?

A: There's a major misconception here. First thing, JSP/Java runs at the webserver, produces a bunch of HTML/CSS/JS and sends it to webbrowser. Webbrowser retireves HTML/CSS/JS and interprets/applies/executes it. It doesn't run any line of Java code because it has already been executed on the webserver. Rightclick page in webbrowser and choose View Source. Do you see it? If webserver has done its job right, you should not see any line of Java code in there. The webbrowser namely doesn't understand it. It only understands HTML/CSS/JS.
Using a JFileChooser in a JSP scriptlet would technically only "work" when both the webserver and webbrowser runs at physically the same machine. It's basically the webserver which displays the dialog, not the webbrowser. This would only "work" when you're locally developing, but never when you publish the website into world wide web by a standalone webserver.
To upload files by HTML, you need an <input type="file"> element, not a JFileChooser. For more detail how to use it with JSP/Servlet, check this answer.
As to the concrete problem, I have no idea why it pops 2 times, but that should be your least concern in this particular case.


text:
Q: List passed as an input to a recursive function acts like a global in that function rather than a local def miniMax(liste, depth,isMaximizing, jogadas):
    scores = {'X': 1, 'O': -1, 'empate': 0}

    result = checkWinner(liste.copy(), jogadas)
    if result is not (None):
        return (scores[result])

    if isMaximizing:
        bestScore = -80000000
        for i in range(0, 3):
            for j in range(0, 3):
                if liste[i][j] == "Nada":
                    liste[i][j] = "X"
                    score = miniMax(liste.copy(), depth + 1, False, jogadas)
                    liste[i][j] = "O"
                    if score > bestScore:
                        bestScore = score
        return bestScore
    else:
        bestScore = 80000000
        for i in range(0, 3):
            for j in range(0, 3):
                if liste[i][j] == "Nada":
                    liste[i][j] = "O"
                    score = miniMax(liste.copy(), depth + 1, True, jogadas)
                    liste[i][j] = "X"
                    if score < bestScore:
                        bestScore = score
        return bestScore
score = miniMax(lista.copy(), depth, True, jogadas)
print(lista)

The lista is changed after running the function minimax.
I have tried to use the .copy() method but the list is still changed in the function

A: As I understand, you are using a 2d list, so using a copy won't be sufficent because it will copy outer lists only. A better solution is using copy.deepcopy:
from copy import deepcopy

score = miniMax(deepcopy(lista), depth, True, jogadas)


text:
Q: Calculate third column based on two other columns on creation of table So I want to create a table for library as follows:
Item
ID Name StartDate ReturnDate Fee
-- ---- --------- ---------- ---
5  Book 5-5-2016   7-5-2016   2
-- ---- --------- ---------- ---

So the above means there's a Book with ID 5 borrowed from 5th May to 7th May.
The fee column should automatically calculate and insert every time a new row is added, with $1 fee for each day between the dates.
How do you do this?
As in, how do you make SQL do this calculation on creation of tuple when the rest of data is inserted (Fee should be updated automatically)?

A: Assuming that you date column have date type
In Mysql  you can use date_diff
SELECT ID, Name, StartDate, ReturnDate, DATEDIFF(ReturnDate,StartDate) AS Fee
from your_table

for oracle simply subtract the date
SELECT ID, Name, StartDate, ReturnDate,
ReturnDate - StartDate  Fee
from your_table

A: You'd better to create the table first and then update the fee column
the DDL should be
create table library (id bigint not null, name varchar(100),startDate date, returnDate date, fee int);

The update sql is
update library set fee=DATEDIFF(ReturnDate,StartDate);


text:
Q: Using ModelForm and passing arguments class MyUserAdminForm(forms.ModelForm):
class Meta:
    model = Users

group = forms.ModelMultipleChoiceField(
    queryset=Groups.objects.filter(domain__user=3),
    widget=forms.CheckboxSelectMultiple,
)

class UserAdmin(admin.ModelAdmin):

list_display = ('login', 'company', 'userType')
form = MyUserAdminForm
filter_horizontal = ('group',)

admin.site.register(Users, UserAdmin)

I am using MyUserAdminForm for customizing the admin interface. I have to pass the pk of the User table as the argument to the filter
queryset=Groups.objects.filter(domain__user=3)

I should pass the pk of the User table instead of the hard coded '3'.
Wanted to know how this can be achieved?

A: The object being edited is given to the form's constructor in the instance argument. You should be able to use that to filter the group choices:
class MyUserAdminForm(forms.ModelForm):
    class Meta:
        model = Users

    group = forms.ModelMultipleChoiceField(
            queryset=Groups.objects.all(),
            widget=forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
        super(MyUserAdminForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('instance'):
            qs = Group.objects.filter(domain__user=kwargs['instance'].pk)
            self.fields['group'].queryset = qs


text:
Q: Splitting one table based on criteria and comparing I'm not quite sure on the best way to phrase this particular query, so I hope the title is adequate, however, I will attempt to describe what it is I need to be able to understand how to do.  Just to clarify, this is for oracle sql.
We have a table called assessments.  There are different kinds of assessments within this table, however, some assessments should follow others in a logical order and within set time frames.  The problems come in when a client has multiple assessments of the same type, as we have to use a fairly inefficient array formula in excel to identify which 'full' assessment corresponds with the 'initial' assessment.
I have an earlier query that was resolved on this site (Returning relevant date from multiple tables including additional table info) which I believe includes a lot of the logic for what is required (particularly in identifying a corresponding event which has occurred within a specified timeframe). However, whilst that query pulls data from 3 seperate tables (assessments, events, responsiblities), I now need to create a query that generates a similar outcome but pulling from 1 main table and a 2nd table to return worker information. I thought the most logical way would be be to create a query that looks at the assessment table with one type of assessment, and then joins to the assessment table again (possibly a temporary table?) with assessment type that would follow the initial one.
For example:
Table 1 (Assessments):
Client    ID    Assessment Type   Start       End
P1        1     Initial           01/01/2012  05/01/2012

Table 2 (Assessments temp?):
Client ID    Assessment Type   Start       End
P1     2     Full              12/01/2012

Table 3:
ID     Worker     Team
1      Bob        Team1
2      Lyn        Team2

Result:
Client  ID    Initial Start    Initial End    Initial Worker   Full Start   Full End
P1      1     01/01/2012       05/01/2012     Bob              12/01/2012

So table 1 and table 2 draw from the same table, except it's bringing back different assessments.  Ideally, there'd be a check to make sure that the 'full' assessment started within X days of the end of the 'initial' assessment (similar to the 'likely' check in the previous query mentioned earlier).  If this can be achieved, it's probably worth mentioning that I'd also be interested in expanding this to look at multiple assessment types, as roughly in the cycle a client could be expected to have between 4 or 5 different types of assessment.  Any pointers would be appreciated, I've already had a great deal of help from this community which is very valuable.
Edit:
Edited to include solution following MBs advice.
Select
*
From(
Select
I.ASM_SUBJECT_ID as PNo,
I.ASM_ID As IAID,
I.ASM_QSA_ID as IAType,
I.ASM_START_DATE as IAStart,
I.ASM_END_DATE as IAEnd,
nvl(olm_bo.get_ref_desc(I.ASM_OUTCOME,'ASM_OUTCOME'),'') as IAOutcome,
C.ASM_ID as CAID,
C.ASM_QSA_ID as CAType,
C.ASM_START_DATE as CAStart,
C.ASM_END_DATE as CAEnd,
nvl(olm_bo.get_ref_desc(C.ASM_OUTCOME,'ASM_OUTCOME'),'') as CAOutcome,
ROUND(C.ASM_START_DATE -I.ASM_START_DATE,0) as "Likely",
row_number() over(PARTITION BY  I.ASM_ID
ORDER BY
abs(I.ASM_START_DATE -  C.ASM_START_DATE))as "Row Number"
FROM
O_ASSESSMENTS I
left join O_ASSESSMENTS C
on I.ASM_SUBJECT_ID = C.ASM_SUBJECT_ID
and C.ASM_QSA_ID  IN ('AA523','AA1326') and
ROUND(C.ASM_START_DATE - I.ASM_START_DATE,0) >= -2
AND
ROUND(C.ASM_START_DATE -  I.ASM_START_DATE,0) <= 25
and C.ASM_OUTCOME <>'ABANDON'
Where I.ASM_QSA_ID  IN ('AA501','AA1323')
AND I.ASM_OUTCOME <> 'ABANDON'
AND
I.ASM_END_DATE >= '01-04-2011') WHERE "Row Number" = 1

A: You can access the same table multiple times in a given query in SQL, simply by using table aliases. So one way of doing this would be:
select i.client,
       i.id     initial_id,
       i.start  initial_start,
       i.end    initial_end,
       w.worker initial_worker,
       f.id     full_id,
       f.start  full_start,
       f.end    full_end
from assessments i
join workers w on i.id = w.id
left join assessments f
       on i.client = f.client and
          f.assessment_type = 'Full' and
          f.start between i.end and i.end + X
/* replace X with appropriate number of days */
where i.assessment_type = 'Initial'

Note: column names such as end (that are reserved words in Oracle SQL) should normally be double-quoted, but from the previous question it looks as though these are simplified versions of the actual column names.

A: From your post, I assume that you're using Oracle here (as I see "Oracle" in the question).
In terms of "temp" tables, Views come right to mind.  An Oracle View can give you different looks of a table which is what it sounds like you're looking for with different kinds of assessments.
Don Burleson is a good source for anything Oracle related and he gives some tips on Oracle Views at http://www.dba-oracle.com/concepts/views.htm


text:
Q: Understanding PyDict_Check behaviour I've been playing around with the Python C API for a while. I like it a lot but today I hit a roadblock. I have a Python extension that has a function which expects one or two dictionaries as argument. I fear I might have misunderstood how PyDict_Check, or PyArg_ParseTuple works. Here's a dumbed down example:
static PyObject * doStuffToOtherStuff(MyCustomPyObject *self, PyObject *args) {
  char const *fmt = "OO";
  PyObject dict1, dict2;

  if (!PyArg_ParseTuple(args, fmt, &dict1, &dict2))
    return NULL;

  int hasDict1 = PyDict_Check(&dict1);
  int hasDict2 = PyDict_Check(&dict2);

  printf("%d %d\n");

  Py_INCREF(Py_None);
  return Py_None;
}

When built and imported I call it like this for example:
myClass.doStuffToOtherStuff(dict(), None)

I expect this to print  1 0  but it actually prints  1 1 . So does:
    myClass.doStuffToOtherStuff(None, None)
    myClass.doStuffToOtherStuff(None, dict())
    myClass.doStuffToOtherStuff({}, None)
    #etc...
If I change PyDict_Check to PyDict_CheckExact it prints 0 0 instead, no matter what I pass as arguments.
Any insight will be much appreciated.

A: PyArg_ParseTuple with O arguments expects a pointer to a PyObject *, not a pointer to a PyObject (i.e. the variadic argument should be of type PyObject **).
So your code should be:
  char const *fmt = "OO";
  PyObject *dict1, *dict2;

  if (!PyArg_ParseTuple(args, fmt, &dict1, &dict2))
    return NULL;

  int hasDict1 = PyDict_Check(dict1);
  int hasDict2 = PyDict_Check(dict2);

  // ...


text:
Q: Getting 404 error in IIS when calling asp page I have a problem with my asp.net 4.0 application. When I call it on the server, it works, but when I call it from outside the server, it gives me a 404 error.
The link I call the asp.net application from is the good one. Other asp.net 4.0 applications are working fine when called from outside the server. The other applications are in another folder though, but I do not see why it would work under a folder and not another one. There is no IP restrictions on the applications.
Anyone got that error int eh past?
Thanks
EDIT:
The app is configured as an asp.net 4.0 application. it is stored in a virtual directory.
This link works:
http://localhost/Phonebook/PhoneBook/default-defaut.aspx
this link does not : https://www.test.com/Phonebook/PhoneBook/default-defaut.aspx

A: A coworker and me found the answer. It's because the server I called on my url was supposed to have a rule redirecting the browser to the right url. So IIS7 on my test server was setted up right.

A: Theres several things to check.

*

*That test.com is even going to your server. Put a file in the root directory 'test.txt' that IIS lists as the root folder for your site. ensure you can get to it.

*Once you verify your root site folder WORKS for ex., www.test.com/test.txt then ensure you have a virtual directory /phonebook that contains a folder phonebook within it.

Seems overkill to be having to folders named phonebook. Try taking one of them out and pointing your web application to your
c:\whatever\phonebook\phonebook folder.

A: Make sure port 443 is bound to your app if you're using https, that could be your problem.


text:
Q: Mobile development - different browser height I'm developing simple mobile app using jquery mobile.
I'm experiencing strage behavor - the HTML renders differently every refresh/post.
I've detected the following symptom that may be the cause:
alert($(window).height())
gives me differnet values when I'm browsing through the address bar and through refresh button. It also gives different values if I'm reaccessing the pages through the same approch(like trying 10 times accessing the same page through address bar)
any ideas?
Thanks


text:
Q: Center views using *only* visual format? I'm trying to center 2 views with different height vertically.
UILabel *view1 = [[UILabel alloc] init];
view1.backgroundColor = [UIColor redColor];
view1.text = @"view1\nline2";
view1.textAlignment = NSTextAlignmentCenter;
view1.numberOfLines = 0;
UILabel *view2 = [[UILabel alloc] init];
view2.backgroundColor = [UIColor greenColor];
view2.text = @"view2\nline2";
view2.textAlignment = NSTextAlignmentCenter;
view2.numberOfLines = 0;
[self.view addSubview:view1];
[self.view addSubview:view2];

NSDictionary *views = @{@"view1": view1, @"view2" : view2};

[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];

for (UIView *view in views.allValues) {
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
}

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[view1]-[view2(==view1)]-|"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view1(200)]-(>=20)-|"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view2(100)]-(>=20)-|"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil views:views]];

This manages to make the centers of both aligned vertically, but they are at the bottom of the superview!

I want to center vertically not only relative to each other, also in the superview.
I added a constraint like this and it works:
[self.view addConstraint:
 [NSLayoutConstraint constraintWithItem:view1
                              attribute:NSLayoutAttributeCenterY
                              relatedBy:NSLayoutRelationEqual
                                 toItem:self.view
                              attribute:NSLayoutAttributeCenterY
                             multiplier:1
                               constant:0]];

But I want to know, is this possible to achieve using only with visual format?

A: Yes, it's possible, but only by adding spacer views. So if you create a couple of views, lets call them spacer1 and spacer2, you can center view1 with this string,
@"V:|[spacer1][view1][spacer2(==spacer1)]|"

This assumes that view1 has a fixed height. I wouldn't recommend doing it this way though, I would just use the code you show at the bottom of your post.

A: What about calculating the Y in "metrics" ?
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-centerY-[view1(200)]-(>=20)-|"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:@{@"centerY": @(CGRectGetHeight(self.view.frame)/2.0 - 100)}
                                                                    views:views]];


text:
Q: PHP mysqli unable to pass id to new php page Displaying of records with bookid, title, author with hyperlink ref on Title. I need to pass Book id as a parameter to new page
Part of the program
    if (mysqli_num_rows($result) > 0)
    {
        echo "
";
        echo 'ID	'.'Title	'.'Author	'.'Price	';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
        {
            echo '
';
            echo "{$row['BookID']} 	 "
             . "" . $row['Title'] . "	"
             . "{$row['Author']} 	"
             . "{$row['Price']} 	";
            echo '
';
        }

I have given hypelink for title and passing Book id
The hyperlink is working fine. On the new page I think it is not passing the value.
On the second page: This is the program getting called from the first program.
after id%20 I don't see the actual value? Is it ok?
http://localhost/Pgpproject319thaug/PhpProject1/displayIndividual.php?id%20=
Also, I am getting an error on line 8 on trying to get the variable name. I cannot see where the mistake is.
Why am I not able to assign the variable using _GET?
Line 8  is

Notice: Undefined variable: _Get in C:\xampp\htdocs\Pgpproject319thaug\PhpProject1\displayIndividual.php on line 8

The actual program is only one line to see whether we can pass the value
$BookID = $_Get['BookID'];
echo $BookID;

A: Two things that stand out:
First, when you're echo-ing the actual line that prints the hyperlink, you're appending the ID directly after the filename: "". So instead of generating links with the IDs assigned to a named GET parameter, you just get something like displayIndividual.php?123 when what you want is displayIndividual.php?id=123 (you see how there's an id= in between the link and the actual ID?).
Next, in displayIndividual.php, based on the error message, you're using $_Get instead of $_GET.


text:
Q: Remove an element create by tinymce plugin I have created a plugin in tinymce that adds an image in front of a text to alert the readers.
(Exemple)
Insert this div, and modify the content inside works fine, but if my users want to delete that div (all the red border), it's harder.
I want my user to click on the "danger sign" and press DEL to remove the element. (actually not possible)
How am I suppose to add this in my plugin  ?
here is my plugin :
tinymce.PluginManager.add('picto', function (editor, url) {
    editor.contentCSS.push(url + '/css/picto.css');

    if (tinymce.majorVersion == 5) {

        editor.ui.registry.addIcon('addwarning', '');
    }

    function addWarning() {
        var selection = editor.selection;
        var node = selection.getNode();
        if (node) {
            editor.undoManager.transact(function () {
                var content = selection.getContent();
                if (!content) {
                    content = 'Contenu';
                }

                selection.setContent('

' + content + '

');
            });
        }
    }

here is my js call to editor :

and my css to create this element :
.alert-modop {
  background: url("../Sources/Images/attention.svg") no-repeat;
}

Thanks for help. o/

A: For those who would have the same difficulty as me, I have an interesting solution.
I've surrounded my content with a div with content editable to true.
This will have no impact on your plugin, but my content can now be selected.
selection.setContent('

' + content + '

');


text:
Q: Decorating a multi-client webapp I have a web-app in Java, Spring, Struts 2 and Hibernate, that servers multiple clients. Each client with multiple users. To create a personal feel for each client, i would like to customize the header for each client.
I'm using sitemesh as decorator, and am looking for tips or examples or someone who can point me in the right direction as to how to acomplish this in the best practice.
What would you think? Should i just code it direct in the header.jsp? Extracting the info about the logged in user and from that create a custom header by code? Or is there a more clever solution out there?
Thanks!
Update:
To further clearify what i want:
Different properties-files for each client is not an option. We are looking at potentionally hundreds of clients. It needs to be database-driven. But thats the easy part. There is no problem storing the information in db and extracting it when needed.
What im trying to figure out is if there is some sort of standard way of doing this. Some sort of filter or Action that is run before the sitemesh decorator that will provide the decorator with the correct info?

A: Struts2 provides application scope, for variables which are global to the application.
Load all the customer specific strings into #application scope (I would use spring to do this when the application starts up). From there referencing the strings would be pretty obvious: #application.greeting I don't like the idea of using an interceptor because there is nothing to intercept. I would say for what you are doing application scope is the perfect place.  If it is a single client system I can see no reason why anything would be stored in application scope.
Aside: Tiles uses a different template paradigm than site mesh, and they have slightly different purposes.  As such the two can be complimentary.  Tiles relying on XML definitions can have it's definitions stored in a DB and is definitely less computationally intensive, however where there is interplay between different UI components... or disparate elements appearing on the page you need to use sitemesh.  So for basic template needs tiles does everything and is quite easy to understand but say you wanted to make add a certain widget in the middle of the page which relies on JS which needs to be added to the header it would be tricky to do this in Tiles (although the obvious solution is to just roll the JS functionality into one JS file for all possible uses in a particular part of the site).
Asside 2: By using a view technology such as velocity or freemarker in conjunction with tiles it is conceivable to move the entire view layer into a database.  I just thought I would mention that as for some maintenance issues that could be extremely beneficial.

A: Sitemesh makes it's decisions about what decoration to use based upon the requested URL string, so unless you have a reference to the client in every url - either as part of the main url string or as a known parameter, then Sitemesh out of the box is not going to help.
This leaves a few possibilities to achieve what you want;
1) Write a filter that runs before Sitemesh that adds, for example, "&clientId="xx" to every incoming request.
2) Dive into the source code for Sitemesh & look for where Sitemesh finally makes it's decision about which decorators to use and override it. I've never tried this so I don't know how practical this might be.
3) Make the style sheet definition in your jsp pages an OGNL expression and provide that information in a base action class that all your actions extend. In this way you end up with (potentially) a different CSS file for each client and you provide your customisation via CSS.
Hope that this helps.


text:
Q: Storing commonly used data in memory I am connecting to an api server. After logging in I receive an access and a refresh token. Also user's name, surname, permission list etc. I always use these properties to display / allow something for the user to do. Also with all the requests I should send access token. I am managing logging in process with BLOC pattern but I don't know where to store all my commonly used data. (like this user data) Maybe in a singleton class? So I can get the data from that class before sending a request.
Do you have any recommendation for it? Because I have no idea.

A: After the some discussion in the comments, I'm adding the answer also.
The BLoC classes not for just handling the logic, also keeping the data for memory.
Inside StatefulWidget and StatelessWidget, yes you can acces the bloc provider with context but for access between bloc, you can simply use singleton. So how to create singleton?
There two basic approaches:
class Bloc{
....//some logic and variable
}

final bloc = Bloc(); //Singleton object for bloc, it's static because
// it's outside of the Class and it can be directlry accessible for
// any file that imports this file

or
class Bloc{
....//some logic and variable

Bloc._internal(); // private constructor

static final bloc = Bloc._internal(); // static object which will sent
// through public factory

factory Bloc() => bloc; // when you use this constructor through your
// application, you'll always get same instance

}

So, using a bloc inside yet another bloc would be like this:
class BlocA{ //this is for second method

final blocB = BlocB();

blocB.method();...

}

For the first method up above use the object, that's all.

A: You can create a singleton class and keep your commonly used data there or create a Bloc class and initialize it in the beginning of your app, it will be like a singleton.
If you already using Blocpattern you can do like this:
void main() {
  runApp(BlocProvider<UserBloc>(
    builder: (_, bloc) => bloc ?? UserBloc(),
    onDispose: (_, bloc) => bloc.dispose(),
    child: MyApp(),
  ));
}

I don't know how your Bloc pattern is implemented, but if you doesn't familiar with this BlocProvider implementation, I can give you a BlocProvider class that I'm using for my apps.
import 'package:flutter/material.dart';

abstract class BlocBase {
  void dispose();
}

class Provider<B> extends InheritedWidget {
  final B bloc;

  const Provider({
    Key key,
    this.bloc,
    Widget child,
  }): super(key: key, child: child);

  static B of<B>(BuildContext context){
    final type = _typeOf<Provider<B>>();
    Provider<B> provider = context.inheritFromWidgetOfExactType(type);
    return provider.bloc;
  }

  static Type _typeOf<B>() => B;

  @override
  bool updateShouldNotify(Provider<B> oldWidget) => oldWidget.bloc != bloc;
}

class BlocProvider<B> extends StatefulWidget{
  final void Function(BuildContext context, B bloc) onDispose;
  final B Function(BuildContext context, B bloc) builder;
  final Widget child;

  BlocProvider({
    Key key,
    @required this.child,
    @required this.builder,
    @required this.onDispose,
  }) : super(key:key);

  @override
  _BlocProviderState<B> createState() => _BlocProviderState<B>();
}

class _BlocProviderState<B> extends State<BlocProvider<B>>{
  B bloc;

  @override
  void initState(){
    if(widget.builder != null){
      bloc = widget.builder(context, bloc);
    }
    super.initState();
  }

  @override
  void dispose(){
    if(widget.onDispose != null){
      widget.onDispose(context, bloc);
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context){
    return Provider(
      bloc: bloc,
      child: widget.child,
    );
  }
}

After initialization you will get your main Bloc class through injections.
Like this:
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final userBloc = Provider.of<UserBloc>(context);
    return MaterialApp(
      home: HomePage(userBloc: userBloc)
  }
}

So, HomePage(userBloc: userBloc) this is how you will inject your Bloc class through your widgets tree.
Another way to keep the data like login information, is to use shared_preferences package. It is a store for simple data, which you can have a quick access. It will save your data in the device.
Hope this will help.


text:
Q: NSXML didStartElement method not being called Iv'e set my h as the delegate and I'm calling the "setDelegate:self" method on my xml parser.
here is my code.
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    elementName = element;
    if ([elementName isEqualToString:@"offer"]) {
        offersDictionary = [[NSMutableDictionary alloc] init];
        offerTitle = [[NSMutableString alloc] init];
        offerDay = [[NSMutableString alloc] init];
        offerDet = [[NSMutableString alloc] init];
        NSLog(@"PARSER didStartElement method!");
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if ([element isEqualToString:@"offerTitle"]) {
        [offerTitle appendString:string];
    }
    if ([element isEqualToString:@"day"]) {
        [offerDay appendString:string];
    }
    if ([element isEqualToString:@"offerDetail"]) {
        [offerDet appendString:string];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:@"offer"]) {
        [offersDictionary setObject:offerTitle forKey:@"offerTitle"]; NSLog(@"offerTitle:%@",offerTitle);
        [offersDictionary setObject:offerDet forKey:@"offerDetail"]; NSLog(@"offerDet:%@",offerDet);
        [offersDictionary setObject:offerDay forKey:@"day"]; NSLog(@"OfferDay:%@",offerDay);
        NSLog(@"DidEndELEMENT");

        //[offersArray addObject:[offersDictionary copy]];
    }

}

I've set "NSlog" in my didStartElement and in my didEndElement methods, but I only get output from the didEndElement.
I'm calling the "parse" method of the NSXML from the viewDidLoad method.
here is my viewDidLoad method.
- (void)viewDidLoad
{
    [super viewDidLoad];
    //alloc and init the array
    offersArray = [[NSMutableArray alloc] init];
    //create NSUrl with the xml file
    NSURL *xmlUrl = [NSURL URLWithString:@"http://mydomain.org/dir/dir/file.xml"];
    //alloc and init the xml parser with the data of the file
    xmlParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlUrl];
    //set some methods on the xml parser
    [xmlParser setDelegate:self];
    [xmlParser setShouldProcessNamespaces:NO];
    [xmlParser setShouldReportNamespacePrefixes:NO];
    [xmlParser setShouldResolveExternalEntities:NO];
    //create a 'success gate' of the 'parse' method
    BOOL xmlParseSuccess = [xmlParser parse];
    if (xmlParseSuccess) {
        NSLog(@"Successed Parsing! array Has %lu elements.", (unsigned long)offersArray.count);
    } else if (!xmlParseSuccess) {
        NSLog(@"Error Parsing!");
    }

    // Do any additional setup after loading the view.
}

Why is the didStartElement method not being called?

A: Here is your issue:
-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
   attributes:(NSDictionary *)attributeDict {

    /*
     Your setting elementName to element. So whatever the
     value of 'element' is, it will compare to @"offer".
     It seems that the value of 'element' is not equal
     to @"offer". You should not be Comment this line out
     and it should work fine.
     */

    elementName = element;

    if ([elementName isEqualToString:@"offer"]) {
        offersDictionary = [[NSMutableDictionary alloc] init];
        offerTitle = [[NSMutableString alloc] init];
        offerDay = [[NSMutableString alloc] init];
        offerDet = [[NSMutableString alloc] init];
        NSLog(@"PARSER didStartElement method!");
    }
}


text:
Q: XSLT 2.0 - iterate over a list of Java objects I have an XSL that is meant to create a copy of an XML but with a few attributes added to certain elements in the XML. The XSL calls a Java function that returns a list (java.util.List) of objects of type CInfo which is currently a very simple class defined as follows:
public class CInfo {
    public int getNewVal() {
        return 12345;
    }
}

I am now facing a problem with the following snippet in the XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:list="java.util.List"
    xmlns:saxon="http://saxon.sf.net/"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    ...
    ...>

...
<xsl:variable name="infoList"
    select="up:computeUpdates($updator)"/>

<xsl:for-each select="$infoList">
    <xsl:variable name="cinfo" select="."/>
    <xsl:variable name="newVal" select="ci:getNewVal($cinfo)"/>
...
...
</xsl:for-each>

computeUpdates(), which I verified is indeed being called by XSL, returns a list containing just one instance of type CInfo. The problem occurs at xsl:for-each which gives the following error:
Error on line 89
  XPTY0019: Required item type of first operand of '/' is node(); supplied value has item
  type java:com.mproj.mpkg.CInfo
  at xsl:for-each (#76)
     processing "com.mproj.mpkg.."
  at xsl:apply-templates (#48)

Somehow the XSL doesn't seem to be able to iterate over infoList. Strangely, an existing XSL in the codebase that I am working on has a very similar for-each and is able to iterate over a list of Java objects of another class (similar to CInfo though) and doesn't seem to give any problem. Am I missing something? What is the standard procedure to make an XSLT iterate over a list of Java objects? Any examples that can help me here? I tried searching the web for examples of such looping and possible solutions to the mentioned problem but have been unsuccessful so far.

A: You haven't shown us line 89, where the error arises. My guess is that it probably contains an expression of the form
$infoList/XXXXX
which is failing because (as the error message explains) the lh operand of "/" must be a sequence of nodes.


text:
Q: Extracting data from net ldap response containing image In my application I sync users image uploaded as photo field in the LDAP, I am using NET::LDAP for the same.
the object returned for the image field is of type Net::BER::BerIdentifiedArray, I can convert it to Net::BER.
My question is how do I extract the type of image(jpeg/gif/bmp etc) while creating a image file from the binary response given by the LDAP.

A: You'll need something to decode the binary data into an image.  RMagick is a Ruby wrapper for ImageMagick that should do the trick.  Specifically, Image.from_blob will read image data from a string in memory.
From there, this answer shows image.format will tell you the format.


text:
Q: The best way to do permission set in Django (group, roles, permissions) Thanks for reading my question.
Before to ask, i was reading about my doubt:
http://djangobook.com/customizing-authentication-django/
django roles authorization architecture
Django Permissions for Different Clients
... And i'm not clear about permissions set in Django :(
I learning Django, but i want to try to build a permission set on my app. My system is about a schoool: teachers, students, management people, class room leaders.
The system's premise is: an user only must to have a rol.
Some questions about it:

*

*I thinking to prepopulate role table, with general profiles: student, teacher, management... What is the better way to do it?

*The typical restriction: a teacher is the unique profile can add, delete, view, edit your student's scores. What is the better way to do it? Should I do it through a custom system? Have u some url, code or source where can i to check it?
Excuse me my english. Thanks!

A: I had a similar problem and ended up designing my own permission system, because with the default django permission system, it is not possible to do per-object permissions.
I simply added a model LabAccess with a foreign key on django.contrib.auth.models.Group (because I often have multiple instructors by course) and another foreign key for the course. (This allows multiple groups be instructor in a course). Then, in each view for instructors, I check whether one of the groups the user belongs to has an item in the LabAccess table. The source code of this system is actually available, if you are interested.
Note that there are also django extensions that support per-object permissions, like (django-guardian) http://django-guardian.readthedocs.io/en/stable. (I have no experience with it,)


text:
Q: for loop in php iteration $j=0;
for ($i=0; $i<31 ; $i++) {
    $t_bills = 0;
    # code...
    if($i<9){
        $j='0'.($i+1);
    }else{
        $j=($i+1);
    }
    $finaldate= $current_year.'-'.$current_month.'-'.$j;
    echo "............";
    echo "
";
    echo "finsal date is";
    echo("
");
    echo $finaldate;
    echo "
";
    //print_r($row);
    $tt_bills=0;
    //echo mysqli_num_rows($run);
    $strQuery ="SELECT bills,r_date FROM  daily_machine_record where (`r_date` = '$finaldate' )";
    $run= mysqli_query($dbhandle,$strQuery);
    while($row = mysqli_fetch_array($run))
    {
        if($finaldate==$row['r_date']){
            for ($x=0; $x <mysqli_num_rows($run) ;$x++ ) {

                echo "............";
                echo "
";
                echo $finaldate;
                echo "
";
                echo "bill is";
                echo "
";
                echo $row['bills'];
                echo "
";
                echo "............";
                echo "
";
                echo $tt_bills +=  $row['bills'];
                echo "
";
                echo "............";
                echo("
");
    //var_dump($tt_bill);
            }
        }
        else{

            echo $tt_bills =$tt_bills+ 0;
        }
    }

i want to get the value of bills at each date of current month which is stored in my database. im having a problem .i.e when the loop executes it generates the bills amount but where the date is same it returns the value incrementing it 2 times like if the value is 100 on 2017:11:06 and on same date i have another value 100 the total amount of bills which i get will be 400 instead of 200.

A: You need to change your else condition. Re-assign only 0 to variable
else{

 echo $tt_bills =  0;
}

EDIT
Also remove un-necessary for loop other wise your result will be repeated


text:
Q: Can I break anything if I set log.segment.delete.delay.ms to 0 I'm trying to put an absolute limit to the size of a topic so it won't fill up disks in case of unexpectedly high write speeds.
Mostly, this amounts to some calculation like segment=min(1GB, 0.1 * $max_space / $partitions) and setting retention.bytes=($max_space / $partitions - $segment),segment.bytes=$segment and reducing log.retention.check.interval.ms. (You can even pull stunts like determining your maximum write rate (disk or network bound) and then subtract a safety margin based on that and log.retention.check.interval.ms, and maybe some absolute offset of the 10MB head index file.) That's all been discussed in other questions, I'm not asking about any of that.
I'm wondering what log.segment.delete.delay.ms is for, and if I can safely set it to 0 (or some very small value - 5?). The documentation just states "The amount of time to wait before deleting a file from the filesystem". I'd like to know why you would do that, i.e. what or who benefits from this amount of time being non-0.

A: This configuration can be used to ensure that a Consumer of your topic has actually the time to consume the message before it gets deleted.
This configuration declares the delay that is applied when the LogCleaner is  triggered by the time-based or size-based cleanup policies set through log.retention.bytes or log.retention.ms.
Especially when your have calculated the retention based on the size of data, this configuration can help you set a minimal time before a message gets deleted and to allow the consumer to actually consume the message during that time.


text:
Q: Can I populate a Sonata entity export using only getters? I am building a very simple billing system for a media company using Sonata that includes Payment entities for paying Reporters. The only purpose of a Payment is to be exported to a spreadsheet. We will never edit Payments directly.
I have a bunch of special getters in my Payment entity that don't correspond directly to properties of that entity. Stuff like this:
public function getReporterName():string
{
    return
        $this->reporter->getUser()->getFirstname() .
        ' ' .
        $this->reporter->getUser()->getLastname()
        ;
}

In my Sonata admin class for this entity, I have told my list view to show reporterName as if it is a property. Sonata is smart enough to find and use the getter to retrieve the string I'm looking for. No problem.
The issue comes when I add that pseudo field name into the configureDatagridFilters() method like so:
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('id')
        ->add('paymentComplete')
        ->add('reporterName')
    ;
}

Now I get a nasty message when trying to export a spreadsheet, saying this:

No metadata found for property
AppBundle\Entity\Payment::$reporterName. Please make sure your
Doctrine mapping is properly configured.

Is there a way to do what I'm trying to do here? Or will I simply have to suck it up and duplicate some data in the database in order to make my export work?
If it helps, I'll reiterate here that we only need this entity for the purpose of exporting to a spreadsheet. It will never be edited manually.

A: I think you are stuck using two fields (unless you add a mapped field for the full name).
You can use the dot syntax to filter by sub entity properties:
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('id')
        ->add('paymentComplete')
        ->add('reporter.user.firstname', null, ['label' => 'Reporter Firstname'])
        ->add('reporter.user.lastname', null, ['label' => 'Reporter Lastname'])
    ;
}

A: I ended up working with the dedicated export method to solve this.
https://symfony.com/doc/current/bundles/SonataAdminBundle/reference/action_export.html