Q: CSS3 :target on named tag not working I am having a hard time getting :target to work on a named tag.
The fiddle is here: https://jsfiddle.net/vgcLartp/1
Any ideas why this is not working?

A: You need to use target on the sections that you want to show not the links
section:target {...}

See updated jsfiddle

nav {
  height: 60px;
  border-bottom: 1px solid #eaeaea;
}

.nav-item {
  display: block;
  float: left;
  margin-right: 20px;
  height: 60px;
  font-size: 26px;
  line-height: 60px;
  text-align: center;
  overflow: hidden;
  color: #666;
  text-decoration: none;
  border-bottom: 3px solid transparent;
  outline: none;
}

.nav-item:last-child {
  margin-right: 0;
}

.nav-item:hover {
  color: #333;
}

.nav-item.active,
.nav-item.active:hover {
  color: #333;
  border-bottom-color: #b39095;
}

section:target {
  visibility: visible;
  opacity: 1;
}

/* -------------------------------- SECTIONS -------------------------------- */

#sections {
  float: left;
  width: 1200px;
  height: 400px;
}

section {
  position: fixed;
  width: 630px;
  height: 400px;
  float: left;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.5s linear;
}

section p {
  padding-top: 5px;
  line-height: 1.6em;
}

section a {
  color: #b39095;
  text-decoration: none;
}

section a:hover {
  color: #7b618a;
}

/* --------------------------------- OPTIONS -------------------------------- */

fieldset {
  margin: 26px 0 15px 0;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}

input {
  padding-left: 2px;
}

#oxford-app-id {
  width: 80px;
}

#oxford-app-key {
  width: 290px;
}

label {
  padding-left: 5px;
}

      options
saved
      about

        Options

        About

A: try this
:target {
  visibility: visible;
  opacity: 1;
}

A: From w3school:

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
  The :target selector can be used to style the current active target element.

:target selector is useful when within an URL is specified (using an anchor  for example) an element in your HTML.
In your case you can use:
:target {
    visibility: visible;
    opacity: 1;
}


Q: Android AVD install chrome and firefox I created few AVD's using the AVD Manager. I want to know how can I install chrome/firefox on these AVD's?

A: Chrome's .apk
Firefox's .apk
Download both .apk files and install to your AVD using adb install apk_name

A: To install something onto a device, you need to already have the device running.
So first, start the device using the emulator command.
Then, in a different terminal/command window, use the adb command to install the package. In my case, I've copied the apk file to the platform-tools folder:
./adb install Firefox_17.0.apk

Like the rest of the emulator, the installation is slow, so be patient.
Of course, this just installs the packages. Getting them to run successfully is another matter entirely. So far, I cannot get the Chrome or Firefox packages to run. Chrome says "Not supported on this version of Android. Version 4.0 is minimal supported version." I am running 4.3 in the emulator. And Firefox starts but then immediately terminates with a "Unfortunately, Firefox has stopped" message.

A: Get the apk files and install them through adb (adb install .apk.


Q: How to remove "continue;"? I have this c++ program that tries to remove vowels from a char array. This works, but I want to do this without continue;.
#include <iostream>
#include <string.h>
using namespace std;

int main() {

    char s[21],afterElimination[19],vowels[] = "aeiou";
    cin.get(s,20);
    int i, n = strlen(s),VowelPos = -1,h = 0;
    for (i = 0; i < n; i++) {
        if (strchr(vowels,s[i])) {
            if(VowelPos == -1) {
                VowelPos = i;
                continue;
            }
            VowelPos = i - 1;
        }
        afterElimination[h++] = s[i];

    }
    afterElimination[h] = NULL;
    strcpy(afterElimination + VowelPos, afterElimination + VowelPos + 1);

    cout<<afterElimination;

    return 0;
}

A: It's pretty easy to remove continue from the loop.  What you need is two indexes in your loop.  One for the position in the source array and one for the position in the array to copy to.  Then you put the copy operation inside the if statement so if there is no copy you do nothing to go to the next iteration.  That would make you loop look like
for (int source_index = 0, copy_index = 0; source_index < n; ++source_index) { // increment source_index always
    if (!strchr(vowels,s[i])) {
        // this isn't a vowel so copy and increment copy_index
        afterElimination[copy_index++] = s[i];
    }
    // now this is the continue but we don't need to say it
}

A: This is a typical approach to filtering letters from a given string.
#include <string.h>

char s[20] = "something";
char no_vowels[20] = {0};

int i = 0;
int j = 0;
const char *vowels = "aeiou";
while (s[i]) {
  if (!strchr(vowels, s[i])) {
    no_vowels[j] = s[i];
    j++;
  }
  i++;
}

Here's a working example.


Q: I can't make this JavaScript count working I want to make a button (out of divs) and a paragraph (or any text field) below the divs that counts the clicks.

$(document).ready(function() {
  $('#butt').mousedown(function() {
    $("#butt").hide();

  });
  $("#pushed").mouseup(function() {
    $("#butt").show();

  });
  $("#butt").click(function() {
    button_click();
  });
});

var clicks = 0;

function button_click() {
  clicks = parseInt(clicks) + parseInt(1);
  var divData = document.getElementById("showCount");
  divData.innerHTML = "Clicks:" + clicks;
}

<form name="ButtonForm">

</form>

A: Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them.
Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well.
Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div.
Lastly, to increment a number by one, you can just use the pre or post-increment operator (++).

$(document).ready(function() {
  var clicks = 0;
  var divData = $("#clickCount");

  $("#pushed").on("click", function() {
    $("#butt").show();
  });

  $("#butt").on("click", function() {
    $("#butt").hide();
    clicks++;  // increment the counter by one
    divData.html(clicks);
  });
});
#pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;}

  <form name="ButtonForm">

Clicks

  </form>

A: First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for.
Second, change the #butt element to an actual button so that you have something to see and click.
Third, make sure your script is loading after jquery is included.

<button id="butt">I'm a button</button>


Q: Proxy for MSGraph APIs I am trying to create an adapter (WEB API that will act as a pass through)
for invoking the MS Graph APIs for managing my Active Directory.
AD objects like application and users will be customized to meet our application needs (removing some attributes, adding some extension attributes etc.) and a transformation from our application specific object to AD object would happen in our adapter layer before and after calling MS Graph APIs.
MS Graph APIs currently supports OData queries.
Applications and users would be read as page-wise.
If I have to provide the same OData options in my pass thru Web API layer, how can I do that?
i.e.

*

*API A supports OData queries.

*API B calls the methods that support OData queries in API A.

*API B is exposed to the client. When the client calls the method from API B
 with OData $Filter, the result has to be returned.

How can I support the OData options in API B?
Thanks in advance.

A: Well, I'm not sure I get your question correctly but, from what I understand, you just want to proxy the API calls to MS Graph and make some changes on the fly to the response.
OData queries are just simple query parameters (see the OData tutorial). So, basically, you just have to get those query parameters in your proxy and forward them to the MS Graph. The response you'll get will then be compliant with the original query.
However, depending on how you mangle the data, you may end up not being compliant with the user query. For example:

*

*The user made a $select(Id) query, but your logic add a custom property Foo. The user just wanted Id but you added Foo anyway.

*The user made an $orderby Name asc query, but your logic modify the property Name. It may not be ordered after your logic.

*The user wants to make $filter query on the Foo property. MS Graph will complain because it doesn't know the Foo property.

*Etc.

If you want to handle that cases, well, you'll have to parse the different OData queries and adapt your logic accordingly. $orderby, $top/$skip, $count, $expand and $select should be pretty straight-forward ; $filter and $search would require a bit more work.

A: Thanks. I was looking for a solution to this.
https://community.apigee.com/questions/8642/how-do-we-fetch-the-query-parameters-odata-standar.html
Instead of parsing the URL to get the OData query parameters, i wanted to understand the standard method to process the OData requests.
Now I am doing the below to extract the OData query parameters and passing them to MSGraph API.
string strODataQuery = String.Join("&", HttpContext.Request.Query.Where(kvp => kvp.Key.StartsWith("$")) .Select(kvp => String.Format("{0}={1}", kvp.Key, Uri.EscapeDataString(kvp.Value))));
And I am performing the conversions after retrieving the results.
Regards


Q: Hibernate - Updating an ID of a parent in a child without updating parent? I couldn't find the answer or didn't phrase this question properly. If you guys know... let me know :-)
I have a parent which has children....
on the child, I have regular vars that map to column names
However, one is mapped as many-to-one. The child basically contains the ID for the parent. Except in the child I obviously contain the entity of the parent, not the id.
ie: (QUICK simple example....)
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name="bcId",referencedColumnName="id")
private ParentEntityClass theParentClass;

How, can I set the the parent object in this hibernate entity so it ONLY uses the parent entity for the ID and doesn't try to save the parent. Should I use Cascade.refresh so it refreshes but doesn't update the parent?
Thanks :)


Q: Why are these MongoDB sums not adding up? Lets say I have 2 documents:
{
    "_id" : "8tvgUTKt2U",
    "answers" : [
        [
            NumberInt(-1)
        ]
    ]
},
{
    "_id" : "BDTESUEIlm",
    "answers" : [
        [
            NumberInt(1)
        ],
        [
            NumberInt(-1)
        ]
    ]
}

I would like to total the values of the array items. But when I $unwind 'answers' and $sum them in $group pipeline I get this:
{
    "_id" : "BDTESUEIlm",
    "answerTotal" : NumberInt(0)
}
{
    "_id" : "8tvgUTKt2U",
    "answerTotal" : NumberInt(0)
}

What am I doing wrong?

A: It’s because when you $unwind a two dimensional array once you end up with just an array and $sum gives correct results when applied to numerical values in $group pipeline stage otherwise it will default to 0 if all operands are non-numeric.
To remedy this, you can use the $sum in a $project pipeline without the need to $unwind as $sum traverses into the array to operate on the numerical elements of the array to return a single value if the expression resolves to an array.
Consider running the following pipeline to get the correct results:
db.collection.aggregate([
    { '$project': {
        'answerTotal': {
            '$sum': {
                '$map': {
                    'input': '$answers',
                    'as': 'ans',
                    'in': { '$sum': '$$ans' }
                }
            }
        }
    } }
])


Q: SQL update query not cooperating I am adding a save/update button to the bottom of my editing form on my admin panel. For some reason, whenever I make a change to the form and click save it just reloads the page with no changes made. I also noticed that ONLY when I try to run the code from the pages.php file(runnning from index then clicking pages is fine) it says:

Undefined variable: dbc in
  C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
  on line 12
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
  in
  C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
  on line 12

I can get rid of this error by declaring a new $dbc(databaseconnection) variable in pages.php, but I still have the same problem updating my form data.
PAGES.PHP:
<?php ## Page Manager ?>

Page Manager

        <?php

           $q = "SELECT * FROM pages ORDER BY name ASC";
           $r = mysqli_query($dbc, $q);

           if ($r)
           {
                while ($link = mysqli_fetch_assoc($r))
                {
                    echo '
'.$link['name'].'
';
                }
           }

        ?>

    <?php

     if (isset($_POST['submitted']) == 1) {

            $q = "UPDATE pages SET title='$_POST[title]', name='$_POST[name]', body='$_POST[body]', WHERE id = '$_POST[id]'";
            $r = mysqli_query($dbc, $q);

     }

     if (isset($_GET['id'])) {

            $q = "SELECT * FROM pages WHERE id = '$_GET[id]' LIMIT 1";
;
            $r = mysqli_query($dbc, $q);
            $opened = mysqli_fetch_assoc($r);

    ?>

        <form action="?page=pages&id=<?php echo $opened['id'] ?>" method="post">

Page title: <input type="text" size="30" name="title" value="<?php echo $opened['title']?>">

Page name: <input type="text" size="30" name="name" value="<?php echo $opened['name']?>">

            Page body:

            <textarea name="body" cols="30" rows="8"><?php echo $opened['body'] ?></textarea>

               <input type="hidden" name="submitted" value="1"/>
               <input type="hidden" name="id" value="<?php echo $opened['id'] ?>"/>

<input type="submit" name="submit" value="Save Changes"/>

        </form>

    <?php } ?>

INDEX.PHP:
<?php
// Setup document:
include('config/setup.php');
?>

<!DOCTYPE HTML>

<meta charset="utf-8">
<title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">

 <?php head(); ?>

 <?php nav_main(); ?>

 <?php include('content/'.$pg.'.php'); ?>

 <?php footer(); ?>

SETUP.PHP
<?php
## Setup Document

// host(or location of the database), username, //password, database name

$dbc = @mysqli_connect('127.0.0.1', 'root', 'password', 'main') OR die ('Could not connect to the database because: '. mysqli_connect_error() );

include('Functions/sandbox.php');
include('Functions/template.php');

if (isset($_GET['page']) == '')
{
    $pg = 'home';
}
else
{
    $pg = $_GET['page'];
}

$page_title = get_page_title($dbc, $pg);

?>

A: on Pages.php you have
$r = mysqli_query($dbc, $q);

$q is fine but you have not mentioned $dbc
on your setup page, create a class for connection, declareing a connection method and then, on PAGES.PHP:
$db_obj =  new setup();  /* create object for setup class */
$dbc = $db_obj -> connect_db();/* call connection method */


Q: c++ how to create a std::vector of functors class A
{
public:
    int x;
    //create a vector of functors in B and C here
};

class B
{
public:
    struct bFunctor
    {
        void operator()() const
        {
            //some code
        }
    };
};

class C
{
public:
    struct cFunctor
    {
        void operator()() const
        {
            //some code
        }
    };

};

void main()
{
 A obj;
 //iterate through the vector in A and call the functors in B and C
}

My question is what should be the format of the vector in class A for calling functors in B and C? Or is the only way this is possible to have a base functor in A and make the functors in B and C derive from it? Or is there a better approach?

A: There are essentially two ways to approach this (that I can think of ATM):
Note: I would rename cFunctor and bFunctor to simply Functor in both cases. They are nested inside respective classes and thus such prefix makes little sense.
Type erased
Example of type erasure is std::function.
class A {
public:
    int x;
    std::vector<std::function<void(void)>> functors;

    A() : functors { B::bFunctor(), C::cFunctor() }
    { }
};

If you need the functors to have more advanced behaviour, Boost.TypeErasure any might help.
Polymorphic

*

*Create an abstract functor type.

*Make B::bFunctor and C::cFunctor inherit from it.

*Store vector of that abstract functor type smart pointers.

struct AbstractFunctor {
    virtual void operator()() const = 0;
};

class B {
public:
    struct Functor : public AbstractFunctor {
       void operator()() const {
       //some code
       }
    };
};

class A {
public:
    int x;
    std::vector<std::unique_ptr<AbstractFunctor>> functors;

    A() {
        // this could most probably be shortened with make_unique
        functors.emplace_back(std::unique_ptr<AbstractFunctor>(new B::Functor()));
        functors.emplace_back(std::unique_ptr<AbstractFunctor>(new C::Functor()));
    }
};


Q: Cannot validate, with novalidate option Hi I was inserting some date do my table. For some reasons I had to disable my constraint. The constraint was associated with index. I. ve used this line of code:
ALTER TABLE my_table DISABLE CONSTRAINT "my_constraint" drop index

And my_constraint is in disable state.
No I' d like to enable this constraint, but after calling this line:
ALTER TABLE my_table ENABLE NOVALIDATE CONSTRAINT "my_constraint";\

I recive an error:

ORA-02299: cannot validate (USER.my_constraint) -  - duplicate keys found

A: You cannot have non-unique values with a unique index.  But you can have non-unique values with a unique constraint that is enforced by a non-unique index.  Even if you initially created a non-unique index, the drop index and enable syntax will try to recreate a unique index unless you provide more details in the using index section.
For example:
SQL> create table my_table(my_column number,
  2     constraint my_constraint unique (my_column));

Table created.

SQL> alter table my_table disable constraint my_constraint drop index;

Table altered.

SQL> insert into my_table select 1 from dual union all select 1 from dual;

2 rows created.

SQL> alter table my_table enable novalidate constraint my_constraint;
alter table my_table enable novalidate constraint my_constraint
*
ERROR at line 1:
ORA-02299: cannot validate (USER.MY_CONSTRAINT) - duplicate keys found

SQL> alter table my_table enable novalidate constraint my_constraint
  2     using index (create index my_index on my_table(my_column));

Table altered.

SQL> --The constraint is enforced, even though other rows violate it.
SQL> insert into my_table values(1);
insert into my_table values(1)
*
ERROR at line 1:
ORA-00001: unique constraint (USER.MY_CONSTRAINT) violated

A: When you inserted the rows into your table you violated the constraint, looks like it is a unique constraint based on the error message "duplicate keys found"
check what columns the constraint is based on, and then do a quick query like the following to see if you have any rows with duplicates (columna and columnb are the columns in your unique constraint)
SELECT columna, columnb COUNT()
FROM mytable
HAVING COUNT() > 1
You won't be able to enable the unique constraint until all the rows in the table meet the rules of the constraint.


Q: Handling the Windows.UI.Xaml.Application.Suspending event I try to resolve the dreaded .WindowsPhone.exe!{<ID>}_Quiesce_Hang hang issue of my WinRT (Windows Phone 8.1) app.
At the moment I have the following handling of the Windows.UI.Xaml.Application.Suspending event:
    private void App_Suspending(object iSender, SuspendingEventArgs iArgs)
    {
        SuspendingDeferral clsDeferral = null;
        object objLock = new object();

        try
        {
            clsDeferral = iArgs.SuspendingOperation.GetDeferral();
            DateTimeOffset clsDeadline = iArgs.SuspendingOperation.Deadline;

            //This task is to ensure that the clsDeferral.Complete()
            //is called before the deadline.
            System.Threading.Tasks.Task.Run(
                async delegate
                {
                    //Reducing the timeout by 1 second just in case.
                    TimeSpan clsTimeout = clsDeadline.Subtract(DateTime.UtcNow).Subtract(TimeSpan.FromSeconds(1));

                    if (clsTimeout.TotalMilliseconds > 100)
                    {
                        await System.Threading.Tasks.Task.Delay(clsTimeout);
                    }

                    DeferrerComplete(objLock, ref clsDeferral);
                });

            //Here I execute the suspending code i.e. I serializing the app
            //state and save it in files. This may take more than clsTimeout
            //on some devices.
            ...

            //I do not call the Complete method here because the above
            //suspending code is old-fashoin asynchronous i.e. not async but
            //returns before the job is done.
            //DeferrerComplete(objLock, ref clsDeferral);
        }
        catch
        {
            DeferrerComplete(objLock, ref clsDeferral);
        }
    }

    private static void DeferrerComplete(object iLock, ref SuspendingDeferral ioDeferral)
    {
        lock (iLock)
        {
            if (ioDeferral != null)
            {
                try
                {
                    ioDeferral.Complete();
                }
                catch
                {
                }

                ioDeferral = null;
            }
        }
    }

I have read the answer about the _Quiesce_Hang problem. I get the idea that it might be related to app storage activity. So my question is: what am I missing? Does my handling of the Suspending event look OK?


Q: Unity 2 and Enterprise library configuration tool Can someone show me how to use Enterprise library configuration tool with Unity2
Whatever I did, when I open the Enterprise library configuration tool, I could not have it working with a Unity config file.
When I click on the menu to add a new block, there is no Unity configuration block
What am I doing wrong?
Thank you for your help

A: Unity 2.0 and documentation is available as a separate download as of today.
http://msdn.microsoft.com/unity
http://blogs.msdn.com/agile/archive/2010/04/20/microsoft-enterprise-library-5-0-released.aspx
Unfortunately the limited support for the Unity configuration in the Configuration Tool that you may have seen in one of the EntLib 5.0 betas didn't make it into the final release due to time constraints.
However, we have made the Unity configuration XML significantly easier to author with things like assembly and namespace aliasing to save having to repeatedly specify fully qualified types.

A: We have released Unity 2.0 standalone, Unity 2.0 for Silverlight as well as Enterprise Library 5.0 full documentation set today.

A: Unity 2 is not yet finalized (still in Beta 2). I guess we have to wait.
Besides, Unity 2 config file is much easier to be typed manually, compared to the 1.x versions.

A: If interested in Unity config tool, which was part of the beta but didn't make it to the final EntLib5.0 release, you can find it here


Q: Testing android app. Trying to mock getSystemService. Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually.
We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before.
The method I'm trying to test:
public boolean isGPSEnabled()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return GPSEnabled;
}

This method checks if the android device got the GPS enabled and returns true if it is, false if not.
I'm trying to mock the LocationManager and the Context, and this is what I have so far:
@RunWith(MockitoJUnitRunner.class)

public class IsGPSEnabledTest
{

    @Mock
    LocationManager locationManagerMock = mock(LocationManager.class);
    MockContext contextMock = mock(MockContext.class);

    @Test
    public void testGPSEnabledTrue() throws Exception
    {
        when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock);
        when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);

        MapsActivity activity = new MapsActivity();
        assertEquals(true, activity.isGPSEnabled());
    }
}

When I run this test I get this error:
"java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked."
Any help on this would be appreciated.

A: Pass the mocked context to your method in activity.
    @Test
    public void isGpsOn() {
        final Context context = mock(Context.class);
        final LocationManager manager = mock(LocationManager.class);
        Mockito.when(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(manager);
        Mockito.when(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);
        assertTrue(activity.isGpsEnabled(context));
    }


Q: double returning only one precision in java in my code i am performing division on numbers and storing it in a double variable. but the variable is returning with only one precision. i want to increase the precision how could i do that.
double x;
        for ( int i =0 ; i<10000 ; i++)
        {

            x= w[i] / l[i];
            System.out.println(x);
        }

in the above code w and l are integer arrays;
i am getting output like
3.0
0.0
1.0
0.0

i want to increase the precision upto 4 atleast.

A: Use
x = ((double) w[i]) / l[i];

As it is, you're dividing two integers using integer division, and assigning the resulting int to a double. Casting one of the operands to a double makes it do a double division instead.

A: If you divide an int by another int you get an int not a double.  Try
x = (double) w[i] / l[i];

A: System.out.printf("%10.4f", x);

Mind, only BigDecimal has precise precision. Doubles are approximations.


Q: Can the models.py file created by Django be used by another python file to fill in a database? I have followed the tutorial (parts 1 and 2) on the Django site (https://docs.djangoproject.com/en/1.4/intro/tutorial01/) and have managed to create a couple folders and to connect to my website. My app is called 'app', so my folder structure looks a bit like:

*

*mainFolder

*---__init__.py

*---test.py

*---djangoSite (created by Django)

*------ manage.py

*------ djangosite

*--------- other .py files

*------ app

*----------__init__.py

*--------- models.py

*--------- other .py files

I changed the models.py file to be something like:
class Result(models.Model):
    options = models.CharField(max_length = 1000, unique = False)
    reverse = models.DecimalField(decimal_places = 6, max_digits = 12)

test.py currently runs a couple tests on some other classes. What I want is for my test.py class to run these tests and save the results in a database (in columns
and reverse). I was hoping to do something like this in my test.py class:
import models.py
if __name__ == "__main__":
    optionResult = someTestsThatRuns
    reverseResult = someOtherTestThatRuns
    models.Result c;
    c.options = optionResult
    c.reverse = reverseResult

I'd like for the last two lines to save the result in the database.
Is this possible? How would I import the models.py from the app folder?
Thank you
EDIT:
When I say someTestsThatRuns, these aren't unit tests. They are practically a function that returns a list and some strings with either 'PASS' or 'FAIL'. Sorry for the confusion

A: Create an empty __init__.py file in the app folder so Python treats the directory as a package. Then do:
from app.models import Result

optionResult = someTestsThatRuns
reverseResult = someOtherTestThatRuns
c = Result()
c.options = optionResult
c.reverse = reverseResult
c.save()

That will save 'c' to the database.
Note that Django's test suite can create its own test database, which runs tests on a separate database. You can read more about Django testing here.
https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs

A: FIXED As David mentioned in the comments, the environment variable was indeed not set. Since I was in Windows, what I had to do was Start -> Computer -> Properties -> advanced System Settings -> Environment Variables -> add Environment Variable.
There I added 'DJANGO_SETTINGS_MODULE' and its location as 'C:\path\to\your\settings.py' Afterwards, in command prompt, I had to do the following:
enter python
>import sys
>import os
>sys.path.append(r"C:\location\to\settings.py")
>from django.core.management import setup_environ
>setup_environ(settings)
>sys.path.append(os.getcwd() + '\\from\\current\\to\\models.py'
>from models import Result

This is all explained at http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ , though I did find it somewhat difficult to understand. Another problem I had with importing my models is that there were TWO folders named exactly the same (djangoSite), so when importing, the computer had some issues trying to figure out which one. I had to rename, remove, reset environment variable and recheck all of the paths I have throughout my files =/
I am sorry if my explanations aren't the best, I barely understood what I did, but I do hope this will help other in the future


Q: Integration class Hey everybody here is my code:
package Chapter5;

import java.util.Scanner;

public class MainMenu extends Integration
{

static Scanner s = new Scanner(System.in);
static int c;
static double lower, upper;
static double Curves;
static double sum = 0;

public static void main(String[] args)
{

    while(true)
    {
        System.out.println("Please choose one of the options");
        System.out.println("1: Calculate the area between two curves");
        System.out.println("2: Calculate the volume when two curves are revolved about a disk");
        System.out.println("3: Calculate the volume when a single curve is revolved about a shell");
        System.out.println("4: Quit");
        c = s.nextInt();
        if(c == 1)
        {
            System.out.println("Area between two curves");
            System.out.println("Please enter the lower limit");
            lower = s.nextInt();
            System.out.println("Please enter the upper limit");
            upper = s.nextInt();
            System.out.print("Lower limit: " + lower);
            System.out.println("  Upper limit: " + upper);
            System.out.println("The area under the f curve: " + sumf);
            System.out.println("The area under the g curve: " + sumg);
            sum = sumf - sumg;
            System.out.println("Area between the two curves = " + sum);
        }
        if(c == 2)
        {
            System.out.println("Working");
        }
        if(c == 3)
        {
            System.out.println("Working");
        }
        if(c == 4)
        {
            break;

        }
    }
}

Here is my Integration class:
   package Chapter5;

   /*Author: Cory Zander
   * Purpose: Find the area and volume between two curves
   */
   public class Integration
   {

static double x;
static double dx;
static double f, g;
static double sumg = 0;
static double sumf = 0;
public static double f(double x)
{
    f = x * Math.exp(x);
    return x;

}
public static double g(double x)
{
    g = Math.pow(x, 2);
    return x;

}

public static double Areaf(double lower, double upper)
{
    int i;
    x = lower;
    dx = (upper - lower)/2000;
    for(i = 0; i <= 2000; i++)
    {
        if(i == 0 || i == 2000)
        {
            sumf += f;
        }
        else
        {
            sumf += 2 * f;
        }
        x += dx;

    }
    sumf *= dx/2;
    return sumf;

}
public static double Areag(double lower, double upper)
{
    int i;
    x = lower;
    dx = (upper - lower)/2000;
    for(i = 0; i <= 2000; i++)
    {
        if(i == 0 || i == 2000)
        {
            sumg += g;
        }
        else
        {
            sumg += 2 * g;
        }
        x += dx;

    }
    sumg *= dx/2;
    return sumg;
}

Okay I just edited this and fixed the areaf and areag issue, but for some reason when I get the area under the f curve I still get 0. Why is it not taking the sumf from the Integration class

A: public static void main(String[] args){
    if (c == 1){
        //...
        double area1 = Integration.Areaf(lower, upper);
        double area2 = Integration.Areag(lower, upper);
        sum = area1 - area2;//sum and minus used?
        System.out.println("Area between the two curves = " + sum);
   }
}

Also you used inheritance incorrectly cause all your methods in base class (Integration) are static. You can simply delete extends clause from sub class or adjust it in correct way.


Q: create value to a model from another model's method I'm trying to create a new table (Payslip model) that will contain the computed salary on an employee in a cutoff.
I want Payslip.salary to get value from  Employee.compute_pay()
Given the example in the url link above, what should my views.py look like?
Is this the best approach to this kind of process? or Is there any library that can help with what I want to do here?
https://imgur.com/a/wVG5qrd
model.py
class Employee(models.Model):
    name = models.CharField(max_length=20)
    rate = models.IntegerField()
    absent = models.IntegerField()
    def __str__(self):
        return self.name
    def compute_pay(self):
        daily = rate / 20
        return rate - (daily*absent)

class Payslip(models.Model):
    name = models.CharField(max_length=20)
    salary = models.IntegerField()
    def __str__(self):
        return self.name

views.py
def compute(request):
    if request.method == "POST":
        return render(request,'payroll/compute/compute.html')

A: I do not think there is a need for another model Payslip, also you have no ForeignKey connections between the two models for it to work.
Considering your requirement, property decorator should work. Read up on how @property works. Basically, it acts as a pseudo model field, keep in mind the value of this field is not stored anywhere in the database, but it is tailor-made for situations like this where the field changes based on other fields and is needed for read-only.
Try this
class Employee(models.Model):
    name = models.CharField(max_length=20)
    rate = models.IntegerField()
    absent = models.IntegerField()

    def __str__(self):
        return self.name

    @property
    def compute_pay(self):
        daily = self.rate / 20
        return (self.rate - (daily*self.absent))

you can get the employee's salary by Employee.compute_pay just like any other model field


Q: How to query classes with edges in orient Db?
My problem is, how can I query “Chat”  table to retrieve person’s details in Profile Table.
ParticipatinIn edge started from Person to chat.
HasProfile Edge came started person to Profile.
Please Help me to solve this..
Thank You

A: I have used this structure

You can use a query like this :
select name, person.name, person.out("hasProfile").name as profile from (select name, in('ParticipatinIn') as person from Chat unwind person) unwind profile

If you use traverse, if a person is a part of two different Chat, you got that person only one time.
Hope it helps.

A: With this schema:

Try this:
select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile

This is the output:

If you don't like see the bracket you can use the unwind command:
select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile unwind Person,Chat

This is the output:

UPDATE
select name, in('ParticipatingIn').name as  Person, in('ParticipatingIn').out('HasProfile').name as Profile from Chat

UPDATE 2
traverse * from Chat

Hope it helps
Regards.


Q: Split Strtotime('now') to seconds and minutes I am developing a browser game where the player gets hospitalized for 30 minutes when his health becomes 0. I am using strtotime to check how much time is left until he gets out of the hospital.

<?php
$current_time = strtotime('now') + 1800; // This variable goes to the database
// The player gets hospitalized for 30 minutes, that's 1800 seconds.

// Updating the database ...
$sql = "UPDATE playerstats SET hospitalized='1', hospitaltimer=$current_time WHERE id = $id";
?>

Now let's say the player is in the page where it says he has to wait ?? minutes ?? seconds until he gets out of the hospital.

<?php
// Getting the timer from the database ...
global $db;
$sql = "SELECT * FROM playerstats WHERE id=$id";
$stmt = $db->query($sql);
$result = $stmt->fetchAll();

$timer = $result[0]['hospitaltimer'];
// substracting strtotime('now') from the timer to see how many seconds are left
// until the player is released from the hospital

$timer = $timer - strtotime('now');
// Lets just say that 2 minutes have passed, the $timer should now be with a result
// like 1680 or something,

?>

My question is, how to split that timer to minutes and seconds? I want to split the 1680 seconds that remain to minutes and seconds. Thanks anyways.

A: Since you're storing hospitaltimer as seconds from the unix epoch, substracting both strtotime figures would then be converted to a date that's, for example, 1680 seconds after the unix epoch. Not what you're looking for.
I'd suggest approaching this by storing the "exit time" in yyyy-mm-dd format
a.- You'd need to alter your table and convert hospitaltimer to a DATETIME field. that's pretty straight-forward
b.- change your code to store the hospitaltimer value as a yyyy-mm-dd hh:mm:ss like this:
$current_time = date('Y-m-d H:i:s', strtotime('now') + 1800); // This variable goes to the database
and then change the logic to show the remaining time:
$timer = date_create($result[0]['hospitaltimer']); // the "exit time" you inserted
$now = date_create(date('Y-m-d H:i:s'));

$diff = date_diff($timer,$now)->format('%r%i minutes %s seconds');

if ($diff < 0)
{
    echo "out";
}

else
{
    echo $diff." before being able to leave";
}

Alternatively, substracting the output of different strtotime() operations would be a non-standard way to calculate dates which you could work around by:
$timer = $timer - strtotime('now');
// now the timer reads 1680 per your example

$seconds = $timer % 60; // use modulo 60 to calculate seconds remaining after dividing seconds by 60 and retrieving the integer part of the result

$minutes = ($timer - $seconds) / 60; // from full timer, substract the seconds and the remaining amount, divided by 60 is converted to minutes

Both of these alternatives would work, but the benefit of storing the hospitaltimer as a timestamp is that at any given point you could easily query the table to find out how many users are still hospitalized (for example) by simply using a where hospitaltimer > now()


Q: Quarkus and JDBI integration: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] I'm trying to use Quarkus and JDBI — not so many examples on this out there I would say :/
The Gradle script has these dependencies:
dependencies {
  implementation(enforcedPlatform("io.quarkus:quarkus-universe-bom:2.1.3.Final"))
  implementation(enforcedPlatform("org.jdbi:jdbi3-bom:3.21.0"))

  implementation("org.jdbi:jdbi3-core")
  implementation("org.jdbi:jdbi3-sqlobject")

  runtimeOnly("io.quarkus:quarkus-config-yaml")
  runtimeOnly("io.quarkus:quarkus-flyway")
  runtimeOnly("io.quarkus:quarkus-jdbc-h2")
  ...
}

I have a class to configure (and integrate) JDBI:
@ApplicationScoped
public class PersistenceConfig {
  @Inject
  DataSource dataSource;

  @Singleton
  public Jdbi jdbi() {
    return Jdbi.create(dataSource)
        .installPlugin(new SqlObjectPlugin());
  }

  @Produces
  public ActorRepository actorRepository(final Jdbi jdbi) {
    return jdbi.onDemand(ActorRepository.class);
  }
}

And I think the problem is somehow within that one (and the datasource), because I'm currently getting this error when starting the application:
2021-08-27 11:31:32,852 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

    at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:415)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:275)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:66)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.firstStart(IsolatedDevModeMain.java:91)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:424)
    at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:64)
    at io.quarkus.bootstrap.app.CuratedApplication.runInCl(CuratedApplication.java:136)
    at io.quarkus.bootstrap.app.CuratedApplication.runInAugmentClassLoader(CuratedApplication.java:93)
    at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:145)
    at io.quarkus.deployment.dev.DevModeMain.main(DevModeMain.java:63)
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors

    [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

    at io.quarkus.builder.Execution.run(Execution.java:116)
    at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79)
    at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:151)
    at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:413)
    ... 9 more
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259)
    at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
    at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at java.base/java.lang.Thread.run(Thread.java:829)
    at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]

    - java member: org.acme.config.PersistenceConfig#dataSource
    - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
    at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
    at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463)
    at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247)
    ... 13 more

I can't fully comprehend why the datasource cannot be injected since I already have it configured in the YAML file:
quarkus:
  datasource:
    db-kind: "h2"
    jdbc:
      url: "jdbc:h2:mem:java_quarkus_graphql;DB_CLOSE_DELAY=-1;MODE=PostgreSQL"
    username: "sa"
  flyway:
    clean-disabled: true
    locations: "classpath:database/migration"
    migrate-at-start: true
    validate-on-migrate: true

I read the guide around this subject and it should be available as AgroalDataSource — or just DataSource.

UPDATE #1
By the way, this setup/configuration works if I use an older version (1.13.4.Final) of Quarkus:
> Task :quarkusDev
Listening for transport dt_socket at address: 5005
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2021-08-27 12:55:39,840 |- INFO  in io.quarkus:88 [Quarkus Main Thread] - java-quarkus-graphql 0.1.2-SNAPSHOT on JVM (powered by Quarkus 1.13.4.Final) started in 0.770s. Listening on: http://localhost:8080
2021-08-27 12:55:39,843 |- INFO  in io.quarkus:91 [Quarkus Main Thread] - Profile dev activated. Live Coding activated.
2021-08-27 12:55:39,843 |- INFO  in io.quarkus:92 [Quarkus Main Thread] - Installed features: [agroal, cdi, config-yaml, flyway, hibernate-validator, jdbc-h2, mutiny, narayana-jta, smallrye-context-propagation, smallrye-graphql]

UPDATE #2
Version 2.2.1.Final doesn't have the issue when starting the application, but somehow it fails when running the test cases:
@Stereotype
@QuarkusTest
@Transactional
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface QuarkusTransactionalTest {
  // ...
}

@QuarkusTransactionalTest
final class ActorRepositoryTest {
  @Inject
  ActorRepository repository;

  @Test
  void findById_WhenActorDoesNotExist() {
    Assertions.assertThat(repository.findById(UUID.fromString("c6b1d415-77ee-49c2-b912-fbd00e07702b"))).isNotPresent();
  }

  @Test
  void findById_WhenActorExist() {
    Assertions.assertThat(repository.findById(UUID.fromString("3bea7318-bb7a-4232-9343-59579dd5b2a2")))
        .contains(ActorFactory.penelopeGuiness());
  }
}

ActorRepositoryTest > findById_WhenActorExist() FAILED
    java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
        [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
        - java member: org.acme.config.PersistenceConfig#dataSource
        - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
        at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1100)
        at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:265)
        at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129)
        at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820)
        at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
        at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
        at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
        at java.base/java.lang.Thread.run(Thread.java:829)
        at org.jboss.threads.JBossThread.run(JBossThread.java:501)
    Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default]
        - java member: org.acme.config.PersistenceConfig#dataSource
        - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig]
        at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492)
        at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:471)
        at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:253)
        ... 13 more

A: yes , it works with AgroalDataSource

A: Fixed with latest (2.2.3.Final) version.


Q: Sorting list with searched input string I am working on a Parse/Android application in which I am getting array list of objects from the server, for example Apple, Banana, Carrot, Dino etc which I am displaying in my Adapter.
Now I want to make a search thing on my list, if I press any alphabet it will show the items according to those characters, for example: if I press "A" so it will show me : Apple, Apricot etc and do not show any other.
My code is given below:
// mItems is my arraylist of objects with "title" object.
mItems = (ArrayList<ParseObject>) objects;
mAdapter = new GenericAdapter<ParseObject>(getApplicationContext(),
mItems,R.layout.listview_dical_assist,mNotificationsBinder);
mListView.setAdapter(mAdapter);

My autoComplete editField where I want to make that sorting list thing.
autoComplete.addTextChangedListener(new TextWatcher() {

              @Override
              public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

               // I need to put that search query here user press any character

               adapter.notifyDataSetChanged();
              }

              @Override
              public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                      int arg3) {
                  // TODO Auto-generated method stub

              }

              @Override
              public void afterTextChanged(Editable arg0) {
                  // TODO Auto-generated method stub

              }
          });


Q: BigQuery Regex to extract string between two substrings From this example string:
{&q;somerandomtext&q;:{&q;Product&q;:{&q;TileID&q;:0,&q;Stockcode&q;:1234,&q;variant&q;:&q;genomics&q;,&q;available&q;:0"}

I'm trying to extract the Stockcode only.
REGEXP_REPLACE(col, r".*,&q;Stockcode&q;:/([^/$]*)\,&q;.*", r"\1")

So the result should be

1234

however my Regex still returns the entire contents.

A: use regexp_extract(col, r"&q;Stockcode&q;:([^/$]*?),&q;.*")
if applied to sample data in your question - output is


Q: cannot get opengraph to scape url I know this is a pretty common problem but any of the solutions I have tried (thats a lot) haven't worked.
I am trying to scrape http://residencyradio.com/ using https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fresidencyradio.com%2F
The site itself is getting a complete overhaul, this will be revealed next week and I want the relevant images, title and info to appear if someone links to the site, but instead at the moment these properties are being shown as they were the very first time the site was cached on FB (nearly a year ago).
As far as I can see, I have included all the relevant meta tags etc how they should be, I even tried implementing a like button on the site, but to no avail. I have followed what has been set out on: http://ogp.me/ and can't see anything wrong.
Here is a sippet of the page from !DOCTYPE to </head>:
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset=utf-8>
<title>The Residency</title>

<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
    </script>
<![endif]-->
<link href="css/reset.css" rel="stylesheet" type="text/css" />
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="icon" type="image/png" href="images/favicon.png" />

<!--Meta Data-->
<meta name="keywords" content="The Residency, M. Budden, Neal McClelland, Michael Budden, Radio, Residency Radio,
Residency, Global, House, Electro, Progressive, Tech, Techno, DnB, Drum and Base, Dubstep, iTunes, Belfast,
Northern Ireland, UK" />
<meta name="description" content="Brought to you by Neal McClelland and M. Budden, The Residency is a weekly global underground dance show" />
<meta property="og:title" content="The Residency A global underground dance show" />
<meta property="og:type" content="musician" />
<meta property="og:url" content="https://www.facebook.com/theresidency" />
<meta property="og:image" content="https://www.residencyradio.com/images/Residency_logo_circle.png" />
<meta property="og:site_name" content="The Residency" />
<meta property="fb:admins" content="1324839758" />

Any help would be greatly appreciated, as I've been scratching my head for a few days trying to figure it out!
Thanks in advance!

A: This is a guess, but your html is not valid and maybe because of that the facebook scraper fail to parse and extract the data from it.
I haven't went through all of it, but you don't seem to close all tags.
For example the description and keywords meta tags don't end with "/>" or ">".

Edit
Screen capture of what the debugger shows when I load your html from my server:


Q: Is there a nice way to tell jQuery to not eval scripts on ajax requests that are HTML I'm using jQuery to make an ajax request, and everything is working as expected.  But it's evaluating the scripts in the wrong context.
I have an iframe (same domain, no worries here), and I'm trying to get the scripts to eval in the context of the iframe, instead of where the ajax request was made -- eg. a different frame.
I figured I could tell ajax not to eval the scripts, and I would do the work myself to eval them in the right context.  Any ideas, or ways to disabled the automatic eval?
Edit
So, I was somewhat wrong about the initial question.. The scripts are not evaluated when loaded, but rather when the content is being placed in the document.  You can see this by testing the example:
$('#some_element').html('content');

Now, when doing this from a different frame, the evaluation happens in the scope of where you're calling, not the element you're inserting content into.
I ended up setting the content without using jQuery, and then finding/evaling any script tags:
element.get(0).innerHTML = data;
element.find('script').each(function() {
  otherWindow.eval(this.innerText);
});

Final Update
I ended up tracking it down to the source, and overriding it from there.. the following is coffeescript, but you can get the idea.  I chose to override it because for my usage, this should never happen in the top window, but is expected in the iframe content.
    $.globalEval = (data) -> (iframeWindow.execScript || (data) -> iframeWindow["eval"].call(iframeWindow, data))(data) if (data && /\S/.test(data))

A: This questions shows how to do custom eval of the scripts:
jQuery: Evaluate script in ajax response
In the following piece of code...  ** this code is from the answer of the other question ** just got it as a snippet:
  $("body").append($(xml).find("html-to-insert").eq(0));
  eval($(xml).find("script").text());

eval itself is bound to a window, that you can define to be the context:
windowObject.eval - when calling just eval('...'), it supposes you are calling just like this: window.eval('...')
Now you need to get the window that corresponds to the frame you want to execute the eval in and do something like this:
myIFrameWindow.eval('...')
When you do this, it is execute in the context of that window. It is just a matter of finding the window associated with the iframe that you want now.
To find the window of a given frame, take a look at this post:
Getting IFRAME Window (And Then Document) References With contentWindow


Q: Ignore adapter creation when adaptee already of correct type I have the following setup:
class Target(Base):

  def __init__(name: str):
    self.name = name

class Adapter(Target):

  def __init__(self, adaptee: Base, name: str):
    super().__init__(name=name)
    self.adaptee = adaptee

def as_target(adaptee: Base, name: str):
  if isinstance(adaptee, Target):
    return adaptee
  else:
    return Adapter(adaptee, name)

I am wondering if I could get rid of as_target function and instead handle the logic on adapter creation.
Semantically, it would have the following meaning:
class Adapter(Target):

  def __init__(self, adaptee: Base, name: str):
    if isinstance(adaptee, Target):
      self = adaptee
    else:
      super().__init__(name=name)
      self.adaptee = adaptee

I've tried playing around with overriding __new__ but I wasn't able to make it work.

A: class Base:
    pass

class Target(Base):
    def __init__(self, name: str):
        self.name = name

    def __repr__(self):
        return "{}({})".format(type(self).__name__, repr(self.name))

class Adapter(Target):
    def __new__(cls, adaptee: Base, name: str):
        if isinstance(adaptee, Target):
            return adaptee
        else:
            return super().__new__(cls)

    def __init__(self, adaptee: Base, name: str):
        super().__init__(name=name)
        self.adaptee = adaptee

print(Adapter(Base(), "a"))  # Adapter('a')
print(Adapter(Target("b"), "c"))  # Target('b')


Q: Generate Permutations - Swap Function I'm going thru the EPI book and adapting the solutions in Go. I don't understand the solution for "generating permutations". Below is my implementation in Go (which works correctly):
    func permutations(A []int) [][]int {
    result := [][]int{}
    var directedPermutations func(i int)
    directedPermutations = func(i int) {
        if i == len(A)-1 {
            B := make([]int, len(A))
            copy(B, A)
            result = append(result, B)
            return
        }
        for j := i; j < len(A); j++ {
            A[i], A[j] = A[j], A[i]
            directedPermutations(i + 1)
            A[i], A[j] = A[j], A[i]
        }
    }
    directedPermutations(0)
    return result
}

Below is the result:
16.3_generate_permutations$  go run main.go
input:  [1 2 3]
[[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]

Specifically, I'm confused as to why the values are swapped before and after the recursive case. I've stepped thru with a debugger and see that for each successive call values are swapped to generate the permutation.
Is the swap before recursive case and swap back afterwards a common pattern?


Q: Only insert new rows in SQLIte with pandas to_sql() I've got a dataframe in Pandas and I want to export the dataframe to sqlite with the pandas function to_sql(), the problem I've got is that function only admit remplace or append values, and I can not export just by inserting new rows.
to_sql() function:
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’

How to behave if the table already exists.

    fail: Raise a ValueError.
    replace: Drop the table before inserting new values.
    append: Insert new values to the existing table.

Is there an option to do that?


Q: Update React [Native] View on Day Change I'm working on a React Native component that should update itself when the day changes, even when the user hasn't interacted with the view.
Is setInterval the only way to deal with this? If I call setTimeout in viewDidLoad specifying the number of ms until the next day, won't the interval be inaccurate if the app gets paused? Alternatively, I could run a periodic timer, but I'd need to give it a short interval so that there's not an apparent delay when the day changes -- seems pretty inefficient.
Am I missing something?

A: I suppose this is more of a general app architectural concern. The simplest answer is you should take the current time in seconds (new Date().getTime()), determine how many seconds there are until the next day, and set a timer for that number.
However, as you mentioned, once the app is killed, that timer will no longer be accurate.
You should use AppStateIOS to listen for when the app is backgrounded and foregrounded. Upon being sent to the background, clear the timer. Upon being brought to the foreground, run the original calculation again and generate a new timer.
Unfortunately there is no equivalent functionality on Android as of yet.

A: You can use react-native-midnight which subscribes to native APIs and fires event listeners when the day has changed from either a timezone change or crossing the midnight threshold.


Q: Error messages are not displayed using jQuery Validate I have the following jQuery script.
function updateItem(form) {
    var validator = $("#add-experience-form").validate({
        debug: true,
        rules: {
            eventTitle: {
                required: true
            }
        },
        messages: {
            eventTitle: {
                required: "Please, enter a title."
            }
        }
    });

    if (!validator.valid()) {
        return;
    }

}
Here's the HTML:
<form action="/User/AddExperience" id="add-experience-form" method="post" novalidate="novalidate">

        Experience Title*
        <input id="eventTitle" name="eventTitle" required="required" style="width: 350px;" type="text" value="">

         50 character maximum

                    {

                        Experience Title

                        @*@
                         50 character maximum

For some reason error message doesn't display for the above form even though validator.valid() evaluates to false.
If it helps, I put this form inside jQuery UI dialog, but I don't think it really matters.
Any ideas?

A: To validate html forms , the simplest way is to combine two open source powerful frameworks twitter bootstrap ( to get nice form ) and jquery.validate.js plugin ( for validation ).
Bootstrap framework : http://getbootstrap.com/getting-started/ .
Jquery validation plugin : http://jqueryvalidation.org/
So your html code and your script may appear like this
Html code :
First add this link
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">

Then
<form  method="post" action="/User/AddExperience" id="add-experience-form" class="form-horizontal">
    <fieldset>

fields required *

            Experience Title*

              <input type="text" class="form-control" id="eventTitle" name="eventTitle">

                <input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">

    </fieldset>

</form>

Jquery script : put it in a js file called validate.js
$(document).ready(function(){

jQuery.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-z]+$/i.test(value);
});

$('#add-experience-form').validate({
    rules: {
        eventTitle: {
            minlength: 2,
            lettersonly:true,
            required: true
        }
    },

    messages: {

        eventTitle: {
            required:"blablabla",
            minlenght:"blablabla",
            maxlenght:"50 character maximum",
            lettersonly: "Letters only please"
        }
    },

    highlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('error').addClass('success');
    },
    success: function (label) {
        $(label).closest('form').find('.valid').removeClass("invalid");
    },
    errorPlacement: function (error, element) {
        element.closest('.control-group').find('.help-block').html(error.text());
    }
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file

});
You can put all these scripts in one folder called js then add them in your code

For more details you can refer to the documentation http://jqueryvalidation.org/documentation/


Q: How to redirect from one servlet to another by using tricky redirection? If I have two servlets:
@WebServlet (urlPatterns = {"/s1"})
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 100);
        map.put("B", 200);
        map.put("C", 300);

        req.setAttribute("map", map);
        getServletContext().getRequestDispatcher("Servlet2").forward(req, resp);
    }
}

public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        Map map = (Map) req.getAttribute("map");

        for (Object o : map.values()) {
            System.out.println(o);
        }
    }
}

How can I make redirect between them? And which path I need to use in my getRequestDispatcher method? And one more condition - Servlet2 must be without any mapping in annotations or in web.xml.

A:
Servlet2 must be without any mapping in annotations or in web.xml.

Then you cannot use HttpServletRequest#getRequestDispatcher(String), which is a container managed method that checks those mappings.
That condition is ridiculous and makes no sense. If you aren't going to use the Servlet container, don't make a Servlet. Make a service class that performs the actions you need. You don't need to make everything a Servlet.
Your only (ridiculous) alternative is to instantiate Servlet2 and explicitly invoke its doGet method.


Q: Move factory method from AppModule to AppComponent in Angular 7 I use ngx-translate-multi-http-loader loader to create specific translations. The documentation requires that this factory has to be created within the app.module.ts:
export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  return new MultiTranslateHttpLoader(http, [
    {prefix: './assets/i18n/default/', suffix: '.json'},
    {prefix: './assets/i18n/bc/', suffix: '.json'}
  ]);
}

This factory is configured inside the import arrays in this way:
TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: multiTranslateHttpLoaderFactory,
    deps: [HttpClient]
  }
}),

I need a way to put the factory into my app.component.ts, because I still have to program some logic and do not want to do that within my app.module.ts.
But if I move the method into my app.component.ts and make all the necessary import statements on top of the file, angular doesn't compile and returns this error message:

ERROR in src / app / app.module.ts (55,21): error TS2304: Can not find
  name 'multiTranslateHttpLoaderFactory'.

Is there a possibility or do I really have to define the factory within app.module.ts ???

A: It really should not matter where you define your factory, or any other function for that matter. Just be sure to import it correctly, somewhere in the top of app.module.ts
import {multiTranslateHttpLoaderFactory} from 'path/to/your/component'


Q: super priviliege not set for master user in aws rds mysql I have created an AWS RDS instance, I have created my master user with master password, and it is working/connecting fine.
But when I am going to create a function on that instance, it shows me the following error:
ERROR 1418: This function has none of DETERMINISTIC, NO SQL,
or READS SQL DATA in its declaration and binary logging is enabled
(you might want to use the less safe log_bin_trust_function_creator variable).

In my instance the variable log_bin_trust_function_creators shows OFF, and if I try to change the variable using SET GLOBAL log_bin_trust_function_creators = 1;, it gives me another error "Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation"

A: Set log_bin_trust_function_creators = 1 for Parameter group of the RDS instance.
Note: Default Parameter-Group is not editable. Create a new Parameter-Group and assign it to the RDS instance by modifying it from UI (AWS Admin Console) OR maybe using commands
DELIMITER $$
CREATE DEFINER=`DB_USERNAME_HERE`@`%` FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120)) RETURNS decimal(12,8)
READS SQL DATA
BEGIN
   DECLARE distance DECIMAL(12,8);
   /*Business logic goes here for the function*/
   RETURN distance;
END $$
DELIMITER ;

Here, you have to replace DB_USERNAME_HERE with you RDS database username and function names according to you need.
Important thing is: DEFINER=`DB_USERNAME_HERE`@`%`
This was the problem I was facing after setting log_bin_trust_function_creators = 1 in parameter group. And it worked like a charm.

A: A better way is to apply your own parameter group, with log_bin_trust_function_creators set to true. (its false by default)

A: This happens when you try to create a procedure/function/view with a DEFINER that is not the current user.
To solve this remove or update the DEFINER clause.


Q: How to call a function when pressing the default react native picker in react native I'm using react-native picker in dialog mode. Now I want to call a function whenever the dialog opens. How can I achieve that because there is no onPress prop? Any help will be appreciated. Please don't recommend any other packages because I want to use the default one.

A: You can achieve it without using Picker, use TouchableOpacity to call a function, and in the same function just open a Modal for showing the list of items of Picker and close the Modal when selecting any item from the list.


Q: WMS/WFS server: am I crazy to write my own? I'm a "do it yourself" kind of guy, but I want to make sure I'm not going to do myself in by trying to bite off more than I can chew.
I am writing a browser-based mapping application that needs to have the option to run standalone (no internet connection) on the end-user's machine. That is, the application is some kind of server that will, in many cases, get installed on the end user's machine and the browser will point to some localhost URL to access it.
I will be using MapLayers on the client side, and the server side will have a bunch of custom logic specific to the application, such as handling click events on the map in certain custom ways, creating various custom objects on the map at certain times, and so on.
For the "business logic" part of the server, I'm happy using paste/webob with python. It's a simple infrastructure that lets me put all this custom logic in easily.
I had been thinking that the client would communicate with two servers: this paste/webob business logic server, and a server just for serving WMS and WFS map elements. So I was looking at MapServer and GeoServer to handle the map parts and ... I'm not happy.
I'm not happy because I don't want to have to install and worry about a "beast" on the client machines. For MapServer, I don't really want to install a full-blown web server like Apache, and have to deal with CGI and PHP and MapScript. For GeoServer, there's (potentially) installing Java, and dealing with various complexities of the GeoServer setup and administration.
Part of this is simply a learning curve issue. If I can avoid it, I'm not especially interested in learning the intricacies of either MapServer or GeoServer. I installed GeoServer, pointed it to some of my data, and was able to use the MapLayers preview built into GeoServer's nice web admin to view my data. But when I tried to serve the data for real using my own MapLayers web page pointed at GeoServer, I crashed GeoServer. That I could crash the server just be sending some presumably malformed requests from the client was quite surprising to me. And I could dig into the GeoServer logs to try to figure out what I did wrong, but ... I don't really want to spend a lot of time on that.
So, I am considering implementing parts of the WMS and WFS interface myself just using the paste/webob server I already have. It may in fact be that I only need the WMS, since I might handle vector objects through a simple custom protocol that I make to pass data to the client, which can then create and manipulate the objects directly using OpenLayers.
I've looked at the specs and example messages for WMS (and a bit less at WFS). It seems not so difficult just to implement this protocol myself, especially because I have full control of the client in this case -- it's not like I need to be able to act as a generic WMS or WFS server; I just have to make my own OpenLayers client happy.
The two main abilities that I need the WMS server to have are:

*

*Serve tiles from a store of prerendered tiles that I've created ahead of time (I'll prerender the tiles using OpenStreetMap data and mapnik as the redering engine; and I'll store and access them using the normal Google Maps style tile naming scheme that OpenLayers expects)

*Have the ability to server modified versions of these tiles where certain data that I store locally is drawn on top of the tiles. For instance, I might have, say, 10000 points on one "layer" and 10000 polygons on another layer, and when the user activates these layers I will serve my same base tiles, but as I'm serving these tiles I'll render these additional features on top of them, and probably I'll implement a simple caching scheme to keep these over-rendered tiles around for some amount of time.
So my question is: Even though I know there are existing tools that do these things (MapServer, GeoServer, TileCache, and others), I'm actually feeling like it's less work for me to just to respond to some simple WMS messages, and do this additional over-drawing on my tiles myself in python, making sure everything is projected correctly, etc. I don't need to draw fancy wide streets or anything for these over-layers, just simple lines, icons, and perhaps labels. It sure sounds nice and simple to have a python-only solution.
I figure if I ever need to expand into supporting more of the WMS/WFS protocol, or doing fancier overdrawing, I can just insert MapServer/GeoServer at that time.
Are there pitfalls here I'm not considering?

A: Mapserver is very easy to setup and learn. Implementing any kind of rendering by yourself is going to require much more effort, and you will probably find a lots of unexpected traps.
mapserver cgi should be enough for your needs. If you require some very specific tweak, then mapscript can be useful.
I think it could be interesting if you could make a pure JavaScript application, and save yourself from installing a web server (and a map server). If you just needed browsing a tile mosaic, may be you could do it just with JavaScript (generate an html table with a cell for each tile). You can render points or polygons, with JavaScript, using a canvas and doing some basic coordinate conversion to translate geographic points to pixels. Openlayers have this functionality, I think.
EDIT: I just checked and with Openlayers you can browse local tiles, and you can render kml and some other vect data. So, I think you should give Openlayers a try.

A: No need to have a wms/wfs. What you need is a tile implementation. Basically you should have some sort of central service, or desktop service that generates the tiles. Once these tiles are generated, you can simply transform them to your "no-real-webserver-architecture" filesystem. You can create a directory structure that conforms to /{x}/{y}/{z}.png and call it from javascript.
An example of how openstreetmap does this can be found here: http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example

A: You may like featureserver: http://featureserver.org/.
It has its own WFS. I am using it right now.


Q: Oracle APEX: Text wrapping issue with a display-only page item I have a display-only page item on an inline dialog region. The value of the item is set via hidden page item that retrieves the value from the database using PL/SQL.
The issue is that the text is rather long, so instead of text wrapping, it extends beyond the width of the inline dialog causing a horizontal scroll bar to appear. How can I set the width of the page item to be no wider than the inline dialog default width and make the page item text wrap around?

A: Did you try to

*

*set display only item's template to "optional" (instead of e.g. "optional - floating"), and then

*set its "custom attributes" property (which is in the "Advanced" set of properties) to e.g. style="width:300px"
Illustration:


Q: SharePoint Visual Studio Build - error : '.', hexadecimal value 0x00 When I deploy my SharePoint project I receive the following error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets(375,5): error : '.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.

The line number relates to the following in the build XML:
<CreateSharePointProjectService Configuration="$(Configuration)"
              Platform="$(Platform)"
              ProjectFile="$(MSBuildProjectFile)"
              ProjectReferences="@(SharePointProjectReference)"
              OutDir="$(TargetDir)">
  <Output PropertyName="ProjectService" TaskParameter="ProjectService" />
</CreateSharePointProjectService>

Furthermore I've managed to whittle down the problem (or at least seemingly) to the following property:
ProjectFile="$(MSBuildProjectFile)"

i.e. if I remove this property then I no longer get the same error message (but I get others as a consequence).
I'm not sure what's going on here as I know nothing about MSBuild.  Obviously this always used to work before so I don't know what's changed to cause it to no longer work.  Any suggestions will be greatly appreciated as I've wasted a lot of time on this already.  BTW, this problem occurs in both Visual Studio 2010 and 2012.
Thanks

A: OK, problem sorted.  It turns out that the error message actually referred to an XML file referenced by the solution (containing some deployment files).  This XML had somehow become corrupted which does fit the message '.', hexadecimal value 0x00.  After removing this feature (which didn't need deploying anyway) the problem disappeared so the world can go on being a happy place again (or at least my manager is!)

A: I just ran into this after downloading an msbuild file from the internet.  Opening the newly downloaded file in a hex editor showed me what the problem was pretty quickly.  The file was downloaded with 2 byte characters, and every other byte was a 0.  I think Notepad++ said the encoding was UCS-2.  In any case, the fix was pretty simple.  Notepad++ has an Encoding menu option that I used to rewrite the file as UTF-8.  Changing the file back to UTF-8 immediately fixed the problem.
Hope this helps people in the future.
--Addendum - I might have tried to muck with the file using PowerShell before its encoding changed.


Q: How is arctangent [function a()] implemented in bc? I wanted to see and possibly modify how the arctangent function a() was implemented in bc (the arbitrary precision calculator language) but was unable to find it. I even found a git repo of the project https://github.com/gavinhoward/bc, however was unable to locate the implementation code for it. This should be part of the matlib library for bc.
Please share link, location of the directory or source code below.


Q: Using mapply to plot I'm trying to iteratively plot scatterplots ONLY using mapply.
Let's say I have the iris dataset:
> names(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length"
[4] "Petal.Width"  "Species"

I would like to use mapply() and only mapply() to plot Sepal.Width, Petal.Length, and Petal.Width against Sepal.Length
I have this starter code:
    mapply(function(ii){plot(x = iris[["Sepal.Length"]],
           y = ii, ylab = paste(names(ii)), xlab = "Sepal Length")},
           ii = iris[c(2,3,4)])

Everything works fine here EXCEPT the y axis labels. I want it to display the column names of the y-axis values, but this does not work.

A: Neither mapply nor lapply pass the names of the items in their data objects to the "working functions". What you see after the function completion is that they add back the names to the results. Even if you use the deparse(substitute)) strategy you end up with a useless name like "dots[[1L]][[1L]]". So you are condemned to either index by the names themselves or by a numeric index into the names(dataframe) values.

A: Consider passing column names to fit your column assignment and ylab character requirement. And as @alistaire comments, you are only passing one vector into your function. Mapply (informally as multivariate apply) is designed to iterate elementwise through more than one equal-length or multiple-length vectors. This would be akin to passing in Sepal.Length 1 or 3 times:
plotfct <- function(ii, jj)
  plot(x = iris[[ii]], y = iris[[jj]],
       xlab = paste(ii), ylab = paste(ii))

mapply(plotfct, c("Sepal.Length", "Sepal.Length", "Sepal.Length"),
                c("Sepal.Width", "Petal.Length", "Petal.Width"))

But since Sepal.Length does not change, repeating its value to meet the length of longer is redundant. Simply use lapply or its simplified wrapper, sapply:
plotfct <- function(ii)
  plot(x = iris[["Sepal.Length"]], y = iris[[ii]],
       xlab = "Sepal Length", ylab = paste(ii))

lapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)

# EQUIVALENTLY:
# sapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)


Q: paginated calls on a service method without changing signature of original method I have a use case where I need to add pagination inputs (viz. page number and page size) to existing service calls (that returns a list of results) without changing the existing signature (because it will break existing clients). One way of achieving this is that we set the inputs in a threadlocal and have the implementation read the threadlocal and do its pagination logic. From a code point of view, it would look something like:
try {
    PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
    List<SpecialObject> results = specialService.getSpecialObjs(); //results count will be equal to pageSize value
} finally {
    PaginationKit.clearPaginationInput(); // Clear threadlocal
}

From a client's point of view, this is not at all elegant and I wanted to wrap this functionality into some better syntactic sugar. There were two approaches I had in mind and I wanted to know if this is a generic enough use case that has been solved as a pattern elsewhere. There are many such services and trying to put up a decorator for each of the services is not desirable.
Approach 1:
I like the mockito style of Mockito.when(methodCall).thenReturn(result) kind of sugar.
So the code may look like:
SpecialService specialService = PaginationDecorator.prepare(SpecialService.class); // Get a spy that is capable of forwarding calls to the actual instance
List<SpecialObject> results = PaginationDecorator.withPageSize(pageSize).onPage(pageNumber).get(specialService.getSpecialObjs()).get(); // The get() is added to clear the threadlocal

I tried to borrow code from Mockito to create the spy, but the OngoingStubbing<T> interface is quite intertwined in the subsequent call chaining/creation code and is smelling of something that I should avoid.
Approach 2:
Use java.util.Function to capture the method call and accept two additional parameters pageNumber and pageSize to play with the threadlocals. The code may look like
List<SpecialObject> results = PaginationDecorator.withPaging(specialService.getSpecialObjs(), pageSize, pageNumber);

PaginationDecorator.java:
public static List<T> withPaging(Function<U, List<T>> call, int pageSize, int pageNumber) {
    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.apply(); // Clearly, something is missing here!
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

I am not able to clearly formulate how to use call correctly here.
Can someone please tell me :

*

*which of these two is the better approach

*if this is available as a recipe elsewhere using a different approach

*suggest ways forward to implement approach 1 or 2. Personally #2 seems cleaner to me (if it works).

Feel free to critique the approach and thanks in advance for the read!
P.S.: I also liked the iterator recipe in this question, but the primary problem of syntactic sugar is still desired.

A: Your second variant does not work, because you are using the wrong interface (Function expects an input argument) and no syntax to create a function instance, but just an ordinary invocation expression.
You have several choices

*

*Use Supplier. This interface describes a function without parameters and returning a value.
public static <T> T withPaging(Supplier<T> call, int pageSize, int pageNumber) {
    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.get();
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

Instead of insisting on it to return List<T>, we simply allow any return type which raises its versatility. It includes the possibility to return a List of something.
Then, we may use either, a method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
                    specialService::getSpecialObjs, pageSize, pageNumber);

or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
                    () -> specialService.getSpecialObjs(), pageSize, pageNumber);

*Stay with Function, but allow the caller to pass the required argument
public static <T,R> R withPaging(
    Function<T,R> call, T argument, int pageSize, int pageNumber) {

    try {
        PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
        return call.apply(argument);
    } finally {
        PaginationKit.clearPaginationInput(); // Clear threadlocal
    }
}

Now, the caller has to provide a function and a value. Since the intended method is an instance method, the receiver instance can be treated like a function argument
Then, the function might be again specified either, as a (now unbound) method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
        SpecialService::getSpecialObjs, specialService, pageSize, pageNumber);

or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
        ss -> ss.getSpecialObjs(), specialService, pageSize, pageNumber);

*There is an alternative to both, resorting to AutoCloseable and try-with-resource, rather than try…finally. Define the helper class as:
interface Paging extends AutoCloseable {
    void close();
    static Paging withPaging(int pageSize, int pageNumber) {
        PaginationKit.setPaginationInput(pageSize, pageNumber);
        return ()->PaginationKit.clearPaginationInput();
    }
}

and use it like
List<SpecialObject> results;
try(Paging pg=Paging.withPaging(pageSize, pageNumber)) {
    results=specialService.getSpecialObjs();
}

The advantage is that this will not break the code flow regarding your intended action, i.e. unlike lambda expressions you may modify all local variables inside the guarded code. Recent IDEs will also warn you if you forget to put the result of withPaging inside a proper try(…) statement. Further, if an exception is thrown and another one occurs inside the cleanup (i.e. clearPaginationInput()), unlike finally, the secondary exception will not mask the primary one but get recorded via addSuppressed instead.
That’s what I would prefer here.

A: Your second approach seems cleaner and easier for this task. As for implementation you can just use Java's Proxy class. It seems easy enough. I don't know any libraries that somehow make it even more easier.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class PagingDecorator {
    public static void setPaginationInput(int pageSize, int pageNumber) {
    }

    public static void clearPaginationInput() {
    }

    public static <T> T wrap(final Class<T> interfaceClass, final T object, final int pageSize, final int pageNumber) {
        if (object == null) {
            throw new IllegalArgumentException("argument shouldn't be null");
        }

        ClassLoader classLoader = object.getClass().getClassLoader();
        return (T) Proxy.newProxyInstance(classLoader, new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                setPaginationInput(pageSize, pageNumber);
                try {
                    return method.invoke(object, args);
                } catch (InvocationTargetException e) {
                    throw e.getTargetException();
                } catch (Exception e) {
                    throw e;
                } finally {
                    clearPaginationInput();
                }
            }
        });
    }

    public static <T> T wrap(final T object, final int pageSize, final int pageNumber) {
        if (object == null) {
            throw new IllegalArgumentException("argument shouldn't be null");
        }

        Class<?>[] iFaces = object.getClass().getInterfaces();

        //you can use all interfaces, when creating proxy, but it seems cleaner to only mock the concreate interface that you want..
        //unfortunately, you can't just grab T as interface here, becuase of Java's generics' mechanic
        if (iFaces.length != 1) {
            throw new IllegalArgumentException("Object implements more than 1 interface - use wrap() with explicit interface argument.");
        }

        Class<T> iFace = (Class<T>) iFaces[0];
        return wrap(iFace, object, pageSize, pageNumber);
    }

    public interface Some {
    }

    public static void main(String[] args) {
        Some s = new Some() {};

        Some wrapped1 = wrap(Some.class, s, 20, 20);
        Some wrapped2 = wrap(s, 20, 20);
    }
}

A: You are using Java 8, right? Maybe you can add a default method without any implementation (sounds a litte weird, I know) like this:
// Your current service interface
interface ServiceInterface <T> {

    // Existing method
    List<T> getObjects();

    // New method with pagination atributes
    default List<T> getObjects(int pageSize, int pageNumber) {
        throw new UnsupportedOperationException();
    }
}

The new services (with pagination suport) must override this method. In my opinion, this way You "keep it simple".


Q: Need Rally Burndown chart API implementation to show in our dashboard I am creating Dashboard(dashing.IO) in which i want to display the Rally Burn down chart.

A: You'll need to create your app in an html file and then embed it in an iframe element in a widget.
https://help.rallydev.com/apps/2.1/doc/#!/guide/embedding_apps
The burn down chart is accessible via the Standard Report component:
https://help.rallydev.com/apps/2.1/doc/#!/api/Rally.ui.report.StandardReport


Q: Vue.js - Data lost in karma/phantomjs tests I'm writting some unit tests for a Vue app. Everything is workign good when I try to test the DOM content, but I can't access the data of my components. In fact there is no data if I console.log my component $data property, it prints an empty object, no initially defined data or any other data. Just nothing.
Here is some code
some vue component
<template>
   <form @submit.prevent="saveAccount">
      Tipo de cuenta
        <select class="form-control" id="accountType" v-model="newAccount.type">
          <option v-for="type in accountTypes" v-bind:value="type.value">
            {{type.label}}
          </option>
        </select>
   </form>
</template>

My tests
  beforeAll(() => {
    vm = new Vue({
      template: '
<account></account>
',
      components: { account }
    }).$mount()
  })

  afterAll(() => {
    vm.$destroy(true)
  })

  it('account type', () => {
    // this pass
    expect(vm.$el.querySelectorAll('#accountType option').length).toBe(4)
    const options = vm.$el.querySelectorAll('#accountType option')
    // here accountTypes is undefined
    const accountValues = vm.accountTypes.map(type => {
      return type.value
    })
    options.forEach(option => {
      expect(accountValues.indexOf(option.value)).not.toBe(-1)
    })
  })

Some code is omitted. So, why is that my component data is empty but at the same time, properly rendered in the DOM?

A: After some try and error I found the answer and it's pretty obvious now. The thing is, that I was searching for data in the wrong place. The vmobject that I defined like this
vm = new Vue({
  template: '
<account></account>
',
  components: { account }
}).$mount()

Is a Vue instance that only have a component and a template option, the data I was searching for was in the child of that instance. So, I have to use this way to access data
const accountInstance = vm.$children[0]

This works, because to test I defined a single child easy to identify. I also tried before using const accountInstance = new account() but that throws an error because vue components ar not constructors