text:
Q: Scala - Play framework Creation Exception I'm trying to add a new controller to my Play framwork but I'm having this exception
CreationException: Unable to create injector, see the following errors:

1) No implementation for service.GithubService was bound.
  while locating service.GithubService
    for the 2nd parameter of controllers.GithubController.<init>(GithubController.scala:12)
  while locating controllers.GithubController
    for the 3rd parameter of router.Routes.<init>(Routes.scala:28)
  at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:139):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$4)

1 error

Here is the HomeController.scala file
package controllers

import play.api._
import play.api.mvc.{BaseController, ControllerComponents}

trait HomeController extends BaseController {
  protected def controllerComponents: ControllerComponents
}

Here is the GithubController.scala file
package controllers

import javax.inject.Inject
import models.GithubRepositoryDTO
import play.api.libs.json.{JsValue, Json}
import play.api.mvc._
import service._

import scala.concurrent.{ExecutionContext, Future}

class GithubController @Inject()(
                                  val controllerComponents: ControllerComponents,
                                  githubService: GithubService
                                )(implicit ec: ExecutionContext) extends HomeController {
  def getStarred(): Action[JsValue] = Action.async(parse.json) { implicit request =>
      githubService.getStarredRepositories()

      Future(Ok("test"))
  }
}

Here is the GithubService.scala file
package service

import models.GithubRepositoryDTO

import scala.concurrent.Future

trait GithubService {
  def getStarredRepositories():Future[Seq[GithubRepositoryDTO]]
}

Here is the GithubServiceImpl.scala file
package service

import javax.inject.Inject
import models.GithubRepositoryDTO
import play.api.libs.json._
import play.api.libs.ws.WSClient

import scala.concurrent.{ExecutionContext, Future}

class GithubServiceImpl @Inject()(
                                  wsClient:WSClient
)(implicit ec: ExecutionContext) extends GithubService {
  def getStarredRepositories(): Future[Seq[GithubRepositoryDTO]] = {
    //some code
  }
}

I've checked if the error comes from the service or controller but still not working, any help or suggestion is welcome. Thanks!

A: The problem is that GithubServiceImpl has not been registered with the dependency injection container. You can find information on how to do this in the Providing custom bindings section of the documentation.
The two options are:

*

*Using binding annotations:
@ImplementedBy(classOf[GithubServiceImpl])
trait GithubService {
  def getStarredRepositories(): Future[Seq[GithubRepositoryDTO]]
}

*Using programmatic binding, in a file called Module.scala in the root of your application:
import com.google.inject.AbstractModule
import com.google.inject.name.Names

class Module extends AbstractModule {
  override def configure() = {
    bind(classOf[GithubService])
      .to(classOf[GithubServiceImpl])
  }
}

Be sure to read the linked documentation for more details on other options and declaring a binding as a singleton.


text:
Q: Xpath expression for council website From this URL:
https://www.walsall.gov.uk/Waste/bincollections/Details/100071042591
I want to extract the indivual bin dates from the webpage.
When I inpsect with Chrome, and copy xpath for the first bin date, I get the following XPath:
//*[@id="main"]/table[1]/tbody/tr[2]/td[2]

Which looks good, but I get a length of zero from my $xpath->query object.
However, when I put my query as:
//*[@id="main"]/h3[2]

I get the right value (Green Bin, Recycling).
Can anyone tell me why the first XPath query isnt working? It looks perfectly logical to me.

A: The problem was with <tbody> tag, I took that out and ended with this:
//*[@id="main"]/table[1]/tr[2]/td[2]

My guess is when I inspected Chrome inserted the tbody tag when you inspect, but it is not actually present in the raw HTML served by the server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When I try to add a deck of cards to my database i get: Integrity error decks_deck.cardID_id may not be NULL. What am I doing wrong? I made my models like this:
from django.db import models

class Attribute(models.Model):
    idAttr= models.CharField(primary_key=True, max_length=40)
    description= models.CharField(max_length=40)
    def __str__(self):
        return self.description

class CardType(models.Model):
    idCardType= models.CharField(primary_key=True, max_length=40)
    description= models.CharField(max_length=40)
    def __str__(self):
        return self.description

class MonsterType(models.Model):
    idMonsterType= models.CharField(primary_key=True, max_length=40)
    description= models.CharField(max_length=40)
    def __str__(self):
        return self.description

class CardClass(models.Model):
    idCardClass= models.CharField(primary_key=True, max_length=40)
    description= models.CharField(max_length=40)
    def __str__(self):
        return self.description

class Card(models.Model):
    idCard= models.CharField(primary_key=True, max_length=40)
    name= models.CharField(max_length=40)
    description= models.CharField(max_length=100)
    attrID= models.ForeignKey(Attribute)
    cardTypeID= models.ForeignKey(CardType, null=True, blank=True)
    monsterTypeID= models.ForeignKey(MonsterType, null=True, blank=True)
    cardClassID= models.ForeignKey(CardClass)
    def __str__(self):
        return self.name

class Deck(models.Model):
    idDeck= models.CharField(primary_key=True, max_length=40)
    name= models.CharField(max_length=40)
    cardID= models.ManyToManyField(Card)

    def __str__(self):
        return self.name

however when I fill in all the required fields in the database I get an error with the cardID saying it may not be null.
The Card class is used to add cards and the deck should show a list of all added cards throught the cardID field, which it does. I fill in all the other fields and select all the cards I want to add to the deck. But after clicking save i get the error mentioned above.
I've read various posts on this site and even read the djago documentation, but I haven't been able to solve it. I would appreciate all the help I could get.

A: can you use this
id = models.AutoField(primary_key=True)


text:
Q: Is there a way to view previously viewed tutorials? A tutorial was shown when I first started  coming across FOES, which was nice and handy, but I can't seem to find anyway to locate the information again. I know that the colour around the FOE map icon is supposed to tell you how difficult it will be, but I can't remember the colours. I've tried locating the tutorial somewhere in my menu, but I'm not having any luck.
Is there a way to view previously viewed tutorials?


text:
Q: Onion architecture - Should we allow Jackson annotations in our core POJOs? I have an application that receives a JSON message and then deserializes it into a POJO. I've been studying the Onion Architecture for a couple of weeks now and I've stumbled across a tecninal dilema for this situation. Since I'm using the Jackson Deserializer I was forced to use Jackson Annotations in order to assist the deserialization process. This Jackson POJOs are needed by the application core and here comes the problem. Since deserialization is an infrastructure concern it wouldn't be correct to have classes with Jackson annotations in my core, right?
I see 2 options:
1 - My core will have a POJO similar to the Jackson POJO but without its annotations. The Jackson POJOs will be in the infrastructure and then I'll use a mapping framework to map the Jackson POJOs to Domain POJOs.
POJO in the infrastructure layer:
public class MyUser {

    private String firstName;
    private String lastName;

    @JsonProperty("first_name")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @JsonProperty("last_name")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

POJO in the core layer:
public class MyUser {

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

2 - Assume that Jackson is cross-cutting and therefore can be used through the layers.
I believe that option 1 is more suitable considering that I'm following the Onion Architecture. However, sticking to this option will force me to duplicate objects and that does not sound good to me.
Is there really only this two options? Any advice?

A: Your solution one is a well known solution the Data Transfert Object Design Pattern or DTO if you want to learn more about about it.
In my point of view those are not object duplication. They are different representation of the same domain concept, each adapted to the need of a specific application layer. And as every pattern there is times where it's mandatory to use them and some where it's a useless and more damaging than anything.
A story from my own experience : we had a project where we chose to use the same POJOs for every layer to avoid duplication and having to handle mapping. Few weeks later we had minor cross-concerns issues that we "hacked out".
A bit later those issues became more serious (performance, database problems in the API layer...) and the hack to fix them worst. In the end after a lots of headache we agreed that mapping and POJOs duplication made sense.
But the opposite can also happen : you can make strict layering with mapping for a simple CRUD application with very few logics at all. And then a strict layered architecture is a waste of time and effort.
As often the answer is : it depends on what you are trying to build.
The bigger and more complex an application is and will be (scalability is a real matter here), the more strict the architecture have to be. But a simple application (or any simple node of a larger structure) need to stay simple.
Hope it helped!


text:
Q: Convert form results to array with jQuery or other I'm trying to get a form result to an array so it can be handled by the next JSP page.
Currently I have this code:
$("seguimiento").submit(function(){
        var labels = new Array();
        var val = new Array();
        $(":input").each(function(){
           if ($(this).val() >0) {
              labels.push($(this).attr('name'));
              val.push($(this).val());
           }
        });
        console.log("ya hemos rellenado los arrays");
       $.post("enviar.jsp", {"etiquetas": labels.join(','), "valores": val.join(',')});
     });

But it is just not working at all, I don't even get on the console the debugging message.
Of course my form has name="seguimiento"

A: simply serialize() or serializeArray()
$.post("enviar.jsp",$("form").serialize(),function(d){});

To get the console msg
$("form[name='seguimiento']").submit(function(e){
        e.preventDefault();
        var values = $(this).serializeArray();//this contains the array you want
        console.log(values);
        $.post('enviar.jsp',values,function(d){
             //d is the output of enviar.jsp
             console.log(d);
        });
     });

Depending on the data, you can consider using window.location to redirect to enviar.jsp and send the data as url variables.

A: You can not pass arrays of javascript, Instead of sending array pass comma separated strings, you can use join to make comma separated string from array.
Change
$.post("enviar.jsp", {etiquetas: labels, valores: val});

To
$.post("enviar.jsp", {"etiquetas": labels.join(','), "valores": val.join(',')});


text:
Q: Intend to come by I came across a sentence which read as follows:

The money you intend to come by through this expedition is not worth
your life.

From the context, I interpreted "intend to come by" as the intention of earning or gaining.
When I searched online for this usage I find examples like, "Let me know if you intend to come by today" Here, it appears to mean "if you have an intention to drop by/come visit today."
Can someone explain how to understand the phrase "intend to come by" and when and how to use it?

A: There are two distinct meanings of "come by".
One meaning is to make a visit. It is intransitive, which means it doesn't take a direct object. This is the meaning in, "Let me know if you intend to come by today." It means, let me know if you intend to visit today.
The other meaning is to acquire or gain possession. With this meaning, it is transitive, which means it takes a direct object. In this case, the object is "the money". So "the money you intend to come by through this expedition" means "the money that you intend to gain through this expedition".

A: The phrase "come by" is used the same way as "come to". When used literally, as you ask or anticipate someone to come by your home or business, or you intend to go to their home or business, it's used to mean just that: they will go to you, or you will go to them. Most often, it refers to the place that's being gone to, rather than any person that's there, even though the person or people are who you're likely going to see.

Come by the house and see your mother.

In the case of the phrase "come by some money" it's used in the same way as "come into some money"; the money is being received or acquired. It's most commonly used this way in less formal speech or writing. Interestingly, it might also be considered as more more polite or at least less direct; less harsh or brash.


text:
Q: Submit form and close window I can't understand why this isn't working.
I have a form opened in new tab, which I want to close when submitting:
<form name="form" id="form"  method="post" enctype="multipart/form-data" >
    //form inputs
    <button accesskey="C" class="boton" onclick="form.submit(); alert('waiting...'); window.close()"> Adjuntar</button>

 </form>

when I remove window.close() the form is submitted, but when it's in my code, it shows the alert but not submitting.
Is there anything wrong?

A: you don't have to open the form in a new window (or tab).
you can either submit the data in ajax or use an inner hidden iframe as the target property of the form element. this way the form will open in a hidden inner element. e.g.:
<form id="eFrm" target="ifrm1">
</form>

A: The form won't be submitted until the event handler function has finished running.
alert blocks all execution of everything until the dialog is dismissed.
close closes a the window, so there is nowhere to load the form submission into, which cancels the request.

If you are going to close a window, don't expect it to be able to send an HTTP request at the same time.

A: You probably already found a solution, but I am posting this anyway for anybody who comes across the same in the future.
I am using Java servlets, but I think that is the same with every form submission => ability to choose which page must be displayed after the posted data was processed.
Once I have submitted the form, the doPost method in the servlet allows me to say which URL I want the browser to display after the data has been processed.
So, you can do probably do something along these lines:
   request.getRequestDispatcher ( "/ClosePopup.html" ).forward ( request, response );

Then also create a file called ClosePopup.html, with nothing but a close () instruction
<!DOCTYPE html>

        <meta charset="UTF-8">

This way it won't be the button you click to trigger the closure of the popup, but you will be loading a self destroying page after the form is submitted. The final result is identical.


text:
Q: vm instance not setting up default to Bridged mode when using vagrant on Windows I have tried to follow this thread: Vagrant how to set network type so that its attached to bridge adapter on Virtual Box with similar problem but no success.
Also tried this: How to automatically select bridged network interfaces in Vagrant?
and Vagrant docs https://www.vagrantup.com/docs/providers/virtualbox/configuration are Linux specific.
This is my vagrant file.
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "xoan/proxmox-ve_6.4"
  config.vm.box_version = "1.0.0"

  config.vm.network "forwarded_port", guest: 8006, host: 8006

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  config.vm.network "public_network", auto_config: false, Bridged: 'Realtek PCIe GbE Family Controller #5',  ip: "192.168.56.2",
    nic_type: "virtio"

  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    vb.gui = true

    # Customize the amount of memory on the VM:
    vb.memory = 2048
    vb.cpus = "2"
    vb.name = "proxmox1"
  end
end

I am specifying the NAT to bridged mode and giving it the Ethernet card name as VirtualBox sees it. (specifying the name since I have multiple nic interfaces)
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'xoan/proxmox-ve_6.4'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'xoan/proxmox-ve_6.4' version '1.0' is up to date...
==> default: Setting the name of the VM: proxmox1
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 8006 (guest) => 8006 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...

but everytime I run vagrant up I keep getting NAT 1 as default

A: Port forwarded to 127.0.0.1 are to the correct NAT, you should try to ping the ip 192.168.56.2 from your host machine. You you should be able to ssh this ip using the pivate key i.e.
ssh -i private_key 192.168.56.2


text:
Q: Google Cloud Messaging IOS registration using Cordova plugins Google created a new way to register application using single location (Google Cloud Messaging), and we can use it to send messages to Android and IOS, Chrome.
I use Phonegap (Cordova) for making IOS/Andoid application, how can I register the application to use that service, I found an old plugin for push notifications, but it's not using the new interface and registration of GCM.
So, any Idea about new plugin that can support IOS/Android registration to GCM?

A: Check out GCMPushPlugin!
This is also currently being worked on at PhoneGap Plugin Push (a fork of the plugin you linked), issue 115.
I think GCMPushPlugin would be your best bet for now, but considering that PhoneGap Plugin Push has ~40 more contributors, I'd keep my eyes open for updates, and see if it's worth switching over when they implement it.


text:
Q: Unlimited integer precision From Python Numeric Types:

Integers have unlimited precision.

This test

#include <stdio.h>

int main(void) {
    printf("%zu bytes", sizeof(long long));
    return 0;
}

gives me 8 bytes or 64 bits under Linux.
How this is implemented in cpython (this was answered in the comment section)?
What happens when the integer exceeds long long in the implementation?
How big is the speed difference in arithmetics between pre-8-byte and post-8-byte integers?

A:
What if I have a bigger number in Python (not going into 8 bytes)?

Python will adapt and always store the correct number, no approximation. Even with very big INTEGER (but this is not true with other types)

How is it stored in the system, literally? Like a few smaller integers?

That's python implementation. You could find it from the source code here : svn.python.org/projects/python/trunk/Objects/longobject.c (thanks @samgak)

Does it hugely slow down the arithmetics on this number?

Yes like in other languages when the number becomes bigger than .e.g 2^32 on 32 bits systems the arithmetic becomes slower. How much is implementation dependent.

What does Python do, when it encounters such number?

Huge integers are stored in a different way and all arithmetic is adapted to fit.

Is there any difference in Python's 2 & 3 behavior except storing as long in Python 2 and appending L to string representation?

Python 2 and 3 should have the same high level behaviour.


text:
Q: TFS Web Access and large files When viewing a whole shelveset diff in TFS Web Access, the largest source files are accompanied with a yellow bar that says "Displayed content is truncated due to maximum viewable content limit."
When I click on that single large file to see just its diff, I get another yellow bar.  This time it says "The file contents were truncated since they exceeded the maximum file content length. Browse to the individual files to download full content."
Okay, maybe this tool just won't show large files to me.

*

*How do I "browse to the individual files" as the yellow bar suggests?  Will that give me both versions that I need to diff (shelved and unmodified)?

*Is the size limit configurable anywhere?

*Is there any way to use TFS Web Access with a
user configurable diff tool?  (I would have many other good uses for that.)

The only workaround I am aware of is to open Visual Studio, painfully look up the shelveset, and view it using my configured diff tool which doesn't care whether the source files are obese or not.
I'm using TFS version 12.0.30324.0.

A: If you select just a single file you should get a download button. Clicking this will retrieve just that single file in it's entirety.

On non-shelvesets it's next to the edit button, but I dought that edit is available on shelvesets.

A: After asking, I discovered some other ways to search and found out that this limitation is specific to TFS 2012 and unpatched TFS 2013.  Maybe this helps someone.
(This does not solve my own problem as I cannot quickly achieve TFS server upgrade so I'm still interested in a better answer.  I'd like to extend my knowledge of TFS Web Access and I found the online resources lacking.)


text:
Q: Customizing a date field in a model form Let me start out by saying this question is basic, and almost certainly has been answered elsewhere if I only could find exactly what I need.
I have users who will be entering dates in some screwy formats, which won't be recognized by the usual validation code for the DateField (for instance, 2014/4 which I will want to convert to 2014-4-01 internally). Do I need to mess with the code to clean, validate, or both for this, and if I redefine those functions do I need to explicitly call super?
My thought was that maybe I should give the model field and the form field different names, and somehow fill the model field with the form field data when I process the form... but the how of that is vague.
class Person(models.Model):
  (some other fields)
  date_of_arrival = models.DateField(blank=True, null=True)

class ClientForm(forms.ModelForm):
  (some other fields)
  date_of_arrival = forms.DateField(required=False, help_text="Date of arrival in town")
  class Meta:
     model = Person
     fields = (..., date_of_arrival, ...)

A: $date = date('Y-m-d',$urvalue);

A: You need to implement a _clean() method in your form, where the name of the field is before the _, so in your example it would be date_of_arrival_clean().
In this method, do all your validations. I would recommend the dateutil package, which provides parse method that is designed to take a string that could possibly be a date, and convert it to a date. Using this method you will not have to write the mundane logic, instead your entire method would be:
def date_of_arrival_clean(self):
    user_input = self.cleaned_data['date_of_arrival']
    try:
        d = parse(user_input)
    except (ValueError, TypeError):
        raise forms.ValidationError('{} is not a valid date'.format(user_input))
    return user_input

My thought was that maybe I should give the model field and the form
  field different names

You don't have to do this ... you can keep the same fields as in your model form and still implement the _clean() method as described above.
Keep in mind that if your form is a ModelForm, then django will also do database validation when try to validate the form.


text:
Q: Passing a NULL value to a GUID I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:

Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
    Dim noFile As String = Nothing
    Dim myGUID = Guid.NewGuid()
    Dim newFileName As String = myGUID.ToString() & ".jpg"
    Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
    If fu_picture.HasFile Then
        fu_picture.SaveAs(fileLocationOnServerHardDisk)
    Else
        myGUID = noFile
    End If
    Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
    Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (@f1,@f2,@f3,@f4,@f5,@f6,@f7,@f8)"
    Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("@f1", tb_booktitle.Text)
    cmd.Parameters.AddWithValue("@f2", tb_bookauthor.Text)
    cmd.Parameters.AddWithValue("@f3", tb_bookpubyear.Text)
    cmd.Parameters.AddWithValue("@f4", tb_bookpages.Text)
    cmd.Parameters.AddWithValue("@f5", tb_publisher.Text)
    cmd.Parameters.AddWithValue("@f6", tb_blurb.Text)
    cmd.Parameters.AddWithValue("@f7", "img/thumb/" & newFileName)
    cmd.Parameters.AddWithValue("@f8", rbl_Stars.SelectedValue)
    oleDbConn.Open()
    cmd.ExecuteNonQuery()
    System.Threading.Thread.Sleep("2000")
    Response.Redirect("~/addedrecord.aspx")

End Sub

Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged

End Sub
End Class

Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist

A: You should pass DBNull.Value to your db if you fail the requirement
 cmd.Parameters.AddWithValue("@f7", _
               if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)

The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.


text:
Q: Read and write the content of file 10 times I have a text file "hello.txt", I need to read that file and write to stdout 10 times, how can I do that?
What I am doing presently is as follows:-
#include<stdio.h>
main(){
 int c,i;
 FILE *fp;
 for(i=0;i<10;++i) {
    fp = fopen("hello.txt","r");
    for(;c!=EOF;c= getc(fp),putchar(c));
    fclose(fp);
 }
 return 0;
}

This code is printing contents only 1 time but not 10 times.

A: The bug is that at the end of first iteration value of variable  c becomes  EOF, and in all next iterations loop break due to c != EOF for loop's condition and couldn't print any char. In-fact you are using uninitialized c in comparison that causes undefined behavior in your code as @alk notice and also comment to your question.
You should (re-)initialise c at starting of each for loop.
Replace:
for(;c!=EOF;c= getc(fp),putchar(c));

by:
for(c = getc(fp); c != EOF; putchar(c), c= getc(fp));
 // ^^ always initialize    ^^          ^^ swap order

Additionally, if you want to read a file again and again then better approach is to use void rewind ( FILE * stream );  function, You need to rewind file pointer to the beginning of the file at the end of loop, something like:
 fp = fopen("hello.txt", "r");
 for(i = 0; i < 10; ++i) {
    for(c = getc(fp); c != EOF; c = getc(fp), putchar(c));
    rewind(fp);
 }
 fclose(fp);

Note: To make code readable use space after ; and ,.

A: #include<stdio.h>
main(){
 int c,i;
 FILE *fp;
 for(i=0;i<10;++i) {
    fp = fopen("hello.txt","r");
    while ((c = getc(fp)) != EOF) {
      putchar(c);
    }
    fclose(fp);
 }
 return 0;
}

As when in your code c becomes EOF the loop will forever be ignored!

A: You have to initialize c before reading file again. In your code once c is EOF it stays it forever and does not go in for loop.
c = 0;
for(;c!=EOF;c= getc(fp),putchar(c));


text:
Q: Can't install Ubuntu 12.04 LTS on Dell Vostro 3460 I trying to install Ubuntu 12.04 LTS on Dell Vostro 3460, Intel Core i7-3632QM, 1TB SATA + 32GB SSDR mSATA.
My goal is to install dual boot (Windows 8 is already installed).
After I boot from Ubuntu CD, I get the following screen:

(From this screen you can't define the disks and move forward with the installation.)

A: Try to Boot from USB Stick.
http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-ubuntu
or from your windows
http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows


text:
Q: What is the most advanced image editing FLOSS? Is it still GIMP? Inkscape? Are they too different to compare? Does anything come close to the two? Are they more/less advanced than Photoshop?
note: advanced = more features

A: Krita is quite feature rich as far as capabilities if you like KDE software, I'm not really sure how it compare's to GIMP, as I'm I don't enjoy image editing, but I seem to recall reading it's better at some things (CMYK Maybe? or what is color depth?) than the GIMP. From what I have seen/heard it's a powerful  that most people never seem to hear about. Here is a pre KDE 4 comparison of Krita and the GIMP.

A: GIMP and Inkscape aren't comparable: GIMP is a bitmap editor, Inkscape is a vector graphics editor.
GIMP is the uncontested leader amongst open source bitmap editors, feature-wise. It ranks closely with Photoshop. However GIMP has poor support for the CMYK color space, which is used by most "serious" color printers; I'm told this makes it unsuitable for many applications. As usual Wikipedia has a comparison of raster graphics editors, which may or may not include all important criteria.
There are many different types of vector graphics. Inkscape is a leader in its field, which is two-dimensional general-purpose schemas and scalable graphics, made mainly of straight lines, simple curves and filled regions. Other programs may perform better for CAD, electronics schemas, geometrical constructions, state diagrams, fonts, 3D modeling, etc.


text:
Q: PHPUnit: How to mock a function on a class? I have a class called "QueryService". On this class, there is a function called "GetErrorCode". Also on this class is a function called "DoQuery". So you can safely say I have something like this:
class QueryService {
    function DoQuery($request) {
        $svc = new IntegratedService();
        $result = $svc->getResult($request);
        if ($result->success == false)
            $result->error = $this->GetErrorCode($result->errorCode);
    }

    function GetErrorCode($errorCode) {
         // do stuff
    }
}

I want to create a phpunit test that will test "DoQuery". However, I want the result of "GetErrorCode" to be determined by a mock. In other words, I want to say that if $errorCode = 1, GetErrorCode must bypass whatever logic is in this function, and just return the word "ONE". If it is any number other than 1, it must return "NO".
How do you set this up using PHPUNIT Mocks?

A: To test this class, you would mock the IntegratedService. Then, the IntegratedService::getResult() can be set to return what ever you like in a mock.
Then testing becomes easier. You also need to be able to use Dependency Injection to pass the mocked service instead of the real one.
Class:
class QueryService {
    private $svc;

    // Constructor Injection, pass the IntegratedService object here
    public function __construct($Service = NULL)
    {
        if(! is_null($Service) )
        {
            if($Service instanceof IntegratedService)
            {
                $this->SetIntegratedService($Service);
            }
        }
    }

    function SetIntegratedService(IntegratedService $Service)
    {
        $this->svc = $Service
    }

    function DoQuery($request) {
        $svc    = $this->svc;
        $result = $svc->getResult($request);
        if ($result->success == false)
            $result->error = $this->GetErrorCode($result->errorCode);
    }

    function GetErrorCode($errorCode) {
         // do stuff
    }
}

Test:
class QueryServiceTest extends PHPUnit_Framework_TestCase
{
    // Simple test for GetErrorCode to work Properly
    public function testGetErrorCode()
    {
        $TestClass = new QueryService();
        $this->assertEquals('One', $TestClass->GetErrorCode(1));
        $this->assertEquals('Two', $TestClass->GetErrorCode(2));
    }

    // Could also use dataProvider to send different returnValues, and then check with Asserts.
    public function testDoQuery()
    {
        // Create a mock for the IntegratedService class,
        // only mock the getResult() method.
        $MockService = $this->getMock('IntegratedService', array('getResult'));

        // Set up the expectation for the getResult() method
        $MockService->expects($this->any())
                    ->method('getResult')
                    ->will($this->returnValue(1));

        // Create Test Object - Pass our Mock as the service
        $TestClass = new QueryService($MockService);
        // Or
        // $TestClass = new QueryService();
        // $TestClass->SetIntegratedServices($MockService);

        // Test DoQuery
        $QueryString = 'Some String since we did not specify it to the Mock';  // Could be checked with the Mock functions
        $this->assertEquals('One', $TestClass->DoQuery($QueryString));
    }
}

A: You need to use PHPUnit to create your Subject Under Test. If you tell PHPUnit which methods you would like to mock it mock only these method and the rest of class methods will stay as from original class.
So an example test could look like this:
public function testDoQuery()
{
    $queryService = $this->getMock('\QueryService', array('GetErrorCode')); // this will mock only "GetErrorCode" method

    $queryService->expects($this->once())
        ->method('GetErrorCode')
        ->with($this->equalTo($expectedErrorCode));
}

Anyway, as answer above says, you should also use Dependency Injection pattern in order to make possible mock IntegratedService as well (because based on the example above you need to know $result->success value).
So the right test should look like this:
public function testDoQuery_Error()
{
    $integratedService = $this->getMock('\IntegratedService', array('getResult'));

    $expectedResult = new \Result;
    $expectedResult->success = false;

    $integratedService->expects($this->any())
        ->method('getResult')
        ->will($this->returnValue($expectedResult));

    $queryService = $this->getMockBuilder('\QueryService')
        ->setMethods(array('GetErrorCode'))
        ->setConstructorArgs(array($integratedService))
        ->getMock();

    $queryService->expects($this->once())
        ->method('GetErrorCode')
        ->with($this->equalTo($expectedErrorCode))
        ->will($this->returnValue('expected error msg');

    $this->assertEquals($expectedResult->error, 'expected error msg');
}

public function testDoQuery_Success()
{
    $integratedService = $this->getMock('\IntegratedService', array('getResult'));

    $expectedResult = new \Result;
    $expectedResult->success = true;

    $integratedService->expects($this->any())
        ->method('getResult')
        ->will($this->returnValue($expectedResult));

    $queryService = $this->getMockBuilder('\QueryService')
        ->setMethods(array('GetErrorCode'))
        ->setConstructorArgs(array($integratedService))
        ->getMock();

    $queryService->expects($this->never())
        ->method('GetErrorCode');
}


text:
Q: How to check the Field value Case I wanna check the field value should be the Case sensitive. So, how to achieve this by using validation rule.
e.g John Milton Roa - Ltd.

A: I would suggest using REGEX function. Something like this should do the work:
NOT(REGEX(Name, "([A-Z]([a-z])+\\s?)+"))

You can create your own regular expression to meet your needs (like ignoring special words - a, the, etc.). So this should be quite flexbile solution

A: Try this
REGEX(Name, ".*\\b\\p{Ll}.*" )

A: You can use below formula in validation condition:
IF(LEFT(fieldname,1) <> LEFT(UPPER(fieldname),1),true,false)


text:
Q: building asp.net mvc from sources I want to build my asp.net mvc project with original  mvc sources. All works fine (solution is building and working as expected) except desiging razor cshtml-pages. Intellisence do not understand command @model. Look at screenshot - it explain my problem.
Is there any way to fix this problem?
Screenshot http://i60.fastpic.ru/big/2013/1005/8a/36343e4b9a7f850b6dc290ec7501978a.png
at the left - solution with ASP.NET MVC bilded from sources,
at the right - solution using original MVC assemblies from GAC

A: i dont think you need the @ symbol there and also i think it should be Model so:
@{
    ViewBag.Title = Model.Value
}


text:
Q: VBA Code for Excel that Pulls Data in/ Recalculates workbook and then PDF hourly Runs fine initially eventually starts PDFing blank sheets As title suggests I have reworked a VBA code that basically runs every hour on the hour (or when it initially gets started). It refreshes the connection and then recalculates the sheets, PDFs the file and saves in 3 separate file locations. It's a pretty basic code but I can't get it to run consistently. Usually it PDFs 3-4 times (3-4 hours) before I start getting a PDF of blank pages and excel has to be forced closed and restarted. Then it runs fine again. Sometimes but not all the time I see the "Not enough resources to display" message from excel. Any suggestions would be greatly appreciated.
Sub RecalcPDF()

Application.ScreenUpdating = False
 On Error Resume Next
'looks to find data in the table, writes the message, sends the message, and tells the timer to reset
Application.OnTime Sheets("Manual Inputs").Range("A28") + Sheets("Manual Inputs").Range("A27"),
"RecalcPDF", Schedule:=False
Application.Calculation = xlManual
Sheets("Manual Inputs").Range("A1") = Now
Sheets("Manual Inputs").Select
Sheets("Manual Inputs").Activate
ActiveSheet.Calculate
Application.Wait (Now + TimeValue("0:00:03"))
ActiveWorkbook.RefreshAll
Application.Calculate

Dim FileName As String
Dim Path As String
    FileName = Sheets("Manual Inputs").Range("D44")
    Path = Sheets("Manual Inputs").Range("D43")
    '## Add the PATH and EXTENSION to the filename
    FileName = Path & FileName & ".pdf"

    FileName2 = Sheets("Manual Inputs").Range("D47")
    Path2 = Sheets("Manual Inputs").Range("D46")
    '## Add the PATH and EXTENSION to the filename
    FileName2 = Path2 & FileName2 & ".pdf"

    FileName3 = Sheets("Manual Inputs").Range("D50")
    Path3 = Sheets("Manual Inputs").Range("D49")
    '## Add the PATH and EXTENSION to the filename
    FileName3 = Path3 & FileName3 & ".pdf"

With Sheets(Array("Daily Dose Display", "Station")).Select
Sheets("Daily Dose Display").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    FileName, Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    FileName2, Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    FileName3, Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False

End With
Application.OnTime Sheets("Manual Inputs").Range("A28") + Sheets("Manual Inputs").Range("A27"),
"RecalcPDF", Schedule:=True
Application.ScreenUpdating = True

End Sub

A: Here is a very basic logging implementation you can try.
Public Sub WriteLog(ByVal msg As String)

    Dim fh As Integer

    fh = FreeFile
    Open "C:\Users\user\Documents\application.log" For Append As #fh
    Print #fh, Format(Now, "mm/dd/yyyy HH:nn:ss> ") & msg
    Close #fh

End Sub

Then you might use it like this
WriteLog "RecalcPDF: Exporting sheet " & ActiveSheet.Name & " to file " & FileName

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    FileName, Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False


text:
Q: Reference one RoslynPad script from another What I'd like to do is reference one script from another.
One way to make this happen might be using assemblies.  RoslynPad allows compiling a script into an assembly.  Here is what I have tried so far.
Script A, which is compiled to SOME_PATH\thing.dll
    class Thing
    {
        public string Name { get; set; }
    }

Script B
    #r "SOME_PATH\thing.dll"

    using static Program;

    var t = new Thing();
    t.Name = "TEST";
    t.Name.Dump();

This gives the error "The type or namespace 'Thing' could not be found..." so I tried the following.
    #r "SOME_PATH\thing.dll"

    var t = new Program.Thing();
    t.Name = "TEST";
    t.Name.Dump();

This gave the following error "The type name 'Thing' does not exist in the type 'Program'".
Is there a way to "Compile and Save assembly" and then reference it from another script?  Or, is there a more direct way to cross reference between scripts?

A: What you're looking for is the #load directive:
#load "Path\To\ScriptA.csx"

var t = new Thing();

You can read more about the C# script variant in the Roslyn wiki. Note that not everything there is relevant to RoslynPad, which unlike the C# Interactive window, is not a REPL.


text:
Q: How to convert a xsd type with ref="xs:schema" attribute into c# class? I'm trying to convert TSFType in the following xml schema to a c# class. But I don't know how to deal with <xs:element ref="xs:schema"/>. Any suggestion?
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="urn:IEEE-1641:2010:STDTSF"
 elementFormDefault="qualified"
 attributeFormDefault="unqualified"
 tsf="urn:IEEE-1641:2010:STDTSF"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:complexType name="TSFType">
        <xs:sequence>
            <xs:element name="interface">
                <xs:complexType>
                    <xs:sequence>
                        <xs:annotation>
                            <xs:documentation>Any XMLSchema definition can be used whose element/attribute types map onto a 1641 type</xs:documentation>
                        </xs:annotation>
                        <xs:element ref="xs:schema"/>
                        <!--xs:any namespace="http://www.w3.org/2001/XMLSchema" processContents="strict" maxOccurs="unbounded"/-->
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
        <xs:attribute name="name" type="xs:NCName" use="required"/>
    </xs:complexType>

    <xs:element name="TSFLibrary">
        <xs:annotation>
            <xs:documentation>TSFLibrary represents the IEEE 1641 intechangeable Signal Model Library</xs:documentation>
        </xs:annotation>
        <xs:complexType>
            <xs:sequence>
                <xs:element name="description" type="string" minOccurs="0"/>
                <xs:element name="TSF" type="tsf:TSFType" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:NCName" use="required"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

The entire xsd is available here.
I have tried xsd.exe, and it give the following incorrect class for interface element in which the schema type is not defined.
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:IEEE-1641:2010:STDTSF")]
public partial class TSFTypeInterface {

    private schema schemaField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace="http://www.w3.org/2001/XMLSchema")]
    public schema schema {
        get {
            return this.schemaField;
        }
        set {
            this.schemaField = value;
        }
    }
}

A: Did you run this command? xsd STDTSF.xsd STDBSC.xsd /c
Try this instead: xsd STDTSF.xsd XMLSchema.xsd STDBSC.xsd /c
It will generate a lot of stuff, including the following class
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.w3.org/2001/XMLSchema")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://www.w3.org/2001/XMLSchema", IsNullable=false)]
public partial class schema : openAttrs {

    private openAttrs[] itemsField;

    private topLevelSimpleType[] simpleTypeField;

    private topLevelComplexType[] complexTypeField;

    private namedGroup[] groupField;

    private namedAttributeGroup[] attributeGroupField;

    private topLevelElement[] elementField;

The XSD you need is found here: https://www.w3.org/2001/XMLSchema.xsd
I made a pastebin of the file, in case you have any issues
http://pastebin.com/4upNhiB1


text:
Q: URL Inepretation in Granite TIDE with flex I did the presentation tier analysis of my application with HTTPWatch.In that I found there are request being made with followng URL,
https://hostname/path/graniteamf/amf

with each of these request taking morearound 2s.I am not able to interpret this URL to the actual problem.Is it because of the UI components being loaded or the method being called.
Would be happy to get any information on the same.
Cheers,
Dwarak

A: Is that the actual string, or did you replace 'hostname' and 'path' with placeholders? What is defined in your services-config.xml file? Are the requests failing, too slow, or unexpected?
Best guess given the info you provided, it sounds like you may just need to update/fix services-config.xml. (Make sure you really want https -- if you're trying to use http that can cause an issue too.)


text:
Q: Split multiple columns to cells using vba enter code here
enter image description here
my data in excel
I am having trouble to split multiple columns to cells. I can perform this in for one column data as per the code below. Can anyone please show me how to do this for multiple column for this file (11 column).
My code is shown here:
Option Explicit

Sub Get_Data_From_File()

Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim sp As String
Dim myarray() As String
Dim i, a As Integer
Dim lastrow As Integer
Dim lastclm As Integer

Application.ScreenUpdating = False

FileToOpen = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*xls*")

If FileToOpen <> False Then
    Set OpenBook = Application.Workbooks.Open(FileToOpen)
    OpenBook.Sheets(1).Range("A:A").Copy
    ThisWorkbook.Worksheets.Add(After:=Sheets(1)).Range("A1").PasteSpecial xlPasteValues
    OpenBook.Close False

End If
lastrow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

For a = 1 To lastrow
sp = ActiveSheet.Cells(a, 1).Value
myarray = Split(sp, "-")
For i = 0 To UBound(myarray)
ActiveSheet.Cells(a, i + 1).Value = myarray(i)

Next
Next
Application.ScreenUpdating = True

End Sub

A: Here's some code that will do it. There will be blank spaces if one string had more dashes than another. It also assumes the maximum number of dashes is 16 (15+1)
I might make a PQ solution as well if I have more time later today.
Sub split()

Dim myarray() As String
Dim sp As String
Dim a, b, c, d, i, lastrow, lastcolumn As Long
Dim myrange As Range

lastrow = ActiveSheet.Cells.End(xlDown).Row
lastcolumn = ActiveSheet.Cells.End(xlToRight).Column
d = 1
b = 1

Do While b <= lastcolumn
        For c = 1 To 15
            Cells(1, d + 1).EntireColumn.Columns.Insert
        Next
    For a = 1 To lastrow
        sp = ActiveSheet.Cells(a, d).Value
        myarray = VBA.split(sp, "-")
            For i = 0 To UBound(myarray)
                ActiveSheet.Cells(a, i + d).Value = myarray(i)
            Next
   Next
   d = d + 15 + 1
   b = b + 1
Loop

Set myrange = ActiveSheet.UsedRange
    For a = myrange.Columns.Count To 1 Step -1
        If Application.CountA(Columns(a).EntireColumn) = 0 Then
            Columns(a).Delete
        End If
    Next a
End Sub

A: I'm not sure exactly what you want.
Here is code that

*

*splits each column in each row

*creates a new row consisting of each split item, replacing the original.

If you want the original interleaved with the results, that is pretty simple to do by altering how the results array is constructed.

*

*The code assumes the data is on your Excel worksheet in a format similar to what you show in your screenshots.

*In the code, the splitted rows are written on an different worksheet

*You can change the relevant factors to overwrite the original, if you prefer

*The data is read into a VBA array for faster processing

*As each column is split, the splitted information is added to a collection

*After we finish processing each row, the collection object is added to a dictionary.

*When done, each row is written into a results array

*The results array is written back to a worksheet.
Note that working in a VBA array is generally much faster than working on the worksheet
Option Explicit
Sub multiColumnSplit()
    Dim wsSrc As Worksheet, wsRes As Worksheet, rRes As Range
    Dim vSrc As Variant, vRes As Variant
    Dim rwCol As Collection, D As Object
    Dim I As Long, J As Long, K As Long, V As Variant, W As Variant
    Dim lastRow As Long, lastCol As Long
    Dim S() As String
    Dim charCount As Long

'read data into array
Set wsSrc = Worksheets("sheet1")
With wsSrc
    lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    vSrc = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
End With

'will create Collection object for each row and store in dictionary by row number
Set D = CreateObject("Scripting.Dictionary")
For I = 1 To UBound(vSrc, 1)
    Set rwCol = New Collection
    For J = 1 To UBound(vSrc, 2)
        S = Split(vSrc(I, J), "-")
        For Each V In S
            rwCol.Add V
        Next V
    Next J
    D.Add Key:=I, Item:=rwCol
    Erase S
Next I

'create results array
K = 0
'how many columns
For Each V In D
    K = IIf(K > D(V).Count, K, D(V).Count)
Next V

ReDim vRes(1 To D.Count, 1 To K)

'fill results array
charCount = 0
I = 0
For Each V In D
    I = I + 1
    J = 0
    For Each W In D(V)
        J = J + 1
        vRes(I, J) = W

            'count characters to set column width
            K = Len(vRes(I, J))
            charCount = IIf(charCount > K, charCount, K)

    Next W
Next V

'Set results worksheet and range
Application.ScreenUpdating = False
On Error Resume Next
    Set wsRes = Worksheets("sheet2")
    Select Case Err.Number
        Case 9
            ThisWorkbook.Worksheets.Add
            ActiveSheet.Name = "Sheet2"
            Set wsRes = Worksheets("sheet2")
        Case Is <> 0
            MsgBox "Error No: " & Err.Number & vbLf & Err.Description
            Stop
    End Select
On Error GoTo 0
Set rRes = wsRes.Cells(1, 1).Resize(UBound(vRes, 1), UBound(vRes, 2))

'write the results
With rRes
    .EntireColumn.Clear
    .NumberFormat = "@"
    .Value = vRes
    .HorizontalAlignment = xlCenter
    .EntireColumn.ColumnWidth = charCount + 1
End With

End Sub

Original Data

Results


text:
Q: Change password of PDF file How can i change the password of a pdf file programmatically?
I have multiple pdf files in a folder and I want to change the password of all of them. I load the pdfs as described in the Quartz 2D Documentation
I can check if it is password protected, unlock it with the password, display it, but i can't change the password. Any help is appreciated.


text:
Q: Consume OAuth Tokens in ASP.Net Web Api 2.0 I have created a brand new WebService using ASP.Net Web Api 2.0 and am trying to use authorization based on an OAuth JWT token.  I have all of the basic wiring done with OWIN, but when I use the [Authorize] attribute, it fails, even for a valid token.  Can you help.
Edit: I narrowed down the issue.  It seems that the key is RS256 and SymmetricKeyIssuerSecurityKeyProvider doesn't handle that... Either that or I am passing the Key Provider the wrong information.  Any ideas how to fix that?
Here is the code of my startup.cs
using System.Configuration;
using System.Web.Http;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
using Microsoft.AspNet.Identity;

namespace SecuredApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
            var config = ConfigureWebApi();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        private HttpConfiguration ConfigureWebApi()
        {
            var config = new HttpConfiguration();
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter("Bearer"));
            config.MapHttpAttributeRoutes();
            return config;
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings.Get("Issuer");
            var audience = ConfigurationManager.AppSettings.Get("Audience");
            var secret = ConfigurationManager.AppSettings.Get("Secret");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                AllowedAudiences = new[] { audience },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
                }
            };
            app.UseJwtBearerAuthentication(
                jwtBearerAuthenticationOptions);

        }
    }
}


text:
Q: Axis_type="mercator" in bokeh I'm trying to run the chart given as example for Tile Provider Maps on the Bokeh geo-mapping site.
https://docs.bokeh.org/en/latest/docs/user_guide/geo.html.
    from bokeh.plotting import figure, show, output_file
from bokeh.tile_providers import CARTODBPOSITRON

output_file("tile.html")

# range bounds supplied in web mercator coordinates
p = figure(x_range=(-2000000, 6000000), y_range=(-1000000, 7000000),
           x_axis_type="mercator", y_axis_type="mercator")
p.add_tile(CARTODBPOSITRON)

show(p)

But instead of the expected chart I'm getting:
ValueError: expected an element of either Auto or Enum('linear', 'log', 'datetime'), got 'mercator'
If I delete the x_axis_type paremeters (x_axis_type="mercator", y_axis_type="mercator") I'm getting the chart, though as expected, without latitude and longitute labels. Is there a problem in the script or am I doing something wrong here?

A: Your version of Bokeh is too old, you will have to update to at least version 0.12.15 to use this feature


text:
Q: Jinja2 access a list of dict in javascript Hey all any idea how to access a list of dict ?
In Flask:
users = [{
    'username': 'john',
    'city': 'Toronto'
},
{
    'username': 'James',
    'city': 'Montreal'
}]

return render_template('home.html', users=users)

and in my template
<script>
    var users = {{users}}
</script>

All I get is

Uncaught SyntaxError: Unexpected token &

Thanks in advance

A: Apply toJson filter to make valid javascript object.
<script>
    var users = {{users | tojson | safe}}
</script>


text:
Q: AutoComplete Rails jquery validations trying to get the input to validate that the entered value is in the data element on blur function and if not to clear the input and get focus.
I can see the element if i output the data but just cant get it to compare
help would be appreciated
$('#ticket_source_name').on('railsAutocomplete.select', function(event, data){
        console.log('autocomplete select fired')
        $(this).blur(function(event){
            $(this).val((data.item ? data.item.self : "")).focus()
            console.log($(this).data.item)
          });
      });

A: For your comment that blur only triggered when focus lost but change triggered when element state get changed


text:
Q: accuracy of C_ARIMA_Gradtrans in R stats::arima The R function stats::arima calls to C_ARIMA_transPars to transform the autoregressive coefficients and keep them in the region of stationarity.
The derivatives of this transformation are needed to obtain the standard errors of parameter estimates. They are obtained by means of C_ARIMA_Gradtrans.
In the case of an AR(2) model I was working with, the derivatives returned by the latter function do not look accurate. As shown below, they differ from the values obtained by numerical methods (based on package numDeriv) and the values obtained based on the analytical expressions that are easy to get for the AR(2) model.
Example for the AR(2) model:
Generate and transform the AR coefficients:
require("numDeriv")
# random values for the AR coefficients
ARcoefs <- rnorm(2)
# transformation of AR coefficients
tp1 <- .Call(stats:::C_ARIMA_transPars, ARcoefs, c(2L,0L,0L,0L,0L,0L,0L), TRUE)[[1]]
# for the AR(2) model, the above reduces to:
tp2 <- tanh(ARcoefs)
tp2[1] <- tp2[1] - tp2[2] * tp2[1]
all.equal(tp1, tp2)
# [1] TRUE

Derivatives of the transformation with respect to the parameters:
# based on package "stats"
g1 <- .Call(stats:::C_ARIMA_Gradtrans, ARcoefs, c(2L,0L,0L,0L,0L,0L,0L))
# based on package "numDeriv" (numerical derivatives)
fnc <- function(x, i) .Call(stats:::C_ARIMA_transPars,
  x, c(2L,0L,0L,0L,0L,0L,0L), TRUE)[[1]][i]
g2 <- matrix(0, nrow=2, ncol=2)
g2[,1] <- numDeriv::grad(func=fnc, x=ARcoefs, i=1)
g2[,2] <- numDeriv::grad(func=fnc, x=ARcoefs, i=2)
# based on analytical derivatives
g3 <- matrix(0, nrow=2, ncol=2)
tmp <- 1/cosh(ARcoefs)^2
g3[1,1] <- tmp[1] - tanh(ARcoefs[2]) * tmp[1]
g3[2,2] <- tmp[2]
g3[2,1] <- -tanh(ARcoefs[1]) * tmp[2]

The second and third methods match each other but differ with the result obtained with C_ARIMA_Gradtrans.
all.equal(g2, g3)
# [1] TRUE
# output for ARcoefs = c(0.7, -0.4)
all.equal(g2, g1)
# [1] "Mean relative difference: 0.0004672373"
# output for ARcoefs = c(0.7, -0.4)
all.equal(g3, g1)
# [1] "Mean relative difference: 0.0004672373"

Looking at the source code, it is not straightforward to me to find out which approach or operations are involved (numerical or analytical derivatives).
It is strange that cosh (which is part of the derivative of tanh employed in the transformation) is not used. Also, a variable eps defined as 1e-3 is used, but this does not show up in the analytical derivatives. Maybe cosh is computed by other (less accurate) means?
Is there any reason explaining the less accurate results shown above?

A: (Should be a comment but written as an answer for formatting ...)
It looks like this block is indeed computing finite differences with an epsilon of 1e-3 (defined just above):
for (int i = 0; i < mp; i++) w1[i] = raw[i];
partrans(mp, w1, w2);           /* transform raw (w1) to w2 */
for (int i = 0; i < mp; i++) {
    w1[i] += eps;
    partrans(mp, w1, w3);       /* w3 = trans(w1+eps) */
    for (int j = 0; j < mp; j++)  /* calc derivative */
         A[i + j*n] = (w3[j] - w2[j])/eps;
    w1[i] -= eps;               /* restore value of w1 */
}

I wonder if the simple analytical expressions that you can use for AR(2) break down/get too unwieldy for higher-order AR models?
I would suggest that the next debugging step (not easy, unless you're already set up for it) would be to compile a standalone version of ARIMA_Gradtrans with a smaller value of eps to see if that helps in this case ...
Or use numDeriv::grad() with method="simple", method.args=list(eps=1e-3) and see if it matches the ARIMA_Gradtrans result.
Following your code above:
g2A <- t(jacobian(fnc,ARcoefs))
g2B <- t(jacobian(fnc,ARcoefs,
        method="simple",method.args=list(eps=1e-3))
all.equal(g1,g2A)   ## as before
## [1] "Mean relative difference: 0.000467239"
all.equal(g1,g2B)
## [1] TRUE
all.equal(g2B,g3)
## [1] "Mean relative difference: 0.000467239"
all.equal(g2A,g3)
## [1] TRUE

The next question is whether a relative difference of 5e-4 is actually important for your application ...


text:
Q: GPUImage framework screen recording chain Within Brad Larson's GPUImage framework, what would be the target chain for a painting app that recorded the screen as a video?
Is it:
GPUImageView -> GPUImageMovie -> GPUImageMovieWriter ?

A: So, as it works out, there isn't an appropriate chain, since there's no GPUImageOutput subclass that generates it's own texture content, without the help of the camera.
I subclassed GPUImageOutput (sort of), with something called GPUImageCanvas. So the finished chain was:
GPUImageCanvas -> GPUImageView -> GPUImageMovieWriter
Hope this helps anyone in a similar position!
Sam


text:
Q: Defining a Web Service Endpoint via Configuration instead of Code I'm interested in creating a web service endpoint in C#/.NET that is fully configurable. To keep it simple assume there is no GET/query/retrieval requirement. I just need some guidance on how to get started here.
The goal is to have a a core solution built, tested, and deployed that can then be configured for new objects thus avoiding a requirement to modify, build, and deploy the entire solution anytime an object is added/removed/modified. This configuration would have to support versioning given the environment it will operate in.
Assume we have a configuration file such as the following:
{
  "V1": {
    "Person": [
      {
        "Name": "FirstName",
        "Required": true,
        "Type": "string",
        "MaxLength": 25
      },
      {
        "Name": "Lastname",
        "Required": true,
        "Type": "string",
        "MaxLength": 25
      },
      {
        "Name": "Title",
        "Required": false,
        "Type": "string",
        "MaxLength": 50
      }
    ]
  },
  "V2": {
    "Person": [
      {
        "Name": "FirstName",
        "Required": true,
        "Type": "string",
        "MaxLength": 25
      },
      {
        "Name": "Lastname",
        "Required": true,
        "Type": "string",
        "MaxLength": 25
      },
      {
        "Name": "Title",
        "Required": false,
        "Type": "string",
        "MaxLength": 50
      },
      {
        "Name": "DateOfBirth",
        "Required": false,
        "Type": "DateTime"
      }
    ]
  }
}

With this configuration I want an application that will expose an endpoint for a caller to send an object and validate the object against the type rules. It should also expose a WSDL.
To be clear, I do not want to write a simple single generic endpoint that can take an array of key-value attributes and then validate - I want to generate a contract.
In essence, I'm trying to have a contract web service while not having to create POCOs. This will allow senders to more easily mock the endpoint for their development work.
For the curious, the incoming data will be sent to a messaging bus to be processed by other services. Thus, the endpoint needs to do the evaluation of type/length/etc but I don't want to create/update the POCOs and controllers along with all the testing and headaches of an enterprise deployment simply because some object has a new field.

A: The traditional way to do this is to define the types in a XSD file and define the service contract in a WSDL file that references the XSD files. You're doing pretty much the same thing in a bespoke JSON format, which is fine if you want to do the work, but you won't find there are a lot of tools out there to help you.
One problem you will quickly discover is that, while it is fairly trivial to define an interface from configuration or markup, that doesn't get you very far, because you will still need code to handle service calls. Since you say you don't want to work with tag/value pairs, that means your code will need to be strongly typed, meaning that a generalized solution is not possible.
I suppose you could build something that will dynamically generate code to translate from the strongly-typed service message to a general format c# data structure.  Which sounds an awful lot like the tag/value sort of solution you were avoiding.  So you're not really solving a problem, just moving it, albeit you will move it from the public interface to private code.

A: Not sure if I've completely understood but I've successfully implemented a general service for any contract using WCF 4 routing in order to execute, record & playback SOAP messages.  Your use may or may not be in the same vein but try these links (I know links are not supposed to be posted as an answer but the articles are too big to summarise)
Microsoft current documentation
Michele Bustamante wrote some articles too.  Not sure if these are what I used - I can't seem to find the originals but these seem to cover it:
Part 1
Part 2
Another example
The key to it is this
namespace WcfRouterService
{
    [ServiceContract]
    public interface IRouter
    {
        [OperationContract(Action = "*", ReplyAction = "*")]
        Message Action(Message msg);
    }

public Message Action(Message msg)
        {
            try
            {
                return ProcessMessage(msg);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.ToString());
                throw;
            }
        }
}

Not sure if that helps or not and I didn't use JSON.


text:
Q: Links on Heroku maintenance pages don't work When I put up our maintenance page, I include some links to our contact us, a link to our twitter feed for more details, etc. However, I just noticed that (at least in chrome) the links don't open. It's clearly due to the page being hosted from within an iframe.
The following error shows up in the console:
Refused to display document because display forbidden by X-Frame-Options.
We're hosting our maintenance page on S3, as heroku suggests. This limits our ability to modify headers, etc. Any suggestions on how to get these links to work?
Thanks in advance

A: I think your problem could be related to headers in the response of your links.
https://developer.mozilla.org/en-US/docs/The_X-FRAME-OPTIONS_response_header
I don't know if Heroku configures the server with those headers by default or your app adds them. But at least, you got something to chew on.
HTH!

A: I just encountered the same issue. I worked around it using target='_blank'.

A: You can set the target attribute on each anchor tag to "_parent" in order to open the link in the parent frame:
click here

Alternatively, you could use a base tag in the head of the page to define the target attribute for all links in the page:
<base target="_parent">


text:
Q: ANTLR3: compiling warning(200) "multiple alternatives" I'm using antlrworks1.5 with antlr3 and encountered the following warning/error. I have been working on this issue for a couple of days, could anybody give me some hint? Thank you in advance.
The minimized grammar file is:
grammar p;

cs : '[' c ']';
c  : 'x' ('p' c)*;

AntLR reports the following warning: warning(200):Decision can match input such as "'p'" using multiple alternatives:1,2
ttp://i.stack.imgur.com/eg7cQ.png
http://i.stack.imgur.com/rnRvx.png
I am wondering:
(1) what is the meaning of 'matched using multiple alternatives"? does it means that the grammar is ambiguous? If it is, could you please give me some example?
(2) how to solve this problem in general?
Thank you very much.

A: The grammar is indeed ambiguous. To understand this, replace the Kleene star by transforming to plain BNF:
c ::= 'x'
    | c 'p' c

Now this is both left- and right-recursive, so derivations can build subtrees on either side, thus creating different parse trees for the same words.
Directly from the EBNF, this is slighly harder to see. Here the difference manifests itself in parse trees differing in depth, depending on whether the repetition is used or not:
       c                 c
      /|                /|\
     / |               | | \
    / /|\              | |  \
   / / | \     vs.     | |   c
  / /| | |             | |  /|\
 | / c | c             | | | | c
 | | | | |             | | | | |
 x p x p x             x p x p x

ANTLR's perspective on this is determined by the SLL algorithm. When processing the repetition, it must be decided whether to
proceed with another iteration, or complete the right hand side of the c production. In either case, a lookahead
token from the followers of c is expected - in the first case, because c is at the very end of the repeated part,
in the second case because the repetition occurs at the end of the c production. Thus the inability to decide.
The solution is fairly obvious: make sure that there is one unique way to obtain a repeated sequence. In this case, either omit the recursion by just having c : 'x' ('p' 'x')*;, or replace the Kleene star by an option, c : 'x' ('p' c)?;.


text:
Q: Using DB2 in a mixed .net core / .net 4.7 project We want to reuse our .net 4.7 library (C#) to Access an DB2 10.5 database from a new .net core 2.2 Project. Unfortunaltely I get errors if I open the Connection:

System.InvalidOperationException: "SQL1159  Initialization error with
  DB2 .NET Data Provider, reason code 2, tokens
  D:\Projekte\Main-Branch-IpIdentity\Services\InvoiceApi\InvoiceApi\bin\db2app64.dll,
  , Process Owner

The missing ddl can be found in path under C:\Program Files\IBM\SQLLIB\BIN.
I copied all out of this directory to the project output directory and got:

System.InvalidOperationException: "SQL1159  Initialization error with
  DB2 .NET Data Provider, reason code 10, tokens 0.0.0, 10.5.5, Process
  Owner:

I wrote a console project in .net core, calling a .net core dll with Access to DB2:
   class Program
   {
      static void Main(string[] args)
      {
         var count = DB2AccessCore.Db2Access.GetCount();
      }
   }

namespace DB2AccessCore

  public class Db2Access
  {
     public static int GetCount()
     {
        var con = new DB2Connection("....");
        con.Open();

        var cmd = con.CreateCommand();
        cmd.CommandText = "SELECT COUNT(*) FROM data.abstimmfeldausschnitt";
        var a = cmd.ExecuteScalar();
        con.Close();
        return (int)a;
     }
  }

}
}
The example works fine, also if I use the same Code in a .net 4.7 console and dll. But I call the 4.7 dll from the core console I get a exception:

System.AccessViolationException: "Attempted to read or write protected
  memory. This is often an indication that other memory is corrupt."

Sounds not good…
What do I wrong, or is it not possible with DB2 to mix between core and 4.7? Has anybody already done this?
Thanks for help!


text:
Q: how to call method with interface as parameter how to call method with interface as parameter xamarin form. I need to call this method and pass the interface
        //Method I am trying to call
        public virtual unsafe void Check (global::Com.Test.Precheck.Client.ITestClientListener listener)
        {
            const string __id = "check.(Lcom/test;)V";
            try
            {
                JniArgumentValue* __args = stackalloc JniArgumentValue [1];

                __args [0] = new JniArgumentValue ((listener == null) ? IntPtr.Zero : ((global::Java.Lang.Object) listener).Handle);

                _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args);

            }
            finally
            {
                global::System.GC.KeepAlive (listener);
            }
        }

Error  Specified cast is not valid
where I try

//Class that inherits ITestClientListener interface
    TestClientListener obj = new TestClientListener();

then call Check method that accepts ITestClientListener
Check((ITestClientListener)obj)

  public class TestClientListener : ITestClientListener
    {
        public TestClientListener()
        {

        }
        public IntPtr Handle => throw new NotImplementedException();

        public int JniIdentityHashCode => throw new NotImplementedException();

        public JniObjectReference PeerReference => throw new NotImplementedException();

        public JniPeerMembers JniPeerMembers => throw new NotImplementedException();

        public JniManagedPeerStates JniManagedPeerState => throw new NotImplementedException();

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Disposed()
        {
            throw new NotImplementedException();
        }

        public void DisposeUnlessReferenced()
        {
            throw new NotImplementedException();
        }

        public void Finalized()
        {
            throw new NotImplementedException();
        }

        public void OnError(int p0)
        {
            throw new NotImplementedException();
        }

        public void OnFinish(string p0, string p1, string p2, string p3, string p4, string p5)
        {
            throw new NotImplementedException();
        }

        public void SetJniIdentityHashCode(int value)
        {
            throw new NotImplementedException();
        }

        public void SetJniManagedPeerState(JniManagedPeerStates value)
        {
            throw new NotImplementedException();
        }

        public void SetPeerReference(JniObjectReference reference)
        {
            throw new NotImplementedException();
        }

        public void UnregisterFromRuntime()
        {
            throw new NotImplementedException();
        }
    }


text:
Q: Upstart service stops when I log out I've written an upstart script I want to run when my server starts up, only it does not. It will run when I call sudo start wiki, where wiki is the name of my service, however it stops running when I log out.
This is the script:
description "run the noplwiki web service"

start on runlevel [2345]

script
    logfile="/var/log/wiki.log"
    source="/home/matt/python/noplwiki/"

    exec >> ${logfile} 2>&1

    . /home/matt/.virtualenvs/noplwiki/bin/activate

    cd ${source}
    exec python wiki.py
end script

this is the log file for when I start it when I'm logged in, request something from the service and then log out:
[20/Oct/2012:18:27:28] ENGINE Listening for SIGHUP.
[20/Oct/2012:18:27:28] ENGINE Listening for SIGTERM.
[20/Oct/2012:18:27:28] ENGINE Listening for SIGUSR1.
[20/Oct/2012:18:27:28] ENGINE Bus STARTING
[20/Oct/2012:18:27:28] ENGINE Started monitor thread '_TimeoutMonitor'.
[20/Oct/2012:18:27:28] ENGINE Started monitor thread 'Autoreloader'.
[20/Oct/2012:18:27:29] ENGINE Serving on 0.0.0.0:8080
[20/Oct/2012:18:27:29] ENGINE Bus STARTED
192.168.1.64 - - [20/Oct/2012:18:27:41] "GET / HTTP/1.1" 200 699 "" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0"
192.168.1.64 - - [20/Oct/2012:18:27:41] "GET /js/index.js HTTP/1.1" 304 - "http://192.168.1.66:8080/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0"
[20/Oct/2012:18:27:51] ENGINE Restarting because /home/matt/.virtualenvs/noplwiki/local/lib/python2.7/site-packages/pymongo/helpers.py changed.
[20/Oct/2012:18:27:51] ENGINE Stopped thread 'Autoreloader'.
[20/Oct/2012:18:27:51] ENGINE Bus STOPPING
[20/Oct/2012:18:27:51] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('0.0.0.0', 8080)) shut down
[20/Oct/2012:18:27:51] ENGINE Stopped thread '_TimeoutMonitor'.
[20/Oct/2012:18:27:51] ENGINE Bus STOPPED
[20/Oct/2012:18:27:51] ENGINE Bus EXITING
[20/Oct/2012:18:27:51] ENGINE Bus EXITED
[20/Oct/2012:18:27:51] ENGINE Waiting for child threads to terminate...
[20/Oct/2012:18:27:51] ENGINE Re-spawning wiki.py
Traceback (most recent call last):
  File "wiki.py", line 46, in <module>
    cherrypy.quickstart(Server(), '/', conf)
  File "/home/matt/.virtualenvs/noplwiki/local/lib/python2.7/site-packages/cherrypy/__init__.py", line 161, in quickstart
  File "/home/matt/.virtualenvs/noplwiki/local/lib/python2.7/site-packages/cherrypy/process/wspbus.py", line 332, in block
  File "/home/matt/.virtualenvs/noplwiki/local/lib/python2.7/site-packages/cherrypy/process/wspbus.py", line 376, in _do_execv
OSError: [Errno 2] No such file or directory: '/home/matt/python/noplwiki'

Why does it shut down when I log out? As far as I can tell the helpers.py file has not been changed.
-rw-rw-r-- 1 matt matt 7350 Oct 15 20:32 /home/matt/.virtualenvs/noplwiki/local/lib/python2.7/site-packages/pymongo/helpers.py

A: As @Tuminoid guessed and the OP realized in his comment here, his home directory is encrypted.
Now @Tuminoid correctly pointed out in his comment that the easiest fix for the issue is to simply move the files needed for the service to run from the home directory to any location that is available all the time, not only while the specific user is logged in and has his home directory decrypted.


text:
Q: Mmap() Segmentation Fault Error While Reading The Stored Valued I'm writing a program in C and using mmap() for processes to return the calculation to their main process.
Here is the code:
int *results = mmap ( NULL, count*sizeof(int),
 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 );

for (i = 0; i < count; i++)
   {
      pid_t pid = fork();
      if (pid == 0)
      {
         /// some calculations in the child.
         }

         // I save the result to ith element of mmap
         results[i] = calculation;
      }
      else{
         wait(NULL);
      }

   }

   // The following part arises an error called segmentation fault.
    for (i = 0; i < count; i++)
   {
      printf(" results[%d] = %d.\n", i, results[i]);
   }

When I try to access the results, I get an error. How can I fix that?
Any help is appreciated.

A: To cite man mmap:

MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero.  The fd argument is ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this.


text:
Q: How to change array to json in php I have this php array
$var = $var = explode("[;;]",$result['infoplantilla']);
$numRow = count($var);
$form = array
        (
            "numRow",$numRow,
            "selectOption",$var,
            "prefijo",$result['prefijo'],
            "Sufijo",$result['sufijo'],
            "Plantilla",$result['descripcion']
            );

echo  json_encode($form);

So when I try to return this to the ajax call it return me value something like this .
["numRow",2,"selectOption",["baners.Idbaner= INMOMEXICO.ANUNCIO.ID"," monedas.Idmoneda= INMOMEXICO.ANUNCIO.MONEDA"],"prefijo","MXSAEI","Sufijo","-14","Plantilla","SAE"]

Which is not a Json string can any one help me out where I am going wrong because supposedly I should get a Json string from the array
Thanks in Advance

A: The problem is that your array is NOT an associative array.
Try this:
$form = array
        (
            "numRow" => $numRow,
            "selectOption" => $var,
            "prefijo" => $result['prefijo'],
            "Sufijo" => $result['sufijo'],
            "Plantilla" => $result['descripcion']
         );


text:
Q: What is the term for a child that's in between toddler and adolescent? I'm trying to come up with terms to describe the various age ranges for children up through teenager and I'm stuck trying to describe someone who's in the age range of about 6 through 10. In other words, I'm trying to fill in the gap:
newborn -> infant -> toddler -> ??? -> pre-teen -> teenager
I considered that "pre-teen" technically fits that age range, but to me, that term strongly implies a child in the 10-12 range (just before they hit 13 and become a teenager). I also considered but rejected "pre-pubescent", which also technically fits, but is more focused on a child's level of sexual maturity, which is irrelevant to the situation I'm trying to describe.
Most references I found simply refer to children of that age as a "child", but doesn't that term apply equally to anyone under the age of majority, or at the very least, anyone pre-adolescence?

A: I think preschooler  and school-aged can define that stage of a child:
Some age-related development periods and examples of defined intervals are:

newborn (ages 0–4 weeks);
infant (ages 4 weeks – 1 year);
toddler (ages 1–3 years);
preschooler (ages 4–6 years);
school-aged child (ages 6–13 years);
adolescent (ages 13–19).


text:
Q: Capitalization of foreign proper nouns Serbo-Croatian grammar requires that only the first word of a multi word name of a place or an object is capitalized. For example, "Stari most" is a name of a bridge in Bosnia-Herzegovina.
If we don't translate the name to English do we capitalize both words as "Stari Most" or do we keep the native language capitalization?

A: Loan words, including proper names, inevitably succumb to the conventions of the language that borrows them. Hence the Serbo-Croat Stari most will inevitably (and quite reasonably) be rendered by most native speakers of English as Stari Most, because using the initial capital in all the important elements of a proper name is a critical marker of what is a proper name in English.
Indeed, in this example, without being capitalized, most would cause the majority of readers to do a double-take, because its spelling and capitalization will cause it to be readily confused with the English adjective most.

A: If we do not translate the names (and more often than not we do not or should not translate them), I believe the original spelling & capitalization is more appropriate (maybe consider the use of italics for names that consist of two or more words).


text:
Q: How to inject service in private constructor I have an existing code implementing singleton pattern by having private constructor and returning object instance returning the object -
export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor() {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

I need to inject a dependency into this factory. And I changed my code to the following -
@Inject('MyService')
export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor(private myService : MyService) {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

Please suggest, how I can inject the dependency at object creation in the constructor?

A: Inject into your component.
import { Router } from  '@angular/router';
    import { FormBuilder, FormGroup, Validators} from '@angular/forms';
    import { Location } from '@angular/common';
    constructor(public location: Location,public fb:FormBuilder,public global_service:GlobalService,public router: Router) {

      }


text:
Q: Is stochastic ordering preserved under weak limit? Let $\mu, \nu$ be probability measures on a partially ordered measurable space $(\Omega, \mathcal{F})$. We say that $\mu\preceq\nu$ ($\nu$ stochastic ally dominates $\mu$) if for every increasing event $A$ we have $$\mu(A)\le \nu(A).$$
With this definition, I now have a sequence of probability measures $\mu_n$ converging weakly to $\mu$ and another sequence of probability measures $\nu_n$ converging weakly to $\nu$. If I know that $\mu_n \preceq \nu_n$ for each $n$. Can I say that $\mu\preceq \nu$?
I have a feeling that it should be true. But I am not able to prove it. The problem is that under weak limit $\mu_n(A)$ need not converge to $\mu(A)$ for every increasing $A.$ I believe there is an alternate definition of stochastic domination in terms of integrals of increasing functions instead of increasing events. And obviously we can get that $$\int fd\mu \le \int fd\nu,$$
for every bounded continuous increasing function $f.$ Using some density argument, I think we should be able to push the inequality for every bounded increasing function.


text:
Q: Realm Android query a list of primitives not working Two objects:
A parent and a child with a list of parent id.
Parent
open class Parent(
        @PrimaryKey
        open var id: Long? = null
) : RealmObject() {}

Child
open class Child(
        @PrimaryKey
        open var id: Long? = null,
        open var parentsId: RealmList<Long>? = null
) : RealmObject() {}

Can't find a way to obtain the list of child with a parent id.
I tried this because of this link:
realm.where(Child::class.java).equalTo("parentsId", idParent).findAll()

But it's not working, always getting this error:
java.lang.IllegalArgumentException: Invalid query: field 'parentsId' in class 'Child' is of invalid type 'INTEGER_LIST'.


text:
Q: ArrayIndexOutOfBounds after solving 'possible loss of precision' compile error works:meaning no precision error::Just array out of bounds
long a[] =new long[1000000];
int no=2,n;
long i;
a[no]=i+a[n];
if(a[no]>longChain)
{
    longChain = a[no];
    startNo = no;
}

and when I do
long a[] =new long[1000000];
long no=2,n;
long i,longChain=1,startNo;
a[no]=i+a[n];
if(a[no]>longChain)
{
    longChain = a[no];
    startNo = no;
}

then loss of precision
found:long
required: int
what is the problem?
My Code  for above problem, its ProjectEuler Problem No. 14
class P14
{
    public static void main(String args[])
    {
        long a[] =new long[1000000];
        long no=2,n;
        long i,longChain=1,startNo;
        a[1]=1;
        while(no<1000000)
        {
            n=no;
            i=0;
            while(n>no-1)
            {
                if(n%2==0)
                    n=n/2;
                else
                    n=3*n+1;
                i++;
                //System.out.println(n);
            }
            a[no]=i+a[n];
            if (a[no] > longChain)
            {
                longChain=a[no];
                startNo=no;
            }
            no++;
            //System.out.println(no);
        }
    }
}

This is my code for where above problem is occurring
Answer:: Replace a[no] by a[(int)n]
a[n],a[(int)n]

A: This is likely because array indexing takes an int as the index. But all your variables are of type long.
a[no]

no is a long.
So using long as an array index is an implicit downcast which could result in loss of precision.
So either you manually cast it down, or you change no to an int.
EDIT: (after additional info in the question)
I'm not 100% sure if this is the cause:
n=3*n+1;

You use n as in index. But n can get pretty large to begin with. So a *3 could make it larger than the size of the array.
You should probably double-check whatever your algorithm is. (which I can't figure out from the code itself)

A: The problem you have is that you cannot store all the possible values you are calculating in array.  Numbers can grow beyond 2^31-1 and you get an overflow.
What you can do is make
long n;

and
while (n > no - 1 || n >= a.length) {

}
// is safe as n < a.length;
a[no] = i + a[(int) n];

This ensures you only look up cached values which are inside your array.

A: your no and n variables need to be int, not long. Arrays can't be indexed by long. Changing the code to:
int no=2,n;

makes the code compile.
The ArrayIndexOutOfBoundsException is because you wrote the algorithm assuming it was longs.
This code will eventually cause n to become negative:
n=3*n+1;

It's hard to see why when you're doing integer arithmetic.  A slight change to make the code use long arithmetic and print the interim result reveals exactly when it becomes negative and how:
while(n>no-1)
{
    long newN = n;

    if (n % 2 == 0) newN = newN / 2L;
    else newN = 3L * newN + 1L;

    if (newN > Integer.MAX_VALUE) System.out.println("about to fail");

    //this is where the magic happens
    n = (int)newN;
    System.out.println("converted " + newN + " to " + n);

    i++;
}

A: n needs to be long because it may get too large for int. (If you use int it will overflow into negative numbers and cause the ArrayIndexOutOfBoundsException.)
You have to declare n as long and cast it to int when using it as index (no can be int)
a[no]=i+a[(int)n];


text:
Q: IONIC apk Generate Issue I have getting this error when I run ionic cordova build --release android
but yesterday it was running perfectly im not change anything about configuration only build distribution I think it is version issue but I unable to find how to resolve it please help
here is console log
FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all files for configuration ':app:releaseCompileClasspath'.
> Could not find any version that matches com.google.firebase:firebase-measurement-connector:[10.2.1,12.1.0[.
  Versions that do not match:
      17.0.0

      16.0.0
      15.0.0

  Required by:
      project :app > com.google.firebase:firebase-messaging:17.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or
--debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED
 in 41s
11 actionable tasks: 11 executed
(node:15826) UnhandledPromiseRejectionWarning: Error: /home/chamikara/Projects/freelance/ionic/beachlines/notifications/platforms/android/gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all files for configuration ':app:releaseCompileClasspath'.
> Could not find any version that matches com.google.firebase:firebase-measurement-connector:[10.2.1,12.1.0[.
  Versions that do not match:
      17.0.0
      16.0.0
      15.0.0
  Required by:
      project :app > com.google.firebase:firebase-messaging:17.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 41s
    at ChildProcess.whenDone (/home/chamikara/Projects/freelance/ionic/beachlines/notifications/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
    at emitTwo (events.js:126:13)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
(node:15826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15826) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

A: Related to this answer : https://stackoverflow.com/a/51779975/279326 I fixed by going back to ionic@4.0.3 npm i -g ionic@4.0.3


text:
Q: codeigniter query within foreach loop which will return a sigle array i am trying to access all the sub category under category but not working for me. Have written the code like that,
function getAllSubCategory($CatId)
    {
        $data=array();
        $this->db->select('c.catId,c.cat_name,c.cat_alias,c.cat_image,c.parentcatid,c.isHeading');
        $this->db->from('coupon_category as c');
        $this->db->where('c.parentcatid', $CatId);
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
            $data = $dataFetched = $query->result_array();
            $query->free_result();
            foreach ($dataFetched as $row) {
                $this->db->select('c.catId,c.cat_name,c.cat_alias,c.cat_image,c.parentcatid,c.isHeading');
                $this->db->from('coupon_category as c');
                $this->db->where('c.parentcatid', $dataFetched->catId);
                $data = $query->result_array();
                $query->free_result();
            }
        }
        echo count($data);
        return $data;

    }

But not working, don't know where i am wrong.

A: The problem is here
  $this->db->where('c.parentcatid', $dataFetched->catId);

Should be
 $this->db->where('c.parentcatid', $row ["catId"]);

A: The code has following issues:

*

*The inner loop assigns the new result set to the variable $data and thereby you
lose the previous values you had in $data;

*You repeat exactly the same query again in each iteration of that loop. You do not
use the $row variable in the loop;

*There is no support for deeper nested subcategories, which the data structure seems to
allow for.

If you want to fetch child categories, and their child categories, ... etc, you
should use recursion, and even if you would only have two levels of subcategories in your table, it will
still be good code.
Here is some code for making it work in the direction you were going,
using recursion, and using the function array_merge to append the data as you go.
function getAllSubCategory($CatId)
{
    $this->db->select('c.catId,c.cat_name,c.cat_alias,c.cat_image,c.parentcatid,c.isHeading');
    $this->db->from('coupon_category as c');
    $this->db->where('c.parentcatid', $CatId);
    $query = $this->db->get();
    $dataFetched = $query->result_array();
    $query->free_result();
    $data = array();
    foreach ($dataFetched as $row) {
        $data[] = $row;
        $data = array_merge($data, getAllSubCategory($row["catId"]));
    }
    echo count($data);
    return $data;
}

Alternative
You could get better performance by doing a
hierarchical query on the database (as for instance was asked for
here ),
but I don't know if it can be made to work with Active Record. So I will provide
the code using plain query() syntax, according to the answer I have given myself
to that particular question:
function getAllSubCategory($CatId)
{
    $CatId = $this->db->escape($CatId); // sanitise to prevent SQL injection
    $query = $this->db->query(
        "select c.catId,c.cat_name,c.cat_alias,c.cat_image,c.parentcatid,c.isHeading
         from   (select * from coupon_category
                 order by parentcatid, catId) as c,
                (select @pv := '$CatId') as initialisation
         where  find_in_set(c.parentcatid, @pv) > 0
         and    @pv := concat(@pv, ',', catId)");
    $data = $query->result_array();
    $query->free_result();
    echo count($data);
    return $data;
}

Note that the last solution requires that
for each record parentcatid < catid, otherwise the results will not be complete.
But if that is the case, this will certainly beat the first solution in performance, as it only executes one database query.
Also, if your table would have cycles where a child of a node is also its parent (for example), the first solution will keep looping and querying until some out-of-memory error occurs. The last solution will not, because it only looks for children for which parentcatid < catid.


text:
Q: Reading if button is hold I would like to increase the value of a variable constantly when a button is held down.
I'm using onClickListener but it only increase once when the button is click and released.
How do I determine if the button is being pressed and hold?
What I want is something like "while(ButtonIsBeingHold){count ++;}"
If there are any other methods please advice me on it

A: Instead of using View.onClickListener, you could try using View.onTouchListener:
public boolean onTouch(View v, MotionEvent event) {

}

This will get fired for different types of touch events such as:
MotionEvent.TOUCH_UP and MotionEvent.TOUCH_DOWN.
You could set a flag for when the butotn is pressed (TOUCH_DOWN) and start increasing your counter and stop on TOUCH_UP. I would, however, advise not to use a while(true) loop and try to throttle the incrementing events being trigger. In this case, I would use a handler and pass messages to it at a constant rate. You can see how a handler like this is used for rendering and updating a game in the Snake sample project that comes with the Android SDK:
http://developer.android.com/resources/samples/Snake/index.html