text:
Q: django forms: editing multiple sets of related objects in a single form I'm trying to do something that should be very common: add/edit a bunch of related models in a single form. For example:
Visitor Details:
Select destinations and activities:
    Miami  []   -  swimming [], clubbing [], sunbathing[]
    Cancun []   -  swimming [], clubbing [], sunbathing[]

My models are Visitor, Destination and Activity, with Visitor having a ManyToMany field into Destination through an intermediary model, VisitorDestination, which has the details of the activities to be done on the destination (in itself a ManyToMany field into Activity).
Visitor ---->(M2M though VisitorDestination) -------------> Destination
                                            |
                       activities            ---->(M2M)---> Activity

Note that I don't want to enter new destination / activity values, just choose from those available in the db (but that's a perfectly legit use of M2M fields right?)
To me this looks like an extremely common situation (a many to many relation with additional details which are a FK or M2M field into some other model), and this looks like the most sensible modelling, but please correct me if I'm wrong.
I've spent a few days searching Django docs / SO / googling but haven't been able to work out how to deal with this. I tried several approaches:

*

*Custom Model form for Visitor, where I add multiple choice fields for Destination and Activity. That works ok if Destination and Activity could be selected independently, but here they are correlated, ie I want to choose one or several activities for each destination

*Using inlineformset_factory to generate the set of destination / activities forms, with inlineformset_factory(Destination, Visitor). This breaks, because Visitor has a M2M relation to Destination, rather than a FK.

*Customizing a plain formset, using formset_factory, eg DestinationActivityFormSet = formset_factory(DestinationActivityForm, extra=2). But how to design DestinationActivityForm? I haven't explored this enough, but it doesn't look very promising: I don't want to type in the destination and a list of activities, I want a list of checkboxes with the labels set to the destination / activities I want to select, but the formset_factory would return a list of forms with identical labels.
I'm a complete newbie with django so maybe the solution is obvious, but I find that the documentation in this area is very weak - if anyone has some pointers to examples of use for forms / formsets that would be also helpful
thanks!

A: In the end I opted for processing multiple forms within the same view, a Visitor model form for the visitor details, then a list of custom forms for each of the destinations.
Processing multiple forms in the same view turned out to be simple enough (at least in this case, where there were no cross-field validation issues).
I'm still surprised there is no built-in support for many to many relationships with an intermediary model, and looking around in the web I found no direct reference to it. I'll post the code in case it helps anyone.
First the custom forms:
class VisitorForm(ModelForm):
    class Meta:
      model = Visitor
      exclude = ['destinations']

class VisitorDestinationForm(Form):
    visited = forms.BooleanField(required=False)
    activities = forms.MultipleChoiceField(choices = [(obj.pk, obj.name) for obj in Activity.objects.all()], required=False,
                                                      widget = CheckboxSelectMultipleInline(attrs={'style' : 'display:inline'}))

    def __init__(self, visitor, destination, visited,  *args, **kwargs):
        super(VisitorDestinationForm, self).__init__(*args, **kwargs)
        self.destination = destination
        self.fields['visited'].initial = visited
        self.fields['visited'].label= destination.destination

        # load initial choices for activities
        activities_initial = []
        try:
            visitorDestination_entry = VisitorDestination.objects.get(visitor=visitor, destination=destination)
            activities = visitorDestination_entry.activities.all()
            for activity in Activity.objects.all():
                if activity in activities:
                    activities_initial.append(activity.pk)
        except VisitorDestination.DoesNotExist:
            pass
        self.fields['activities'].initial = activities_initial

I customize each form by passing a Visitor and Destination objects (and a 'visited' flag which is calculated outside for convenience)
I use a boolean field to allow the user to select each destination. The field is called 'visited', however I set the label to the destination so it gets nicely displayed.
The activities get handled by the usual MultipleChoiceField (I used I customized widget to get the checkboxes to display on a table, pretty simple but can post it if somebody needs that)
Then the view code:
def edit_visitor(request, pk):
    visitor_obj = Visitor.objects.get(pk=pk)
    visitorDestinations = visitor_obj.destinations.all()
    if request.method == 'POST':
        visitorForm = VisitorForm(request.POST, instance=visitor_obj)

        # set up the visitor destination forms
        destinationForms = []
        for destination in Destination.objects.all():
            visited = destination in visitorDestinations
            destinationForms.append(VisitorDestinationForm(visitor_obj, destination, visited, request.POST, prefix=destination.destination))

        if visitorForm.is_valid() and all([form.is_valid() for form in destinationForms]):
            visitor_obj = visitorForm.save()
            # clear any existing entries,
            visitor_obj.destinations.clear()
            for form in destinationForms:
                if form.cleaned_data['visited']:
                    visitorDestination_entry = VisitorDestination(visitor = visitor_obj, destination=form.destination)
                    visitorDestination_entry.save()
                    for activity_pk in form.cleaned_data['activities']:
                        activity = Activity.objects.get(pk=activity_pk)
                        visitorDestination_entry.activities.add(activity)
                    print 'activities: %s' % visitorDestination_entry.activities.all()
                    visitorDestination_entry.save()

            success_url = reverse('visitor_detail', kwargs={'pk' : visitor_obj.pk})
            return HttpResponseRedirect(success_url)
    else:
        visitorForm = VisitorForm(instance=visitor_obj)
        # set up the visitor destination forms
        destinationForms = []
        for destination in Destination.objects.all():
            visited = destination in visitorDestinations
            destinationForms.append(VisitorDestinationForm(visitor_obj, destination, visited,  prefix=destination.destination))

    return render_to_response('testapp/edit_visitor.html', {'form': visitorForm, 'destinationForms' : destinationForms, 'visitor' : visitor_obj}, context_instance= RequestContext(request))

I simply collect my destination forms in a list and pass this list to my template, so that it can iterate over them and display them. It works well as long as you don't forget to pass a different prefix for each one in the constructor
I'll leave the question open for a few days in case some one has a cleaner method.
Thanks!

A: So, as you've seen, one of the things about inlineformset_factory is that it expects two models - a parent, and child, which has a foreign key relationship to the parent. How do you pass extra data on the fly to the form, for extra data in the intermediary model?
How I do this is by using curry:
from django.utils.functional import curry

from my_app.models import ParentModel, ChildModel, SomeOtherModel

def some_view(request, child_id, extra_object_id):
    instance = ChildModel.objects.get(pk=child_id)
    some_extra_model = SomeOtherModel.objects.get(pk=extra_object_id)

    MyFormset = inlineformset_factory(ParentModel, ChildModel, form=ChildModelForm)

    #This is where the object "some_extra_model" gets passed to each form via the
    #static method
    MyFormset.form = staticmethod(curry(ChildModelForm,
        some_extra_model=some_extra_model))

    formset = MyFormset(request.POST or None, request.FILES or None,
        queryset=SomeObject.objects.filter(something=something), instance=instance)

The form class "ChildModelForm" would need to have an init override that adds the "some_extra_model" object from the arguments:
def ChildModelForm(forms.ModelForm):
    class Meta:
        model = ChildModel

    def __init__(self, some_extra_model, *args, **kwargs):
        super(ChildModelForm, self).__init__(*args, **kwargs)
        #do something with "some_extra_model" here

Hope that helps get you on the right track.

A: From django 1.9, there is a support for passing custom parameters to formset forms :
https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms
Just add form_kwargs to your FormSet init like this :
from my_app.models import ParentModel, ChildModel, SomeOtherModel

def some_view(request, child_id, extra_object_id):
    instance = ChildModel.objects.get(pk=child_id)
    some_extra_model = SomeOtherModel.objects.get(pk=extra_object_id)

    MyFormset = inlineformset_factory(ParentModel, ChildModel, form=ChildModelForm)
    formset = MyFormset(request.POST or None, request.FILES or None,
        queryset=SomeObject.objects.filter(something=something), instance=instance,
        form_kwargs={"some_extra_model": some_extra_model})


text:
Q: extern "C" Vs. extern I am exporting functions from a static library as follows:
extern "C"
{
    __declspec(dllexport) HRESULT CreateGraphicsDevice(HINSTANCE hDLL,  IAMG3DGraphicsDevice **pInterface);
}

All my code is written in C++, so I don't see why I need to extern "C". For example, if I put:
extern __declspec(dllexport) HRESULT CreateGraphicsDevice(HINSTANCE hDLL,  IAMG3DGraphicsDevice ** pInterface)

the function is not accessible from the DLL. Why is extern "C" required if my code is written in c++ as opposed to putting extern directly before the function declaration?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there some data structure or database that can handle path expression statements and path expression queries? I need to model a graph (or could be seen as a recursive tree(s) since it typically as a single or small number of roots) based on things having children:
a hasChildren (b, c)
b hasChildren (d, e)
c hasChildren (f, g)
d hasChildren (h, a)

Now there are implicit paths, a/c/f and recursive ones as well: a/b/d/a/b/d/...
And then I need to set things on the graph via a path expression, both properties about them (these paths have color: blue, or such) and also changing their children--perhaps removing/hiding them, or adding new children.
By path expression, I mean something like this:
a/b/** -> color = "blue"

would mean that all paths that start with a/b/ have the property color = "blue". So, if I queried for the color of a/b/d/a/b/d/a, it would return blue. But if I queried for the color of just a, at this point there is none.
Other expressions might be:
**/d/h
a/b/[color="blue"]
a/**/h

So, that would be used to make statements. I need similar way of doing querying. I need simple queries such as:
a/b/d

and more complex ones like:
a/**[color="blue"]  -- descendants that have attribute color = "blue". This could be infinite in recursive case so we can put a restriction on this type of query to have it make sense, like does such a path exist, or just return first one or something.

Also, more nodes might be added at any time.
a hasChildren (b, c, x, y, z)
I need the queries after that to match appropriately all the statements. So in other words, I can't just run a query and set a property on all the results, since then it won't apply to new things added later.
And of course, I need it to be very fast :)  I would have on the order of 1000's of nodes, 1000's of path expression statements, and query on 100,000's of path expressions.
Is there something that handles this type of thing well?
I looked into RDF/OWL kind of thing but it doesn't seem to have any support for paths.

A: If I understand your question correctly, you are talking about querying against inferences made against object relationships.  If so, you need to take a look at RDF and SPARQL http://www.w3.org/TR/rdf-sparql-query/ and the whole field of semantic content.

A: On a similar problem, I ended up implementing my own Trie (in my case, in Java) with a Node class that contains Node children and is able to check if the leftover path matches it (which implies that all its ancestors green lighted their chunk of the path before it.
It's pretty fast and the code's quite compact. Hope it helps!

A: not sure if this is exactly what you need but to me it sounds like oracle's CONNECT BY and START WITH clauses.
for instance you could have a table called NODES with these columns:

*

*ID as primary key

*PARENT_ID pointing to ID of this same table

*COLOR ... and whatever else you need

and then make this kind of query
SELECT ID, PARENT_ID, COLOR FROM NODES START WITH PARENT_ID IS NULL CONNECT BY PRIOR ID = PARENT_ID
adding whatever clause you need i.e. WHERE COLOR='BLUE'
it also has a nocycle condition for your a/b/d/a/b/d example
here's more info
http://www.adp-gmbh.ch/ora/sql/connect_by.html

A: From what i understand of the question you want to model a tree that can support recursive.
I can answer from sql table design point of view. There are 2 ways to do this
1) use an adjaceny model where you will store the key in one column and the child in the other
Parent Child
Null   A
A      B
A      C
B      D
B      E

2) You can use a Left Hand Value and Right Hand Value as defined as a Nested Set Model and this has good performance. Read this article from the SQL guru Joe Celko and it will give you more hints
http://en.wikipedia.org/wiki/Nested_set_model

A: Graph model is quite different from the relational model, I thing you should use some NoSQL db.
Finding nodes by partial paths is implemented in MongoDB, only for trees, but should by easy to write graph implementation on application layer: http://www.mongodb.org/display/DOCS/Trees+in+MongoDB
There are few graph-oriented DBs:

*

*Neo4J: Open source database NoSQL graph.

*Dex: The high performance graph database.

*HyperGraphDB

*InfoGRID - The Internet graph database
Also recommend that you read this article: Querying RDF Data from a Graph Database
Perspective, especially chapter 3.2 about graph query language

A: I am really not sure about any pre-made stuff to handle this kind of problem, but if I was going to model a tree structure I would probably just create a set of c# classes (or some other object oriented language). The general idea is you set up a class for a node, then a class for the graph itself with functions to add nodes, remove nodes, find specific paths, etc (set the "colour" of paths). You could then even save matrices representing different graph structures and paths to a DB if that is what you are looking for.
It is hard for me to get specific when your question does not really specify what sort of approach you wanna take. Are you looking for something pre-made to do this? If not, check out this set of tutorials about creating graphs in c# (same concepts could apply to any OO language though). http://msdn.microsoft.com/en-us/library/ms379574.aspx


text:
Q: Update AWS Elastic Beanstalk solution stack name I have a Cloudformation template with the following Elastic Beanstalk environment:
Resources:
  BeanstalkEnvironment1:
    Type: AWS::ElasticBeanstalk::Environment
    Properties:
      ApplicationName: Application1
      Description: ignored
      EnvironmentName: Environment1'
      SolutionStackName: '64bit Amazon Linux 2017.03 v2.5.0 running Python 3.4'

My main goal is to update the environment's Python version from 3.4 to 3.6. I was able to update the solution stack name with the following command (taken from this answer)
aws elasticbeanstalk update-environment --solution-stack-name "64bit Amazon Linux 2018.03 v2.7.6 running Python 3.6" --environment-name "Environment1"

However, I cannot do subsequent updates using the existing template if I update it to the new solution stack name, because I get "Cannot update a stack when a custom-named resource requires replacing". It works if I keep the original one, but I would like to keep the running platform in sync with the template.
Any ideas?
Thanks!

A: I get the same problem.  This appears to be a limitation of Elastic Beanstalk and CloudFormation.  In the docs (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html) an update to SolutionStackName shows as Update requires: Replacement.
If you just change the EnvironmentName every time you change SolutionStackName it should work fine.

A: Check the documentation note of SolutionStackName:

Note: If you specify SolutionStackName, don't specify PlatformArn or
TemplateName.


text:
Q: Static data reuse I'm going to describe the situation first and ask questions in the end.
I need to validate a scalar value using the Symfony Validator component. The value is an associative array. Now I have defined the following validation constraints according to the expected structure:
new Constraints\Collection([
            'Call' => new Constraints\NotBlank(),
            'Start Time' => new Constraints\DateTime(['format' => 'd M Y H:i:s']),
            'Caller ID' => new Nullable(),
            'Calling Party Number' => new Nullable(new Phone()),
            'Dialed Party Number' => new Nullable(new Phone()),
            'Call Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
            'Receiving Agent' => new Nullable(),
            'Is Abandoned' => new Constraints\Regex(['pattern' => '/^(True|False)$/']),
            'Total Queue Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
            'Account Code' => new Nullable(),
            'Initial Tag' => new Constraints\NotBlank(),
        ]);

where Nullable and Phone are custom constraints.
These constraints must be reusable, and to achieve this I've created the following validation service:
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class Validator
{
    private $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    public function validate($value, ConstraintsProvider $constraintsProvider): ConstraintViolationListInterface
    {
        $violations = $this->validator->validate($value, $constraintsProvider->getConstraints());
        return $violations;
    }
}

And defined the ConstraintsProvider interface:
interface ConstraintsProvider
{
    public function getConstraints(): array;
}

which is going to be implemented by newables, encapsulating validation constraints like this:
class Call implements ConstraintsProvider
{
    public function getConstraints(): array
    {
        return [
            new Constraints\Collection([
                'Call' => new Constraints\NotBlank(),
                'Start Time' => new Constraints\DateTime(['format' => 'd M Y H:i:s']),
                'Caller ID' => new Nullable(),
                'Calling Party Number' => new Nullable(new Phone()),
                'Dialed Party Number' => new Nullable(new Phone()),
                'Call Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
                'Receiving Agent' => new Nullable(),
                'Is Abandoned' => new Constraints\Regex(['pattern' => '/^(True|False)$/']),
                'Total Queue Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
                'Account Code' => new Nullable(),
                'Initial Tag' => new Constraints\NotBlank(),
            ])
        ];
    }
}

And the validation is carried out as
$validator=new Validator();
$validator->validate(['foo'=>'bar'],new Call());

What I was wondering is:

*

*Is it a common practice to add an extra abstraction level in order to encapsulate some data which need to be reusable throughout the app? I my case it's the validation constraints.

*If it's common, are there any patterns addressing this issue?

*Is there any better way to resolve the problem I faced?

Update
The Call class is not an entity, it's just a wrapper around the constraints from where the validation service takes them. The validation service is used to validate the data before filling an entity with them. The corresponding entity has its own validation defined in its config.

A: If the constraints are used by the validator, then they should be a static field on the Validator class itself. Furthermore, the validator class is too generic to be of any use. It should specialize in validating a Call. You can use it in a generic sense by defining an interface for validators:
interface Validator
{
    function validate($value) : ConstraintViolationListInterface
}

And then your CallValidator can implement the Validator interface and own the constraints:
class CallValidator implements Validator
{
    private $validator;

    private static $constraints = new Constraints\Collection([
        'Call' => new Constraints\NotBlank(),
        'Start Time' => new Constraints\DateTime(['format' => 'd M Y H:i:s']),
        'Caller ID' => new Nullable(),
        'Calling Party Number' => new Nullable(new Phone()),
        'Dialed Party Number' => new Nullable(new Phone()),
        'Call Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
        'Receiving Agent' => new Nullable(),
        'Is Abandoned' => new Constraints\Regex(['pattern' => '/^(True|False)$/']),
        'Total Queue Duration' => new Constraints\Regex(['pattern' => '/^\d{1,2}:\d{1,2}:\d{1,2}$/']),
        'Account Code' => new Nullable(),
        'Initial Tag' => new Constraints\NotBlank(),
    ]);

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    public function validate($value): ConstraintViolationListInterface
    {
        $violations = $this->validator->validate($value, self::$constraints);
        return $violations;
    }
}

Now the validator owns the constraints that it checks, they are static (so only 1 copy is held in memory), and nobody else can access those constraints without going through the validator.


text:
Q: Start an Activity in full cycle with out showing UI I have activityB with UI which is working fine as a regular activity with showing UI upon calling from another activityA. Now, I want to call activityB and let the activity complete the entire activity cycle without showing its UI.
So far I had tried:

*

*Set theme in Manifest:
android:theme = "@android:style/Theme.Translucent.NoTitleBar" />

But the problem is I need to setContentView() in ActivityB so that UI element can be recognized in the ActivityB. This ran into error.

*Put finish() in activityB onCreate()
The activityB did not complete the full activity cycle. It end at finish().

Any thought about how I can achieve starting an Activity in full cycle without showing its UI.
Thank you

A: I would suggest you pass some boolean through intent if UI should be shown or not:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean isShowUI = getIntent().getBooleanExtra(EXTRA_IS_SHOW_UI, true);

    if (isShowUI) {
        setContentView(R.layout.activity_layout);
    }

    //your onCreate logic
}


text:
Q: Test Kerberos Authentication without throwing exception I'm using an HDFS keytab to perform certain superuser operations on an API call. The keytabs change roughly every 6 months, sometimes more frequently if a breach occurs. Whenever this happens, my application needs to fetch the latest keytabs from a remote host over SSH.
For performance reasons, on each API call, I would like to determine if the existing keytab is still valid and current. (If not, there's no need to fetch it.) One way to do is to try using the keytab, and if an exception is thrown, fetch the new keytab. However, I don't like this approach because I understand that using exception handling to control flow is an anti-pattern.
Ideally, I would query some sort of API to check the current keytab's validity, and only fetch the latest keytab if necessary. Do the UserGroupInformation Java APIs provide a way to do this?


text:
Q: Analyze the continuity of the following function Here in my book I have such an exercise with the explanation given below, but still there is something the authors didn't add, but simply put "...after some operations...". Here is such an exercise:
Analyze the continuity of the following function:

$$f:\Bbb R^2\to\Bbb R $$    $$ f(x,y)= \begin{cases}
\frac{3x^2y}{\sqrt{x^4+y^2}}& \text{if } (x,y)\neq(0,0)\\[2ex]
0& \text{if }   (x,y)=(0,0)
\end{cases}$$
In my book is writen, after some operations, we find that  $f$ is continuous on $\Bbb R^2 \setminus\{(0,0)\}$. What are these operation ? Thanks.

A: if $|y|\leq 1$, $$\sqrt{x^4+y^2}\geq \sqrt{x^4+y^4}$$
and thus
$$|f(x,y)|=\left|\frac{3x^2y}{\sqrt{x^4+y^2}}\right|\leq\underbrace{\left|\frac{x^2}{\sqrt{x^4+y^4}}\right|}_{\leq 1}|3y|\leq |3y|\underset{(x,y)\to(0,0)}{\longrightarrow 0}$$
therefore $f$ is continuous on $\mathbb R^2$.
Justification for $\left|\frac{x^2}{\sqrt{x^4+y^4}}\right|\leq 1$:
$$x^4\leq x^4+y^4\implies x^2\leq\sqrt{x^4+y^4}\implies \underbrace{\frac{x^2}{\sqrt{x^4+y^4}}}_{=\left|\frac{x^2}{\sqrt{x^4+y^4}}\right|}\leq 1.$$


text:
Q: Can't upload file to Apache 2.2 Apache/2.2.15 (Win32) PHP/5.3.2
I'm trying to upload a file to Apache and my PHP script tells me everything goes well (status code 0), but the file is not in the temp directory. The PHP answer is always coming immediately, regardless of the file size. The PHP Error log doesn't show any errors at all.
The Apache server is running on its own user account with full access to the log and doc folders.
PHP.ini
file_uploads = On
upload_tmp_dir =
upload_max_filesize = 10M
upload_tmp_dir="C:\WINDOWS\Temp"

send.html
<!DOCTYPE html>
<html>
  <body>

  <form enctype="multipart/form-data" action="upload.php" method="post" >
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
  </form>

  </body>
</html>

upload.php
<?php
  // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
  // of $_FILES.

  echo '<pre>';
  print_r($_FILES);
  echo '</pre>';
?>

The result look like this
Array
(
    [userfile] => Array
        (
            [name] => strings.lua
            [type] => application/octet-stream
            [tmp_name] => C:\WINDOWS\Temp\phpC0.tmp
            [error] => 0
            [size] => 9935
        )

)

The file C:\WINDOWS\Temp\phpC0.tmp doesn't exists.
Are there any other considerations/configurations that I have missed out?
The Apache server has been running with PHP for over 5 years and works fine in all other aspects. I can't upgrade Apache or PHP to a newer version because this is an application in production and the customer won't risk to an upgrade.

A: The temporary file only exists until the end of your PHP script upload.php. It's truly temporary.
You should move the file right away using move_uploaded_file:
http://www.php.net/move_uploaded_file
Something like:
$savePath = "path/where/you/really/wantit/" . $_FILES['userfile']['name'];

move_uploaded_file($_FILES['userfile']['tmp_name'], $savePath);

From this link:
http://us3.php.net/manual/en/features.file-upload.post-method.php

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.


text:
Q: javadoc fail when using jdk12 to build language-level 9 javadoc I'm using jdk 12 to build a maven project of language level 9.
The compile can succeed but it cannot generate javadoc correctly.
In short the error code is:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.1.0:jar (default) on project commonx: MavenReportException: Error while generating Javadoc:
[ERROR] Exit code: 1 - javadoc: error - The code being documented uses modules but the packages defined in https://docs.oracle.com/javase/9/docs/api/ are in the unnamed module.

code is at https://github.com/XenoAmess/commonx/tree/3d875ee71ba1712b1b2bf76e89af08c5683fe57d
travis-ci is at https://travis-ci.org/XenoAmess/commonx/builds/540181778
I can do this with jdk9 or 10, but NO jdk 12 can I found which can build this javadoc right.
I tried zulu, oracle open jdk, adopt open jdk, amazon-corretto(11), all of them are the latest binary version I can get.
Win10 x64 I use but according to travis-ci's report it shall not be caused by system because I use linux x64 on travis.
If any guys can get it "maven install" using any jdk 12, please tell me what shall I do.
Thanks sincerely.

update: 2019/06/03
We change language level to 8.
Then it can build the javadoc correctly(on AdoptOpenJDK12)
Don't know why.
https://travis-ci.org/XenoAmess/commonx/builds/540461237
Well then.
We will stay on language level 8 before they fix the bug in OpenJDK.
(But some part of this library shall not be able to run on jre 8...well anyway.)

A: UPDATE FOR THOSE WHO GOOGLED THIS BUG:
If the project uses source/target 8, adding 8 in javadoc configuration should make the project build able on jdk {11, 12, 13}:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <configuration>
      <source>8</source>
    </configuration>
     ...
  </plugin>

A: You can add following line in configuration of maven-javadoc-plugin
<detectJavaApiLink>false</detectJavaApiLink>


text:
Q: VMWare guest OS as bridge gives BSOD in host (bridge.sys) I'm using Windows 8 x64 with a Ubuntu 12.04 x64 guest in VMWare. I'm trying to use the guest network as bridged but it always gives me a BSOD:
DRIVER_IRQL_NOT_LESS_OR_EQUAL (bridge.sys)
I already disabled Hyper-V on Windows 8 (programs and features) and installed VMWare tools in guest OS. What else do I need to do?


text:
Q: How can I update diskless installation 11.04 to 11.10 Bonjour messieurs,
we have installed on our Ubuntu server 64bit in directory /MNT the distribution of Ubuntu 11.04 32 bit as shared drive for PXE diskless computers in school.

*

*Can we upgrade to 11.10? How?

*Can we use NFS 4.0? Is it recommended?

*Can we use Ubuntu software center and install packages with the GUI?

*Is possible to use 1 Gbit connection between NFS PXE server and diskless computers?

I'm not Linux expert, but I hope it is possible. Our admin said, do not use GUI packager in 11.04, there is some NFS LOCKING problem. I hope that 11.10 is the general solution.
In the fact, we have HDDs in all computers and we are using them for swapping only. The idea is to have only one installation for all computers in the school for easier servicing.

A: This sounds like an upgrade that should not be done blindly - if you break that install then no computer in your school will be able to boot!
I don't see any reason 11.10 wouldn't work where 11.04 did for a PXE/NFS server setup. I would try doing a fresh install into a new directory and exporting that to a couple of clients first to check compatibility.
If it works, it sounds like you would want to chroot into /mnt and use do-release-upgrade to update it. But it's quite difficult to answer this properly without full technical details.
To point 2) I'm aware of no problems with NFS4 for this kind of setup, it is the currently accepted de-facto standard.
To point 4) 1Gb is no problem for an PXE/NFS server so long as your hardware supports it.


text:
Q: How do I properly declare global variable? ALL,
Consider this piece of code:
our $classwork = 0;
while( <INFILE> )
{
    chomp;
    next if $. == 1;
    if( $year >= 1992 && $year <= 1995 )
    {
        $classwork = (split( /,/ ))[6];
        print "Classwork is: ", $classwork, "\n";
    }
    if( $year >= 1996 && $year <= 2001 )
    {
        $classwork = (split( /,/ ))[-1];
    }
    print "Classwork is: ", $classwork, "\n";
    if( $year == 2002 )
    {
        $classwork = (split( /,/ ))[-2];
    }
    if( $year == 2003 || $year == 2004 )
    {
        $classwork = (split( /,/ ))[23];
    }
    if( $year >= 2005 && $year <= 2009 )
    {
        $classwork = (split( /,/ ))[22];
    }
    if( $year >= 2010 && $year <= 2012 )
    {
        $classwork = (split( /,/ ))[20];
    }
    print "Classwork is: ", $classwork, "\n";
    $line = <STDIN>;
}

The last print statement does not want to print the variable. Even if I declare it as 'our' or just comment the declaration out.
What's more weird is that it happens only on the first iteration. The file has couple of thousand records and on the first iteration only the variable is undefined. All subsequent calls are good.
Any idea what is going on?
Thank you.

A: You haven't provided enough information for us to replicate the problem for ourselves, but the most likely case is that the first line of the file does not contain properly-formatted data for whatever $year you're dealing with.  Perhaps the first line is a header?
Another possibility is that $year may not be set on the first pass through the while loop, so you never enter any of the if blocks which set $classwork and then it gets set at a later point in the loop.  Since you don't show where or how $year is set, we can't say whether this could be the issue or not.
To get the best possible answers, it's generally best to provide complete, runnable example code which demonstrates your issue with as little additional code as possible.  (In my experience, such examples are usually no more than 15-20 lines.)  Another benefit of doing this is that you will often discover the problem for yourself while in the process of finding the smallest possible program which demonstrates it.
Also, there is no evident reason why $classwork needs to be global.  Changing our to my in its current declaration should not affect any of the code you've shown and I would definitely consider moving my $classwork to be inside the while loop, unless there's some intended condition under which it shouldn't be reassigned on every pass and should instead retain its value from one iteration to the next.


text:
Q: XMLHttpRequest: How do I pass 'POST' parameters safely (username, password)? I have this code:
function RequestLogin()
  {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
          if (this.readyState == 4)
          {
              alert(this.responseURL);
          }
      };

      request.open('POST', 'http://myserver/login');
      request.setRequestHeader('Content-type', 'multipart/form-data');
      request.send('user=myUsername&password=myPassword');
    }

Is this considered "safe" If I use HTTPS instead of http://myserver/login?
What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there? Am I appending them in the URL, therefore they're visible if someone sniffs the request? I used to create Form Object and pass it there, but it's not working in this case.
It's the only way I found to pass parameters to POST request, but am I not exposing the parameters anyway by doing 'user=myUsername&password=myPassword'?
Thanks

A: If you POST to an HTTPS endpoint, yes, that'll be safe.

What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there?

You are sending that string as the request body., and you're sending it to the URL specified, request.open('POST', 'http://myserver/login');.
With HTTPS, both the path (/login) and request body are encrypted; snoopers will not be able to see the actual contents of either of them.

Am I appending them in the URL, therefore they're visible if someone sniffs the request?

No, they're not appended in the URL - if that was being done, the code would instead look something like
request.open('POST', 'http://myserver/login?foo=bar&baz=buzz');

Which would be quite strange for a POST - but if it was over HTTPS, it's still be safe, because all snoopers would be able to see is that you and https://myserver are having a conversation. They wouldn't be able to see which endpoint on myserver you're talking to (so, the /login? and everything that follows would be private), and they wouldn't be able to see the contents of the request either.
That said, it'd be better to .send the data as you're doing now
request.send(sensitiveInfo)

than to append the info to the URL because URLs are sometimes stored in the server logs. It's nowhere near as vulnerable as allowing any observer to see what's going on, but it's still not a good idea.
You also might consider whether you could use fetch instead of XMLHttpRequest - fetch is considered the more modern way of making requests. It uses Promises, is arguably more intuitive, and has been generally supported by browsers since 2015.


text:
Q: Call not thread-safe DLL function from Java's multi threads in parallel Although my C++ program is obviously NOT thread-safe, I need to call it from Java's multiple threads in parallel. I can not rewrite C++ code and need to execute DLL created by compiling the C++ program in parallel due to performance issue.
How do I call not thread safe C++ function from Java's multi-threads?
What I've tried is using JNA and call Native#loadLibrary every time when a thread calls DLL function. But, it does not solve the problem and occurs the segmentation fault.
public static class MyRunnable implements Runnable{
  ...
  public void run(){
    MyCLibrary INSTANCE = (MyCLibrary)Native.loadLibrary(MyCLibrary.JNA_LIBRARY_NAME, MyCLibrary.class);
    INSTANCE.cfunc()
  }
  ...
}

I thought that new memory space for DLL is allocated by calling Native#loadLibrary and reentrant issue should be avoided. But, my thought might be fault.
I searched correct way to create multiple memory space for DLL from Java, but could not find it.

A:
How do I call not thread safe C++ function from Java's multi-threads?

You can't.  You can't do it because the C++ function is not thread-safe1.

I searched correct way to create multiple memory space for DLL from Java, but could not find it.

There isn't a way to do that.  (AFAIK)
Your options are:

*

*Restrict calls to the C++ function to a single Java thread ... or one thread at a time.  (Not acceptable, and in the latter case, possibly unsafe.)

*Launch multiple child processes to (each) run a C++ application that calls the function.  Pass the arguments and results via the process pipes or using network messages, RPC, etcetera.  (Problem is that the Java app <--> C++ app information passing could be a performance bottleneck.)

*Rewrite the C++ code to make it thread-safe.
The last approach will give you the best performance.

1 - This possibly overstates the case.  It may depend on why the C++ function is not thread-safe.  But if the issue is ... as I suspect ... that the function use static variable to hold state, then the situation is as I state.


text: Q: Exsitence of bounded, non-periodic, infinite recurrence relation Does there exist an infinite sequence $a_1,a_2,\ldots,a_n,\ldots$ of real numbers which is bounded, not periodic, and satisfies the recursion $a_{n+1}=a_na_{n-1}+1$?


text:
Q: IndexedBD and localStorage undefined error I have an indexedDB which im trying to use to capture form information on user registration. That part is working fine but the prof wants an account to be create once with the username and password set on creation so he can log in.
The way I approached this was with a localStorage API. I created a function to check if the admin account had ever been created, and if not to create it calling the addAdmin() function.
I tried to create addAdmin() by copying my addObject() but for some reason my db variable is returning as undefined in the console.
Error" Uncaught TypeError: Cannot call method 'transaction' of undefined
var mainForm, fName, lName, uName, pass, email, dob, phone, bio, nl, terms, school, gender, save, reset, db;

//-------------USER DB------------------//
function startDB(){
    mainForm = document.getElementById('mainFormSidebar');
    fname = document.getElementById('fName');
    lName = document.getElementById('lName');
    users = document.getElementById('uName');
    pass = document.getElementById('password');
    email = document.getElementById('email');
    dob = document.getElementById('dob');
    phone = document.getElementById('phone');
    bio = document.getElementById('bio');
    nl = document.getElementById('newsletter');
    terms = document.getElementById('terms');
    school = document.getElementById('school');
    gender = document.getElementsByName('gender');
    save = document.getElementById('save');
    reset = document.getElementById('reset');
    reset.addEventListener('click',clearForm);
    databox = document.getElementById('databox');

    mainForm.addEventListener('submit',addObject);

    //open DB
    var request = indexedDB.open('macroPlay');
    //if fails
    request.addEventListener('error', showerror);
    //if succeeds
    request.addEventListener('success', start);
    //if !exist, create.
    request.addEventListener('upgradeneeded', createdb);

    //Create Admin account on launch
    chkAdmin();
}
function createdb(e){
    var datababase = e.target.result;
    var myusers = datababase.createObjectStore('users', {keyPath: 'userName'});
}
function start(e){
    db = e.target.result;

showUsers();// Show all values in the object store
}

function addObject(){
    if(confirm('Are you sure you want to resgister?')){
        var fName = document.getElementById('fName').value;
        var lName = document.getElementById('lName').value;
        var userName = document.getElementById('uName').value;
        var pass = document.getElementById('password').value;
        var email = document.getElementById('email').value;
        var dob = document.getElementById('dob').value;
        var phone = document.getElementById('phone').value;
        var bio = document.getElementById('bio').value;
        var nl = document.getElementById('nl').value;
        var terms = document.getElementById('terms').value;
        var school = document.getElementById('school').value;

        //May need to set a loop to find value of radio
        var gender;
        var radios = document.getElementsByName('gender');

        for (var i = 0, length = radios.length; i < length; i++) {
            if (radios[i].checked) {
                gender=radios[i].value;
            }
        }

        //set up transaction
        var mytransaction = db.transaction(['users'], "readwrite");

        //get object store
        var myusers = mytransaction.objectStore('users');

        //Add item
        var request = myusers.add(new getUser(userName,fName,lName,pass,email,dob,phone,bio,nl,terms,school,gender));
    }

    // Show all results.
    mytransaction.addEventListener('complete', showUsers);

    //Reset Form Fields
    resetForm();

}
function getUser(userName, fn, ln, pw, em, dob, tel, bio, nl,tm, scl, gender){
    this.userName = userName;
    this.fn = fn;
    this.ln = ln;
    this.pw = pw;
    this.em = em;
    this.dob = dob;
    this.tel = tel;
    this.bio = bio;
    this.nl = nl;
    this.tm = tm;
    this.scl = scl;
    this.gender = gender;
}
//------Create Admin Account-----//
function chkAdmin(){
    alert('before adding admin');
     if(localStorage.getItem('admin')!="added"){
        alert('adding admin');
        addAdmin();
        alert('admin added');
    }
}
function addAdmin(){
    //set up transaction
        var mytransaction = db.transaction(['users'], "readwrite");
    //get object store
        var myusers = mytransaction.objectStore('users');
        var request = myusers.add(new getUser('admin','Shawn','Smith-Choa','admin'));
        request.addEventListener('success',showUsers);
    //Locally store that admin as been created
        var admin = 'admin';
        var value = 'added';
        newItem(admin,value);
}

//-------------Web Storage API------------//
function newItem(id,style){
    localStorage.setItem(id,style);
}

A: You're not assigning the value of db to anything so it's always undefined. I think you mean to be doing it in the createdb method, but really you should be capturing/assigning it in the start method which the success handler will trigger (I also can't find the start method anywhere)


text:
Q: How to figure out which resource to enter in Google Cloud Policy troubleshooter? I'd like to give a colleague permission via IAM on a Google Cloud Monitoring resource. He send me the error message
Error loading /monitoring/alerting/incidents/[incident id]?project=[project]

and the roles that are necessary to proceed from the error message:
monitoring.incidents.get
stackdriver.projects.get

I assume that I can use Policy troubleshooter in order to list the required role I need to assign in IAM, but maybe that's a misunderstanding.
Assuming that can use the troubleshooter, I entered my colleagues e-mail address which is used for Google Cloud login as well as one pair with Permission monitoring.incidents.get. I tried the following for Resource:
/monitoring/alerting/incidents/[incident id]
/monitoring/alerting/incidents/[incident id]?project=[project]
//monitoring/alerting/incidents/[incident id]
//monitoring/alerting/incidents/[incident id]?project=[project]
//monitoring/alerting/incidents
//monitoring.googleapis.com/alerting/incidents/[incident id]
//monitoring.googleapis.com/alerting/incidents/[incident id]?project=[project]
//monitoring.googleapis.com/alerting/incidents

The UI doesn't provide any support in filling out this field nor any feedback in the error message. As far as I understand the docs the full form with monitoring.googleapis.com is expected.
I don't have logging turned on, so I cannot use the Log explorer as suggested.


text:
Q: Writing a list to a csv file in Python I am in Python and have a list of numbers that I want to write to a csv file. Say, my list is: [1 2 3 4 5 6 7 8 9], and within the csv file to which I am exporting this data, I want to begin a new line every three numbers. Meaning, when I open my output file in Excel, I want it to look like
this.
So, I essentially want to take a 9 element list and write it into a 3x3 matrix. I'm sure I must end up using the writerows command, but have not been able to find documentation of a problem similar enough to mine, so I am not sure exactly what to do with it.
Any help would be greatly appreciated, and I'm sorry if this question has already been asked at some point.

A: slice your list into a 2D list using a comprehension, and pass that to csv.writerows.
Self-contained example:
import csv

lst = list(range(1,10))

with open("out.csv","w",newline="") as f:
    cw = csv.writer(f)
    cw.writerows(lst[i:i+3] for i in range(0,len(lst),3))

creates a csv file like this:
1,2,3
4,5,6
7,8,9

A: You can use reshape:
import numpy
my_array=numpy.reshape(my_list, (3,3))

BTW, it should be  [1, 2, 3, 4, 5, 6, 7, 8, 9], not [1 2 3 4 5 6 7 8 9]


text:
Q: Find largest sum of consecutive integers in array using 2 threads I want to find the largest sum of consecutive integers in an array using 2 threads.
It is quite simple with a single thread
int maxSum = Integer.MIN_VALUE;
    public static void main(String[] args) {
        MaxSumSubArray maxSumSubArray = new MaxSumSubArray();
        maxSumSubArray.maxSum(new int[]{1, 2, 3, -12, 7, 9,3} , 0);
        System.out.println(maxSumSubArray.maxSum);
    }

    public int maxSum(int[] nums, int index){
        int maxSumForCurrentIndex = 0;
        if (index == nums.length - 1)
            maxSumForCurrentIndex = nums[index];
        else
            maxSumForCurrentIndex = Math.max(nums[index], nums[index] + maxSum(nums, index + 1));
        maxSum = Math.max(maxSum, maxSumForCurrentIndex);
        return maxSumForCurrentIndex;
    }

I can create two threads one with an even index and one with an odd index, then store the results in the MaxHeap and get the first element.
Is there a better approach to do this?
I have tried to do the code. Something like this. But it didn't give me the correct answer.
public static void main(String[] args) throws InterruptedException {
        MaxSumSubArray maxSumSubArray = new MaxSumSubArray();
        int[] nums = {1, 2, 3, -12, 7, 9, 3};
        int[] answer = new int[nums.length];
        for(int i = 0;i<answer.length; i = i+1){
            MaxSum m1=new MaxSum(nums, 0);
            m1.start();
            m1.join();
            answer[i] = m1.answer;
        }

        for(int i = 1;i<answer.length; i = i+2){
            MaxSum m2=new MaxSum(nums, i);
            m2.start();
            m2.join();
            answer[i] = m2.answer;
        }
        System.out.println(Arrays.toString(answer));
        System.out.println(Arrays.stream(answer).max().getAsInt());
    }

class MaxSum extends Thread{
    int[] nums;
    int index;
    int answer;

    MaxSum(int[] nums, int index){
        this.nums = nums;
        this.index = index;
        this.answer = Integer.MIN_VALUE;
    }
    @Override
    public void run() {
        int maxSumForCurrentIndex = 0;
        if(index == nums.length - 1){
            maxSumForCurrentIndex = nums[index];
        } else {
            MaxSum m1 = new MaxSum(nums, index + 1);
            m1.start();
            try {
                m1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            answer = Math.max(nums[index], nums[index] + m1.answer);
            maxSumForCurrentIndex = answer;
        }

    }
}

A: You can have one thread go from left to right while the other one from right to left. The threads break when they pass the middle of the array and find a negative number. Then you take max from both the results.
In the worst case both threads will browse the entire array, so you won't get any speedup. On the other hand, if a large percentage of numbers is negative this should give you up to 2x speedup (assuming the array is large enough, that it makes sense to run two separate threads).


text:
Q: Python: returning the next greatest integer from a list when variable is in the list I'm writing a program to filter through coordinates and determine whether or not the coordinate is a safe position based on random data and changing data. If the y-position is already in the list, I am currently incrementing by one and moving to the next position.
I was wondering for example you have:
a = [1,3,5,6,2]
y = 2

Is there a way to return the next largest integer not in the list. For example in the above it would return 4. If so would this prove to be faster than incrementing by one each time. Any help is appreciated.

A: If you sort the list, you can use a binary search to get the answer quickly. The bisect_right function will return the index of the number you seek, or len(a) if the number is >= the largest in the list.
>>> a.sort()
>>> a
[1, 2, 3, 5, 6]
>>> import bisect
>>> bisect.bisect_right(a, 2)
2
>>> bisect.bisect_right(a, 4)
3
>>> bisect.bisect_right(a, 7)
5


text:
Q: Is it possible to store more than 100 MB in the browser between sessions? How much data can we keep in the browser, so that we can have access to the files again after closing / reopening the browser?
LocalStorage seems to allow ~ 5 or 10 MB (depending on the browser).
Other systems might be available (such as IndexedDB), as detailed here, but it seems quite complex.
Question: is there a simple-to-use technique (working at least for Chrome+Firefox, or even better if totally cross-browser, and both mobile and desktop) allowing to store more than 100MB (up to 500MB)?
Use-case: a website allowing to play piano with high quality samples (let's say 150 MB audio samples), and prevent to have to re-download the data each time we open the page.
PS: I'm preferably looking for a solution not requiring to install an extension or a browser plugin.

A: Yes!
As mentioned in the comments as well IndexedDB is the way to go. PouchDB has a nice FAQ about the storage limits between different browsers.

Though Firefox has no upper limit besides disk space, if your application wishes to store more than 50MB locally [In IndexedDB], Firefox will ask the user using a non-modal dialog to confirm that this is okay.
Android works the same as Chrome as of 4.4+ (IndexedDB), while older versions can store up to 200MB (WebSQL).

And from the Chrome webpage.

Temporary storage is shared among all web apps running in the browser.{#It is also shared across all offline APIs, such as App Cache, IndexedDB, and File System. However, it does not include web storage APIs like Local Storage and Session Storage, which still has a limit of 5 MB per origin.#} The shared pool can be up to 1/3 of the of available disk space. Storage already used by apps is included in the calculation of the shared pool; that is to say, the calculation is based on (available storage space + storage being used by apps) * .333 .
Each app can have up to 20% of the shared pool. As an example, if the total available disk space is 60 GB, the shared pool is 20 GB, and the app can have up to 4 GB. This is calculated from 20% (up to 4 GB) of 1/3 (up to 20 GB) of the available disk space (60 GB).


text:
Q: Selenium Chrome driver Print to PDF, can't change the paper size with MediaSize's microns I'm trying to save web page design into pdf file.
I've searched the solution and they all saying about dealing MediaSize.
I want to save it as "legal" size, and it is 355600 height microns, and 215900 width microns.
So this is the code I used:
chrome_options = webdriver.ChromeOptions()

settings = {
    "recentDestinations": [{
        "id": "Save as PDF",
        "origin": "local",
        "account": ""
    }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    "mediaSize": {
        "height_microns": 355600,
        "width_microns": 215900,
        "name": "NA_legal",
        "custom_display_name": "legal"
    },
    "isCssBackgroundEnabled": True,
    "isHeaderFooterEnabled": True,
}

prefs = {'printing.print_preview_sticky_settings.appState' : json.dumps(settings)}

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--kiosk-printing')
chrome_options.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome("chromedriver.exe", options=chrome_options)
driver.get('page')
driver.execute_script('window.print();')

And I compared it with the pdf which I made by manual. It has different height(and maybe width as well).
I changed the height_microns and width_microns dramatically, and found out it isn't affected at all.
Did I miss something? Or was it deprecated somehow?
Thank you in advance!
Edit: I checked the spec and I think it somehow got recognized as unavailable value, and get width_microns: 215900, height_microns: 279400. But not sure why is that so... (https://github.com/chromium/chromium/blob/eadef3f685cd9e96e94fcb9645b6838b6d0907a8/chrome/browser/resources/print_preview/data/model.js)


text:
Q: .save() is not saving all the details given in list I have a list of size 20 which i am trying to save to database using .save() JPA.
but is saving only 17 rows.
After saving, i am checking in the database only 17 rows are getting reflected.
what might be the issue?
here is my code snippet.
List<MyBean> g=new ArrayList<>();
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
MyBean.add(mybean object);
repository.save(MyBean);

here it is saving only 17 rows in db, not all the 20.

A: This is not the soultion but a way to debug further
This is how List save implementation looks from inside.
@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {

    List<S> result = new ArrayList<S>();

    if (entities == null) {
        return result;
    }

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}

you notice its returning List. So all your persisted data are also returned.
you can cross check which entities are missing.


text:
Q: Make ElectronJS mainWindow.loadURL() asynchronous I have a ExpressJS server running inside an electron instance and the mainWindow.loadURL() is directed to the server view URL (localhost:3000) but the mainWindow launches before the server is able to start so it's not able to fetch the view. I tried restarting the instance once running but apparently it restarts the server too.
I tried stopping the electron instance with a loop for some seconds to give the Express server time to start but is quite a mediocre solution.
I need a way to restart the Electron mainWindow using code until it's able to fetch the landing page from the Express server or to stop the Electron instance for as long as the Express server is able to fully start.
Note: The Express server also runs a Moongose instance which starts around one second after.
Don't know if the code will help, it's just a common Electron basic index.js file with 2 extra lines:
const {app, BrowserWindow} = require('electron');
const server = require('./app'); // HERE I LOAD THE EXPRESS SERVER

let mainWindow

function createWindow () {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        }
    })

    mainWindow.loadURL('http://localhost:3000') // HERE I TRIED TO LOAD THE EXPRESS LANDING PAGE

    mainWindow.on('closed', function () {
        mainWindow = null
    })
}

app.on('ready', createWindow)

app.on('resize', function(e,x,y) {
    mainWindow.setSize(x, y);
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    if (mainWindow === null) {
        createWindow()
    }
})

A: The Express server has facility for a callback with the app.listen() function.
The callback is called when the Express server is up and running.
Therefore, you can use that to wrap your window.loadURL(url) function.

main.js (main process)

For simplicity, I have added the instantiation of the Express server and the setting of any route(s) to this main.js file.

// Import required electron modules
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;

// Import required Node modules
const nodeExpress = require('express');
const nodePath = require('path');

// Start Express server
const appExpress = nodeExpress();

// Set route(s)
appExpress.get('/', (req, res) => {
    res.sendFile(nodePath.join(__dirname, 'index.html'));
});

// Prevent garbage collection
let window;

function createWindow() {
    window = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    // Using 'listen' callback, once server is ready, load the URL and show the window.
    appExpress.listen(3000, () => {
        window.loadURL('http://localhost:3000')
            .then(() => { window.show(); });
    });

    return window;
}

electronApp.on('ready', () => {
    window = createWindow();
});

electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

index.html (render process)
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Electron Test</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>

Hello world!


text:
Q: Include OSGI-INF to jar package after Maven compilation I'm creating OSGi package and I want the Apache Felix SCR maven plugin to automatically include generated OSGI-INF folder to .jar package. Now it just generates OSGI-INF to target/scr-plugin-generated. This is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>maven.test</groupId>
  <artifactId>test-dfs</artifactId>
  <version>0.0.4-SNAPSHOT</version>
  <name>DFS test</name>

  <build>
      <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-scr-plugin</artifactId>
            <version>1.9.0</version>
            <executions>
              <execution>
                <id>generate-scr-scrdescriptor</id>
                <goals>
                  <goal>scr</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
            <plugin>
              <artifactId>maven-jar-plugin</artifactId>
              <configuration>
                <archive>
                  <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
                </archive>
              </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.felix</groupId>
              <artifactId>maven-bundle-plugin</artifactId>
              <executions>
                <execution>
                  <id>bundle-manifest</id>
                  <phase>process-classes</phase>
                  <goals>
                    <goal>manifest</goal>
                  </goals>
                </execution>
              </executions>
            </plugin>
      </plugins>
  </build>

  <dependencies>
    <dependency>
        ...
    </dependency>
    <dependency>
      <!-- scr annotations - for generating component descriptors only -->
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.scr.annotations</artifactId>
      <version>1.7.0</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>

  <properties>
    <depl.user>user</depl.user>
    <depl.password>password</depl.password>
    <depl.host>localhost</depl.host>
    <depl.port>4502</depl.port>
  </properties>

</project>

A: if you use:
<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>2.4.0</version>
    <extensions>true</extensions>
</plugin>

instead maven-jar-plugin + maven-bundle-plugin (with manifest goal), all files generated by maven-scr-plugin will be included into a built bundle implicitly.


text:
Q: Multiple Materialized view refresh via pg_cron blocks other scheduled cron jobs I have a table "T1".
2 materialized views MV1 and MV2  built on T1.
The materialized views have aggregate functions on the data.
Using pg_cron, I scheduled view refresh (concurrent) at 5 min, 15 min and 12 hours for MV1, MV2 and MV3 respectively.The view refresh for MV1 takes time more than 5 min, for example 25 min.
When MV1 refresh is in progress, i expect the 15th min refresh job for MV2 to start as all are independent views.
But if one cron job is in progress, none of the other cron jobs start.
Tried with a dummy cron job , to run every one minute. The dummy job also does not run if any other cron is in progress.
What could be the reason and how to solve it?
postgres version 14
pg cron version 14
But if i manually run a refresh materialized view concurrently on MV2 then it works.


text:
Q: OSError: Disk quota exceeded When I run:
gcloud init

I met an error like this:
Welcome! This command will take you through the configuration of gcloud.

Settings from your current configuration [default] are:
core:
  disable_usage_reporting: 'True'

Pick configuration to use:
 [1] Re-initialize this configuration [default] with new settings
 [2] Create a new configuration
Please enter your numeric choice:  1

ERROR: gcloud crashed (OSError): [Errno 122] Disk quota exceeded

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics

I check the disk usage and find that I have 10+G left on my local file systems.
How could I solve this problem? Which path should I check, the installation path or /home? (Linux)


text:
Q: Perl - How can I turn a hash into a query string? How can I turn a hash into a query string? I would like to find a solution that doesn't involve using the CGI module. Here's an example of what I'm wanting to do but don't know what the best and most elegant approach would be, since I'm relatively new to Perl.
Hash:
my $data = {
         'key1' => 'value1',
         'key2' => 'value2',
         'key3' => 'value3',
         'key4' => 'value4'
};

To desired query string:
key1=value1&key2=value2&key3=value3&key4=value4

A: use URI qw( );
my $url = URI->new('', 'http');
$url->query_form(%$data);
my $query = $url->query;

If you're actually trying to build a POST request, check out HTTP::Request::Common's POST.


text:
Q: Python insert variable to mysql via mysql.connector I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.
This is how I create the table:
CREATE TABLE aaa (
     id MEDIUMINT NOT NULL AUTO_INCREMENT,
     data CHAR(30) NOT NULL,
     PRIMARY KEY (id)
);

This is my python script:
import mysql.connector
from time import strftime, gmtime, sleep

cnx = mysql.connector.connect(
    user='root', password='abcd', database='test_db'
    )
cur = cnx.cursor()
# get current timestamp
curr_time = strftime("%Y%m%d_%H%M%S", gmtime())
cur.execute(
            "INSERT INTO aaa(data) VALUES (%s)", (curr_time)
            )
cnx.commit()
cnx.close()

The error is like this:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1

Can anyone help me solve this problem?

A: replace , with % in  "INSERT INTO aaa(data) VALUES (%s)", (curr_time) it should be "INSERT INTO aaa(data) VALUES (%s)"%(curr_time).
@tsh is correct use this (curr_time) -> (curr_time,) instead


text:
Q: Write validation failed for table row of type 'PurchPurchaseOrderLineEntity' I'm trying to post the the purchase order line details from postman using odata and I'm getting the following error.
{
"error": {
    "code": "",
    "message": "An error has occurred.",
    "innererror": {
        "message": "Write validation failed for table row of type 'PurchPurchaseOrderLineEntity'. Infolog: .",
        "type": "Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataValidateWriteException",
        "stacktrace": "   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateProcessor.CreateEntity_Save(ChangeOperationContext context, ChangeInfo changeInfo)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateManager.<>c__DisplayClass10_0.<CreateEntity>b__1(ChangeOperationContext context)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.ChangeInfo.ExecuteActionsInCompanyContext(IEnumerable`1 actionList, ChangeOperationContext operationContext)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.ChangeInfo.TrySave(ChangeOperationContext operationContext)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateManager.SaveChanges()\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataDelegatingHandler.<SaveChangesAsync>d__3.MoveNext()"
    }
}

}
I have tried checking these links but I'm not getting a breakthrough:

*

*https://powerusers.microsoft.com/t5/Connecting-To-Data/Error-creating-order-line-in-Dynamics-365-for-Operations/td-p/11927

*https://community.dynamics.com/365/financeandoperations/f/dynamics-365-for-finance-and-operations-forum/378486/error-while-submitting-po-from-external-system-odata-d365-f-o
Below is my payload
{
            "dataAreaId": "XXXX",
            "LineNumber": 1,
            "PurchaseOrderNumber": "XXXX-PO-000009",
            "ReceivingSiteId": "1",
            "LineDescription": "XXXXXXX XXXX XXXX",
            "ItemNumber": "SKU0000012530",
            "DIOTOperationType": "Blank",
            "LineAmount": 9687.19,
            "PurchasePriceQuantity": 1,
            "PurchasePrice": 9687.19,
            "PurchaseUnitSymbol": "EA",
            "OrderedPurchaseQuantity": 1,
            "DeliveryAddressName": "XXXXX XXXXX XXXX",
            "ProcurementProductCategoryName": "XXXXXX XXXXX XXXX",
            "ReceivingWarehouseId": "TG",
            "VendorInvoiceMatchingPolicy": "ThreeWayMatch",
            "RequestedDeliveryDate": "2021-09-03T12:00:00Z"
}

Anyone who can help me on this?
NB: The Purchase order header is working without any problem.

A: Despite the missing information in the question, I tried to reproduce the issue. My test setup was a 10.0.20 environment with contoso demo data. I used the DEMF company and created a new purchase order since the existing ones were either already invoiced and/or intercompany.
I created the new purchase order for vendor DE-001 and was able to create lines in it using an OData request sent by Postman.
While testing, I noticed that the response Postman receives does contain the infolog messages which are missing in the question. Either they were removed (in which case please [edit] the question and add them) or the version of D365 does not include them (in which case please [edit] the question to add the version information).
I also noticed that the payload in the question contains fields ItemNumber and ProcurementProductCategoryName. As far as I know, a purchase line can have only one of those two, but not both. If you manually create a line with either one, the other one will be locked for editing. So please retry your request without either the ItemNumber or the ProcurementProductCategoryName field.
For the record, here are the payloads that worked in my test setup:
Payload with procurement category
{
            "dataAreaId": "DEMF",
            "LineNumber": 1,
            "PurchaseOrderNumber": "000011",
            "ReceivingSiteId": "1",
            "LineDescription": "XXXXXXX XXXX XXXX",
            "ProcurementProductCategoryName": "PAYROLL",
            "DIOTOperationType": "Blank",
            "LineAmount": 47.11,
            "PurchasePriceQuantity": 1,
            "PurchasePrice": 47.11,
            "PurchaseUnitSymbol": "EA",
            "OrderedPurchaseQuantity": 1,
            "DeliveryAddressName": "XXXXX XXXXX XXXX",
            "ReceivingWarehouseId": "11",
            "VendorInvoiceMatchingPolicy": "ThreeWayMatch",
            "RequestedDeliveryDate": "2021-09-03T12:00:00Z"
}

Payload with item number
{
            "dataAreaId": "DEMF",
            "LineNumber": 1,
            "PurchaseOrderNumber": "000009",
            "ReceivingSiteId": "1",
            "LineDescription": "XXXXXXX XXXX XXXX",
            "ItemNumber": "D0001",
            "DIOTOperationType": "Blank",
            "LineAmount": 47.11,
            "PurchasePriceQuantity": 1,
            "PurchasePrice": 47.11,
            "PurchaseUnitSymbol": "EA",
            "OrderedPurchaseQuantity": 1,
            "DeliveryAddressName": "XXXXX XXXXX XXXX",
            "ReceivingWarehouseId": "11",
            "VendorInvoiceMatchingPolicy": "ThreeWayMatch",
            "RequestedDeliveryDate": "2021-09-03T12:00:00Z"
}


text: Q: Is that possible to use apache arrow integration with relation database? Apache Arrow is an in-memory columnar data structure and relational database is a line data structure. If we still use MySQL to store these in-memory data, the only way is to save the arrow file in the relational database or can I have any other choice?


text:
Q: Can the word never imply that something has happened many times? In the sentence given below does the use of the word never imply that Fred has watched the game many times in the past,but has never watched it completely from beginning to end?
Fred has never watched a  Barcelona football game in its entirety.
Thank you.

A:
Fred has never watched a Barcelona football game in its entirety.

In strict formal logical terms, we don't know whether Fred has watched any games at all.
However, in common usage, we would assume that Fred has partly watched some Barcelona games. Not necessarily many but probably more than one.


text:
Q: How to detect two finger touch: ReactJS I have touchMove event handler.
I am trying to access event object or to be the more specific number of touches on display.

 this.handleMapMove(e)}  onTouchStart={this.handleMapTouch} >
....

Then I access event in handler method
handleMapMove = (e) => {
   console.log(e);
   ...
};

In the console, I can see
Proxy {dispatchConfig: {…}, _targetInst: FiberNode, isDefaultPrevented: ƒ, isPropagationStopped: ƒ, _dispatchListeners: ƒ, …}
[[Handler]]: Object
[[Target]]: SyntheticTouchEvent
[[IsRevoked]]: false

How Can I access [[Target]] object in an example, or to be more specific, I need to notify the user to use two fingers to move map instead of one.

A: You can use touches property of the touch event, it will contain all the touch points available.
Like this:
handleMapMove = (e) => {
    console.log(e.touches);
};

As per MDN DOC:

A TouchList listing all the Touch objects for touch points that are
  currently in contact with the touch surface, regardless of whether or
  not they've changed or what their target element was at touchstart
  time.
This property is Read only .
Could be thought of how many separate fingers are able to be
  identified to be touching the screen.

A: You can access it like this:
let target = e.target || e.srcElement;

This will give you a regular DOMNode though.
You can call regular DOMNode function on it though, so the following would return the id of the target node:
target.getAttribute('id')

Take a look at the documentation: target - mozilla
Edit based on your comments
To get the number of clicks save the number of clicks in your React component's state and use that.
Take a look at the following example:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      clicks: 0,
      show: true
    };
  }

  IncrementItem = () => {
    this.setState({ clicks: this.state.clicks + 1 });
  }
  DecreaseItem = () => {
    this.setState({ clicks: this.state.clicks - 1 });
  }
  ToggleClick = () => {
    this.setState({ show: !this.state.show });
  }

  render() {
    return (

        <button onClick={this.IncrementItem}>Click to increment by 1</button>
        <button onClick={this.DecreaseItem}>Click to decrease by 1</button>
        <button onClick={this.ToggleClick}>
          { this.state.show ? 'Hide number' : 'Show number' }
        </button>
        { this.state.show ?
{ this.state.clicks }
 : '' }

    );
  }
}

which I took from: medium.com
 Based on yet more information added through comments..
You seem to want to get the number of fingers on the display, you don't need the target event for that you need "touch events".
To check whether two fingers have clicked you can use the following code:
handleMapMove = (e) => {
   if(e.touches.length == 2){
     console.log("yay, two finger press")
   }
};


text:
Q: Wordpress : hide Submenus, but show active submenu (3 tier) I've searched up and down the internet and cannot find an answer that fits my specific needs for this.  I'd really appreciate some help.
I've set up a menu in Wordpress, and have set some Jquery code to hide the .sub-menu so that only the top level menu items show.  On click, the second tier opens, and clicking on one of those will open the third tier.  Only the third tier are actually URL links, the others are just #.
That all works lovely. The problem is, when the user clicks on a third-tier link, and is taken to the relevant page, I want THAT tier to stay open on the new page.
I've managed to assign a .active class to the li within the ul for the open page, but I can't seem to target it in Jquery to force it to show the sub-menu but only for the ul/li that has the .active class...
Any ideas?
My JQuery:
$('.sub-menu').hide(); //Hide children by default
$('li a').click(function(){

$(this).siblings('.sub-menu').slideToggle('slow');
}

How do I target the correct navigation tier to keep that one open when viewing that page?


text:
Q: Pandas count in second dataframe if part of string is first df's content having a simple DataFrame like this one:
    items
0   apple
1   car
2   tree
3   house
4   light
5   camera
6   laptop
7   watch
8   other

what would be a good way to count the times the individual words occur in a string in DF2:
    id        items
0   555       wall, grass, apple
1   124       bag, coffee, light
2   23123     bag, none, game
3   666       none, none, none

resulting in something like this
    items    count
0   apple    1
1   car      0
2   tree     0
3   house    0
4   light    1
5   camera   0
6   laptop   0
7   watch    0
8   other    0

A: Let's try value_counts the exploded items columns of df2 then map the result to items column of df1
df1['count'] = (df1['items'].map(df2['items'].str.split(', ')
                                 .explode()
                                 .value_counts())
                .fillna(0).astype(int))

print(df1)

    items  count
0   apple      1
1     car      0
2    tree      0
3   house      0
4   light      1
5  camera      0
6  laptop      0
7   watch      0
8   other      0

A: I would split the items, explode, then reindex:
(df2['items'].str.split(', ')
    .explode().value_counts()
    .reindex(df1['items'], fill_value=0)
    .reset_index(name='count')
)

Output:
    items  count
0   apple      1
1     car      0
2    tree      0
3   house      0
4   light      1
5  camera      0
6  laptop      0
7   watch      0
8   other      0


text:
Q: How to enlarge image? I have an image where i need to zoom in and zoom out the image . How do i go about it . Not getting proper solutions until now . Banging head onto this . Have taken image tag where following is the code:
<apex:image id="theImage" value="https://s3.amazonaws.com/{!bucketToList}/{!obj.key}? AWSAccessKeyId=AKIAJGN4J4RSRNW26IEA&amp" width="100" height="100">
</apex:image>

Please help !

A: Visual force support HTML and JavaScript and if you want to Zoom out and Zoom in You can use Javascipt or CSS to achieve this functionality. Following link could be useful.
You can use like this.
<apex:page >
<style>
img:hover {
            height: 200px;
        }
</style>
 <apex:image id="theImage" value="https://s3.amazonaws.com/{!bucketToList}/{!obj.key}? AWSAccessKeyId=AKIAJGN4J4RSRNW26IEA&amp" width="220" height="55"/>
</apex:page>

When you will hover on image, Image will zoom in.
[https://stackoverflow.com/questions/21479102/how-to-add-zoom-in-out-on-click-to-all-img-html-tags][1]


text:
Q: Does Tom catch Jerry? Tom has Jerry backed against a wall. Tom is distance 1 away (perpendicularly). At time t=0, Jerry runs along the wall. Tom runs directly towards Jerry. Tom always runs directly towards Jerry. Tom and Jerry both run at the same speed.

*

*Does Tom catch Jerry?

*How close does he get (in the limit t tends to infinity)?

*What shaped curve does Tom run?

Edit: I made this problem up last week. Friends enjoyed it, I thought this site might too.
Hint: Take the x-axis as the wall, and assume Jerry runs to the right, without loss of generality at speed 1. Let $x(t)$ and $y(t)$ be Tom's position at time $t$. So $x(0) = 0$, and $y(0) = 1$.
Consider Tom's direction of travel at time $t$ towards Jerry at $(t, 0)$. Write $\theta$ for the (positive) angle below the horizon. Then
$$ \tan \theta =  \frac{dy}{dx} =  \frac {y}{t-x} $$
Tom runs at unit speed, so also
$$ \frac{dy}{dt} = - \sin \theta $$
$$ \frac{dx}{dt} = \cos \theta $$
That's as far as I got, I don't know how to solve such a complex differential equation.

A: The problem is simplified considerably if we consider the vector from Tom to Jerry.
So let $\vec r=\pmatrix{x\\y}$ be the vector from Tom to Jerry, with $r=|\vec r|=\sqrt{x^2+y^2}$. Then
\begin{eqnarray*}
\dot x&=&-\frac xr+1\;,\\
\dot y&=&-\frac yr\;,
\end{eqnarray*}
and
\begin{eqnarray*}
\dot r&=&\frac{x\dot x+y\dot y}r\\
&=&\frac xr-1\\
&=&-\dot x\;.
\end{eqnarray*}
Thus $r+x$ is constant. Initially $x=0$ and $r=1$, so the sum is $1$. In the limit, $x=r$, so both are $\frac12$.
This answers questions $1$ and $2$. To answer question $3$, you can introduce $\phi$ with $x=r\cos\phi$ and $y=r\sin\phi$ and calculate $\frac{\mathrm dr}{\mathrm d\phi}=\frac{\dot r}{\dot \phi}$ from $\dot x$ and $\dot y$. The result is
$$
\frac1r\frac{\mathrm dr}{\mathrm d\phi}=\tan\frac\phi2\;,
$$
and integrating yields $r=\lambda\cos^{-2}\frac\phi2$. The initial condition $r=1$, $\phi=\frac\pi2$ yields $\lambda=\frac12$, so the trajectory is
$$
r=\frac1{2\cos^2\frac\phi2}\;.
$$
Substituting $\phi=0$ again yields $r=\frac12$ in the limit.

A: Let $x=1$ be the  wall,  let Tom start at $(0,0)$, Jerry at $(1,0)$ upwards, and assume that both have the same speed $1$. Tom's orbit is then a graph curve
$$\gamma: \quad x\mapsto \bigl(x,y(x)\bigr)\qquad(0\leq x<1)\ ,$$
whereby $y(0)=y'(0)=0$. At  any point $(x,y)\in\gamma$ we have
$$y'={\int_0^x\sqrt{1+y'^2}\>dx -y\over 1-x}\ .\tag{1}$$
One arrives at this equation by the following argument: When Tom is at $(x,y)$ he has run the length $s:=\int_0^x\sqrt{1+y'^2}\>dx$ so far. Therefore Jerry is at $(1,s)$ now, and this enforces $(1)$.
From $(1)$ we get
$$(1-x)y'+y=\int_0^x\sqrt{1+y'^2}\>dx\qquad(0\leq x<1)\ .$$
In order to get rid of the integral we take the derivative with respect to $x$ and separate variables:
$${y''\over\sqrt{1+y'^2}}={1\over 1-x}\ .$$
This leads to
$$\log\bigl(y'+\sqrt{1+y'^2}\bigr)=\log{1\over1-x}+C\ ,$$
and the initial condition $y'(0)=0$ immediately gives $C=0$. We solve for $y'$ and obtain
$$y'={1\over2}\left({1\over 1-x}-(1-x)\right)\ .$$
One more integration then gives
$$y(x)={x^2\over4}-{x\over2}+{1\over2}\log{1\over 1-x}\qquad(0\leq x<1)\ .$$
This is the explicit shape of $\gamma$. In order to compute how far Tom is staying behind in the limit we have to compute the limit for $x\to 1-$ of
$$\int_0^x\left(\sqrt{1+y'^2(x)}-y'(x)\right)\>dx=\int_0^x(1-x)\>dx=x-{x^2\over2}\ .$$
It follows that Tom stays ${1\over2}$ behind in the limit.

A: See to the essence of the problem so you can avoid needless calculations:
No.  Of course Tom will never catch Jerry.

*

*Jerry's horizontal speed is always $v_x=1$.

*Tom's horizonal speed begins $v_x<1$ and is always $v_x \le 1$.

QED.

A: Let the speed of tom be v and of jerry be u. Let tom be running at angle $\theta$ from horizontal at any instant, relative velocity of tom wrt jerry is $v-u\cos\theta$ and let them be at an initial separation $l$ so $\int_0^T(v-u\cos\theta){\rm d}t=l$ and also $\int_0^Tv\cos\theta=uT$ so $T=\frac{vl}{v^2-u^2}$. Try putting $u=0$.

From question $u=v$ so $T=vl/(v^2-v^2)\to\infty$


text:
Q: Consumir DLL C no VB6 ou C# Tenho uma DLL (gbasmsb_library.dll) disponibilizado pela Farmácia Popular responsável por retornar algumas funções para interação com este ambiente.

Penso que seja uma DLL escrita em C, preciso consumir esta DLL em VB6 OU C#.
No Guia do programador do programador tenho as seguintes informações para o uso da DLL:

1:

Sintaxe:

const char* IdentificaEstacao();

Valor de retorno: Uma string contendo o DNA da máquina.

2:

Sintaxe:

const char* PegaSolicitacao(
const char* CNPJ,
const char* CPF,
const char* CRM,
const char* UF_CRM,
const char* DT_EMISSAO );

Uma string que será utilizada para validação da solicitação através da geração da assinatura da
  máquina.

Em VB6 consegui consumir a primeira função (1), já a segunda retorna erro:

49 Bad DLL calling convention

Código VB6:
Private Declare Function PegaSolicitacao Lib "c:\temp\gbasmsb_library.dll" (ByRef CNPJ As String, ByRef CPF As String, ByRef CRM As String, ByRef UF_CRM As String, ByRef DT_EMISSAO As String) As String
Private Declare Function IdentificaEstacao Lib "c:\temp\gbasmsb_library.dll" () As String
    Private Sub Form_Load()
      MsgBox (IdentificaEstacao) //1 - retorno OK

      Dim CNPJ As String, CPF As String, CRM As String, UF_CRM As String, DT_EMISSAO As String

      Dim resp As String
      CNPJ = "98352942000133"
      CPF = "72794534491"
      CRM = "7347"
      UF_CRM = "AM"
      DT_EMISSAO = "01/01/1991"
      resp = PegaSolicitacao(CNPJ, CPF, CRM, UF_CRM, DT_EMISSAO) //2 - ERRO
    end sub

Já alterei a assinatura da função para byVal, mudei os parâmetro para array também sem sucesso.
Código C# Sem sucesso na chamada de nenhuma FUNÇÃO.
[DllImport(@"c:\temp\gbasmsb_library.dll")]
private static extern string PegaSolicitacao(string cnpj, string cpf, string crm, string ufCrm, string dtEmissao);

[DllImport(@"c:\temp\gbasmsb_library.dll")]
private static extern string IdentificaEstacao();

private void button1_Click(object sender, EventArgs e)
{
    var cnpj = "98352942000133";
    var cpf = "72794534491";
    var crm = "7347";
    var ufCrm = "PI";
    var dtEmissao = "01/01/1991";
    //MessageBox.Show(PegaSolicitacao(ref cnpj, ref cnpj, ref cnpj, ref cnpj, ref cnpj));
    //ERRO
    MessageBox.Show(PegaSolicitacao(cnpj, cpf, crm, ufCrm, dtEmissao));
    //ERRO
    IdentificaEstacao();
}

A: Bibliotecas em C/C++ possuem convenção de chamadas (a maneira pela qual o método é manipulado pela CPU, sua pilha, etc), isto implica em otmização.

https://msdn.microsoft.com/en-us/library/k2b2ssfy.aspx

Enfim, sua solução está aqui:

https://msdn.microsoft.com/en-us/library/aa232602%28v=vs.60%29.aspx

Tenha certeza de que os argumentos estão corretos e na mesma ordem, bem como o nome da função, também especifique a convenção de chamada diretamente no atributo:
    // analise sua DLL, talvez não seja StdCall, pode ser Cdecl ou outras convenções
    [DllImport("Foo.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern void FooMethod();

Talvez alguns pontos a mais sejam necessários como CharSet (Unicode ou Ansi) e ExactSpelling=true
Outro ponto importante:

https://stackoverflow.com/questions/370079/pinvoke-for-c-function-that-returns-char

Strings (char* para string) -> Use System.IntPtr já que char* é um ponteiro, você precisará criar a string depois de chamar o método copiando por Marshal.
Assinatura das Funções
public class Gba
{

    //const char* IdentificaEstacao();
    [return: MarshalAsAttribute(UnmanagedType.AnsiBStr)]
    [DllImport("gba.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
    public static extern string IdentificaEstacao();

    //const char* PegaSolicitacao( const char* CNPJ, const char* CPF, const char* CRM, const char* UF_CRM, const char* DT_EMISSAO );
    [return: MarshalAsAttribute(UnmanagedType.AnsiBStr)]
    [DllImport("gba.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
    public static extern string PegaSolicitacao(string CNPJ, string CPF, string CRM, string UF_CRM, string DT_EMISSAO );

    //const char* PegaConfirmacao( const char* CNPJ, const char* NU_AUTORIZACAO, const char* NU_CUPOM_FISCAL );
    [return: MarshalAsAttribute(UnmanagedType.AnsiBStr)]
    [DllImport("gba.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
    public static extern string PegaConfirmacao(string CNPJ, string NU_AUTORIZACAO, IntPtr NU_CUPOM_FISCAL );
}


text:
Q: getting error of cursor while fetching single row from mysqlite hi am facing an error while getting a long string from sqlite. is there any limit to store long string in sqlite.
i am facing  below error
 Couldn't read row 0, col 0 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

here is my create table query
 private static final String CREATE_TABLE2 = "create table " + SHAREDPREFERANCEVIDEO_TABLE + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT,"+
        "storedvalue1 TEXT)";

and here is function of fetching single row which is only one row in my table
  public String sharedprefindb (int position) {

    String value="";
    String id =Integer.toString(position);
    SQLiteDatabase db =this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT  *  FROM "+ " sharedpreferancevideo_talbe " + " WHERE ID = ? ", new String[] {id});;
    if(cursor.getCount()!=0)
    {
        if(cursor.moveToFirst()){
            do{
                value=cursor.getString(cursor.getColumnIndex("storedvalue1"));
            }while(cursor.moveToNext());
        }
        cursor.close();
    }
    return value;
}

my this code is working fine in another project in which string is very small
but in this code i am storing encrepted data so its text is verylong.
so any idea where is i am doing wrong.

A: Updated
Try this solution by changing your function:
public String sharedprefindb (int position) {

    String value="";
    String id =String.valueOf(position);
    SQLiteDatabase db =this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT  *  FROM "+ " sharedpreferancevideo_talbe " + " WHERE ID = '"+position+"'", null);;
    if(cursor!=null && cursor.getCount() > 0)
    {
        if(cursor.moveToFirst()){
            do{
                value=cursor.getString(cursor.getColumnIndex(1));
            }while(cursor.moveToNext());
        }
    }
    cursor.close();
    return value;
}


text:
Q: Why is curl truncating this query string? I'm sure the answer to this is going to be some painfully obvious character encoding issue...
I'm using curl on the command line to test some endpoints in a python app.  The endpoint takes url params of latitude and longitude.  Nothing too special.  I put in the command:
curl -v -L http://localhost:5000/pulse/?lat=41.225&lon=-73.1

Server responds, with verbose curl output:
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET /pulse/?lat=41.225 HTTP/1.1
> User-Agent: curl/7.21.6 (i686-pc-linux-gnu) libcurl/7.21.6 OpenSSL/1.0.0e zlib/1.2.3.4 libidn/1.22 librtmp/2.3
> Host: localhost:5000
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 500 INTERNAL SERVER ERROR
< Content-Type: application/json
< Content-Length: 444
< Server: Werkzeug/0.8.1 Python/2.7.2+
< Date: Wed, 01 Feb 2012 17:06:29 GMT
<
{
    "msg": "TypeError: float() argument must be a string or a number",
    "flag": 0,
    "stack": [
        "Traceback (most recent call last):",
        "  File \"engine.py\", line 139, in dispatch_request",
        "    return getattr(self, 'action_'+endpoint)(request, **values)",
        "  File \"engine.py\", line 818, in action_getpulse",
        "    lon = float(request.args.get('lon'))"
    ],
    "err": 1
* Closing connection #0
}
[1]+  Done

On the second line of that dump, it's obvious that the second param, lon, isn't being sent.  What am I doing wrong?  Thanks.

A: I think you can try this:
 curl -v -L -d "lat=41.225&lon=-73.1" http://localhost:5000/pulse

by default, this calls POST. If you want to send a GET request
 curl -v -L -G -d "lat=41.225&lon=-73.1" http://localhost:5000/pulse

More...
and since you're using localhost, if you were to use https, you'd probably want to include -k as an option to ignore certificate errors
Thanks to Ross for pointing this.

A: The answer to the question, "what am I doing wrong," is that the shell sees the ampersand (&) and thinks that's the end of the command (and puts it into the background). You need to quote it, which is why the answers that quoted the string work. You could just as easily run this:
curl -v -L "http://localhost:5000/pulse?lat=41.225&lon=-73.1"


text:
Q: UISplitviewcontroller and printing "Airprint" with navigationbar I got uisplitviewcontroller and it's working almost flawless
how ever
i implantent a way for th user to print using AirPrint...
i had to implant it on every Detail storyboard how ever and make navigation bar not appear and then write in the AirPrint method. i wanted to know if theres anyway to do this properly
in my seneario i lose the popupcontroller that navigates back to Index in the uitableview
and i want to be able to have a "back" button and print from all Details i have
my AirPrint code :
- (void)printWebView:(id)sender {

UIGraphicsBeginImageContext(self.view.bounds.size);{
    CGPoint savedContentOffset = scrollView.contentOffset;
    CGRect savedFrame = scrollView.frame;

    scrollView.contentOffset = CGPointZero;
    scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);

    [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];

    scrollView.contentOffset = savedContentOffset;
    scrollView.frame = savedFrame;
}
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIPrintInteractionController *printer = [UIPrintInteractionController sharedPrintController];
printer.printingItem = viewImage;

UIPrintInfo *info = [UIPrintInfo printInfo];
info.orientation = UIPrintInfoOrientationLandscape;
info.outputType = UIPrintInfoOutputGeneral;
printer.printInfo = info;

UIPrintInteractionCompletionHandler completionHandler =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (!completed && error)
    NSLog(@"FAILED! due to error in domain %@ with error code %ld: %@",
          error.domain, (long)error.code, [error localizedDescription]);
};

if (IDIOM == IPAD)
[printer presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
else
[printer presentAnimated:YES completionHandler:completionHandler];
}

my navigation "sorta"
can't set navigation bar to NO because then i won't print the current Detail and instead takes the first detail "Top"
-(void)mineSygedomme:(int)viewId {
UIViewController *viewController;
switch (viewId) {
    case 0:
        viewController = self.vaccinationer;
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        break;
    case 1:
        viewController = self.skadestuen;
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        break;
    case 2:
        viewController = self.leagen;
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        break;
}
[self showChildViewController:viewController];
}
-(void)showViewWithId:(int)viewId {
UIViewController *viewController;
switch (viewId) {
    case 0:
        viewController = self.startSide;
        break;
}
[self showChildViewController:viewController];

}

i tried using this code on the other Details but it wouldn't work
#pragma mark - Split view

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Hovedmenu", @"Hovedmenu");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem

{
// Called when the view is shown again in the split view, invalidating the button and popover controller.
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}

i think i need a way to get current Detail/Storybord and then i can print from it
but don't know how to do this

A: figured it out atlast !
had to change they way the AirPrint works. so it takes a screenshot of uiview and then prints that
- (void)printWebView:(id)sender {

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGRect rect=self.view.frame;

CGImageRef cropped1 = CGImageCreateWithImageInRect(viewImage.CGImage, rect);
UIImage *imges =  [UIImage imageWithCGImage:cropped1];
CGImageRelease(cropped1);
// squarecropimg.image=imges;

NSData *date=UIImagePNGRepresentation(imges);
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doc = [paths objectAtIndex:0];
NSString *appstr = [doc stringByAppendingPathComponent:@"currentview.png"];
[date writeToFile:appstr atomically:YES];

UIPrintInteractionController *printer = [UIPrintInteractionController sharedPrintController];
printer.printingItem = viewImage;

UIPrintInfo *info = [UIPrintInfo printInfo];
info.orientation = UIPrintInfoOrientationLandscape;
info.outputType = UIPrintInfoOutputGeneral;
printer.printInfo = info;

UIPrintInteractionCompletionHandler completionHandler =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
    if (!completed && error)
        NSLog(@"FAILED! due to error in domain %@ with error code %ld: %@",
              error.domain, (long)error.code, [error localizedDescription]);
};

if (IDIOM == IPAD)
    [printer presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
else
    [printer presentAnimated:YES completionHandler:completionHandler];
}