text:
Q: Find in All subkey of Object MongoDB I have this Document in mongodb
 {
    "name": "test2",
    "_id": "1502609098801598ffeca615f5d3dd09087c6",
    "events": {
        "0": {
            "delay": "0",
            "actionid": "2"
        },
        "1": {
            "delay": "0",
            "actionid": "3"
        }
    }
}

I want to find documents that contain event with specific actionid
i tried something like these but i can't find what i want
db.mycollection.find({ "events.$.actionid":"2" })
db.mycollection.find({ "events.$**.actionid":"2" })
db.mycollection.find({ "events.$": { $elemMatch: { "actionid":"2"} })

attention please: i can't change document structure and mongodb version is  3.0.6

A: We can take use of the aggregation feature within mongodb and project the object to an array
db.test.aggregate( [ { "$project" : { "events" : { "$objectToArray" : "$events" } } } ] )

after this we can just use the normal array filtering with a $match
db.test.aggregate([
    { "$project":
        { "events": {"$objectToArray": "$events"} } },
    { "$match":
        { "events.v.actionid" : "2" } } ] )

This will output the following:
{
        "_id" : "1502609098801598ffeca615f5d3dd09087c6",
        "events" : [
                {
                        "k" : "0",
                        "v" : {
                                "delay" : "0",
                                "actionid" : "2"
                        }
                },
                {
                        "k" : "1",
                        "v" : {
                                "delay" : "0",
                                "actionid" : "3"
                        }
                }
        ]
}
>

So you might want to project the document back to its orignial structure


text:
Q: Prompt user when url changes using react-router-dom Assuming I am within an edit form page that has the url route of /person/edit/123
Within my react app, I also have a website logo at the top left of my app that when clicked, returns the user to the url route /home
Using react-router-dom v6 or some other means, I need to be able to check that when a user is within an edit page and decides to click on the website logo, I need to prompt the user that changes have been made and provide some message that has a "Leave page yes/no dialog"
Unsure what approach to take inorder to accomplish the above.
I have seen other threads within SO but they are using older versions of react-router-dom.
Any guidance would be great.
UPDATE: Code used but didn't seem to work:
  useEffect(() => {
    window.addEventListener('beforeunload', function (e) {
      var confirmationMessage =
        'It looks like you have been editing something. ' +
        'If you leave before saving, your changes will be lost.';

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE
      return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    });
  }, []);

A: This demostrate a simplified version of a complex example to manually check for dirty forms, instead of relying on unload.
Considering you have a mechanism to check for dirty forms.
e.g.
const Component = ({ text }) => {
  const [ edited, setEdited ] = useState(text)

  const checkDirty = () => edited !== text

  return (... my form codes here...)
}

One of the solution is to create a CustomLink component. (psuedo code)
const CustomLink = React.forwardRef(({ onClick: dirty, href }, ref) => (

    const beforeHref = (e) => {
       e.preventDefault();
       if (typeof dirty == "function") {
          if (!dirty()) {
             return redirect(href)
          } else {
             if (confirm("Should we redirect!")) {
               return redirect(href);
             } else {
               return null
             }
          }
       }
       redirect(href);

    }
    // you should probably use the link component here
    return <a href={href} onClick={beforeHref} {...rest} />
));

Then in the page you can create a link like
<CustomLink href="/somepage" onClick={checkDirty} />

PS: Of course in the overall pages, you must pass those props to your menu, and your logo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a better email error in ZF2 using Forms I am wondering how to change the email error message returned from a form:

The error in the image is pretty ugly.
This is my form:
    $this->add(
        [
            'name'       => 'email',
            'type'       => 'email',
            'options'    => [
                'label' => 'E-Mail',
                'instructions' => 'Your email address'

            ],
            'attributes' => [
                'class' => 'form-element',
                'required' => 'required',
            ]
        ]
    );

Would be nice for the message to state: "That email is already registered" or "Email me@example.com is already in use"
How do you do this?

A: This is my way of validating emails for registration. It will strip all tags, trim the email, see if the input field is empty, if the email is at least 5 chars long and if the email contains only valid chars.
public function getInputFilterSpecification()
{
    return [
        [
            "name"=>"email",
            'required' => true,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
            "validators" => [
                [
                    'name' => 'EmailAddress',
                    'options' => [
                        'encoding' => 'UTF-8',
                        'messages' => ['emailAddressInvalidFormat' => "Email address doesn't appear to be valid."],
                    ],
                ],
                [
                    'name'    => 'StringLength',
                    'options' => [
                        'encoding' => 'UTF-8',
                        'min'      => 5,
                    ],
                ],
                ['name' => 'NotEmpty'],
            ],
        ],
     ];
}

If you simply want to check for existing email inside your database, I would suggest you to do this in your controller, when the form has been submitted and return error/success message depending if the email is there or not. For this you can try this code.
$email = 'me@example.com';
$emailQuery = $db->findEmail('email = ?', $email);
$validator = new Zend\Validator\Db\RecordExists(
    [
        'table'   => 'users',
        'field'   => 'email',
        'exclude' => $emailQuery
    ]
);

if ($validator->isValid($email)) {
    // email appears to be valid
} else {
    // email is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}


text:
Q: Django getattr() for related models I have a people class in my django project:
class People(models.Model):
   user        = models.OneToOneField(User, unique=True)
   adress      = models.CharField(max_length=500)

   def __unicode__(self):
    return "%s %s" % (self.user.first_name, self.user.last_name)
   def get_all_fields(self):
    return self._meta.fields + self.user._meta.fields

I created a view to export models from the django database into a csv file.
Of course it would be nice to export information of the related models e.g. the django-user too.
But when I loop over my peoples list with
people = People.objects.all()

for p in people:
row = ""
for field in p.get_all_fields():
     row     += str(getattr(p, field.name)) + ','

I got the error:   'People' object has no attribute 'password'
Of course it has not, but how can I use the foreign objects related to 'People' to get notified by getattr()?
EDIT
I finally wrote a small workaround by using some additional functions in my class
class People(models.Model):
   user        = models.OneToOneField(User, unique=True)
   adress      = models.CharField(max_length=500)

   def __unicode__(self):
      return "%s %s" % (self.user.first_name, self.user.last_name)

   def get_all_fields(self):
      return self._meta.fields + self.user._meta.fields

   def get_attribute(self, field_name):
      name_list = self.get_field_names()
      if field_name in name_list:
        return unicode(getattr(self, field_name))
      else:
        return unicode(getattr(self.user, field_name))

   def get_field_names(self):
      name_list   = []
      for field in self._meta.fields:
        name_list.append(field.name)
      return name_list

A: Maybe you could add this mixin to your People class:
class GetNestedFieldsMixin(object):
    link_fields = set((u"ForeignKey", u"OneToOneField"))

    @classmethod
    def _get_nested_fields(cls, obj):
        for field in obj._meta.fields:
            value = field.value_from_object(obj)
            is_link = field.get_internal_type() in cls.link_fields
            if is_link:
                nested_obj = field.rel.to.objects.get(pk=value)
                for name, field, value in  cls._get_nested_fields(nested_obj):
                    yield name, field, value
            else:
                yield obj._meta.object_name, field.name, \
                    field.value_to_string(obj)

    def get_nested_fields(self):
        return self._get_nested_fields(self)

class People(GetNestedFieldsMixin, models.Model):
    ...

for p in people:
    for model_name, field, value in p.get_nested_fields():
        print(model_name, field, value)

If the number of people gets bigger you should use .select_related to avoid database queries in the inner loop. And link_fields is probably not correct. It's just to give you an idea :).


text:
Q: wp category showing all posts from all categories instead of specific posts from specific category I'm building a site on wp and can't seem to get over this obstacle, when I go to a specific category archive page, it shows all the posts from all the categories instead of just the ones in that category... Wondering if anyone has can help me figure out how to limit the results to show just the posts from the category called.
Here's my category.php
<?php get_header(); ?>

                <?php
                    $the_query = new WP_Query( array(
                    'post_type' => 'post',
                    'orderby' => 'date',
                    'order' => 'DESC',
                    'posts_per_page' => 999)); // how many posts to show
                     $x = 0;

                 while ( $the_query->have_posts() ) :
                 $the_query->the_post(); ?>

                        <?php the_post_thumbnail('grid-image'); ?>

<?php the_title(); ?>

<?php the_excerpt(); ?>

                             <a href="<?php the_permalink(); ?>" class="info">Take Me To The Porn!

                    <?php $x++; ?>
                    <?php endwhile; ?>

                    <?php wp_reset_query(); ?>

            <?php get_template_part('sidebar'); ?>

<?php get_footer(); ?>

A: Since you are creating your own WP_Query you have to precise the actual filter you are using. For categories look at the relevant documentation here: http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
Note that if you are modifying the category.php template you are already inside the wordpress Loop and you do not need to specify your own WP_Query. You can simply use a
while(have_posts() ):
    ...
endwhile;

loop. I would recommend downloading the TwentyTwelve theme and observing its inner workings.


text:
Q: Adding a suffix at the end of each shell command Is it possible to automatically add some characters at the end of each command typed in the terminal.
For example, if I write
sudo apt-get update

the shell will execute
sudo apt-get update && notify-send Done

without me writing the && notify-send Done part.
Thanks in advance!

A: If you're using bash as your default shell, you can set PROMPT_COMMAND.
From the bash man page:
PROMPT_COMMAND
If set, the value is executed as a command prior to issuing each primary prompt.

So just paste the following line in your .bashrc to get a notification for each command:
PROMPT_COMMAND="notify-send Done"

So each time your bash prompt is called (normal behavior when a command is finished, with success or not), you'll get a notification.
Note: you'll be also notified if you press just Enter as the prompt will be displayed again.

A: You can bind some characters to to an enter key:
$ bind '"\C-M":" && echo test\n"'

This has some drawbacks, for example if you just press Enter:
-bash: syntax error near unexpected token `&&'

You can block this effect by terminating your lines with # character - it will turn appended text into a harmless comment.
Still I'd say that this sounds like a really bad idea.


text:
Q: Tesseract for WinRT UWP I need to use Tesseract on a Windows 10 app for phones. Already found an intent made by Yoisel . I've tried to build the project for test, but i'm kinda new to Visual Studio dependencies and usage.
What i've done so far is to open the tesseract_winrt.sln on the VS2015 folder.
After that i copied leptonica project to root directory of tesseract_winrt so it can be loaded inside the solution. Once that everything is loaded i click build solution and get this errors:

I'm not sure what i'm doing wrong or how to properly set the dependencies
Any idea would be appreciated.

A: There are now binaries for the project that you can use:
https://github.com/yoisel/tesseract_winrt/releases/tag/v0.1-alpha
It is a set of Visual Studio Extension SDKs, you can install the one for UWP projects on your system and add a reference to it in your project using the "Extensions" tab:

Disclaimer: This project was merely a proof of concept and I strongly recommend not to use it as is in a production scenario


text:
Q: How to clone Umbraco Cloud development environment to local I am currently in the process of migrating some old websites to Umbraco Cloud, however for testing it I created a brand new project, created a basic document type and added some text.
How do I extract the content from my Development Environment to Local?
The first time I started my local umbraco instance it asked to sync, downloaded some files and everything worked, however how do I trigger this for new changes?
I have tried the following in CMD in the /data/ folder:
echo > deploy

A file called "deploy-complete" is created but is empty, and new content did not download to local umbraco.

A: Turns out I was blind the first time.
In the local Umbraco Installation right-click the Home (or whatever node you want to sync to local) and click Restore or Partial Restore, this will trigger the sync.
Umbraco has a guide here:
https://our.umbraco.com/Documentation/Umbraco-Cloud/Deployment/Restoring-content/


text:
Q: Error during export dump file oracle using sql developer Version Version 18.1.0.095 Build 095.1630 I want to export dump file DDL my database (Oralce database version 11.2.0.4). I created user and granted permission (sysdba). I connected to database using user above, I choose View --> DBA --> Data Pump --> Data Pump Export Wizard --> choose connection above --> and it alert error "Cant use Data Pump as sys.".

A: Here's an interesting thing about SYS, it cannot use SERIALIZABLE transactions. This also applies to users connected as SYSDBA. Find out more.
The SERIALIZABLE isolation level means that all statements in a transaction are read consistent. The default for Oracle is READ COMMITTED, which applies at the statement level. The difference is this: if we run select * from T1 followed by select * from T2 under READ COMMITTED isolation level then we will any changes committed to T2 while we were querying T1. That is, the result sets for T1 and T2 are both consistent set of records, but we might have seen different results if we had run the queries the other way round. Whereas, under SERIALIZABLE the result sets are consistent with the start of the transaction. It doesn't matter what order we query the tables, the results are stable.
You can see why this is important for exporting. The entire set of exported tables must be consistent in order to guarantee the relational integrity of a subsequent import. We don't want to export a child table with records which depend on records added to the parent table after we exported it. (The old Export utility allowed us to set consistency=N - indeed that was the default! - but Data Pump protects us from ourselves).
So this is why we can't run exports as SYS, or SYSDBA users. Fortunately there is a simple solution: revoke SYSDBA from your user and grant it DATAPUMP_EXP_FULL_DATABASE and DATAPUMP_IMP_FULL_DATABASE roles instead. [Find out more][2].

A: I found answer to my question:
- when login we choose Role default

*

*We need grant dba permission to user
Ex:
Grant dba to vinhhc_vsc;


text:
Q: Помогите составить верно запрос Необходимо обновить значение Answer где idLog max мой код  не работает. Заранее спасибо!!!
UPDATE log_sms SET Answer= ? where (SELECT MAX(idLog) FROM log_sms order by Answer desc limit 1)

A: Результат подзапроса в WHERE надо с чем-то сравнивать. В данном случае - с idLog
Также из-за того, что обновляется та же таблица, по которой идёт подзапрос, придётся использовать промежуточный результат
Итоговый вариант:
UPDATE log_sms
SET Answer = ?
WHERE idLog = (SELECT * FROM (SELECT MAX(idLog) FROM log_sms) as t)

Есть вариант без подзапросов (например, в этом ответе):
UPDATE log_sms
SET Answer = ?
ORDER BY idLog DESC
LIMIT 1


text:
Q: mysqli fetch result as assoc array $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

can somebody help me to this statement/syntax? i want the result as associative array (indexed by fieldname) and don't want to write this "$stmt->bind_result($name, $code);" statement. thanks

A: As you are not actually using any parameters i.e. ? then you dont really need to do a ->prepare
So you could just use the ->query() and ->fetch_assoc() mechanism
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

$result = $mysqli->query($query)

if ( $result === FALSE ) {
    echo $mysqli->error;
    exit;
}

/* fetch values */
while ($row = $result->fetch_assoc()) {
   printf ("%s (%s)\n", $row['name'], $row['code']);
}

After your comment
This is another option, if you have to keep the prepare
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

// there seems to be some confusion in the manual as to
// whether this next statement is needed or not
// see if that helps

$stmt = $mysqli->stmt_init();

if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    if (!$stmt->execute()) {
        echo $stmt->error;
        exit;
    }

    $result = $stmt->get_result();

    /* fetch values */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row['name'], $row['code']);
    }

} else {
    echo 'Failed to prepare statement';
    exit;
}

The call to $stmt->get_result() basically converts a mysql_stmt object to a mysql_result object

A: Try this.
    $stmt = $mySqli->query($query);
    $countries = mysqli_fetch_all($stmt, MYSQLI_ASSOC);
    $stmt->close();

A: Just try this :
while ($stmt->fetch(PDO::FETCH_ASSOC)) {
    printf ("%s (%s)\n", $name, $code);
}


text:
Q: Cannot create stored procedure MySQL I am trying to create a stored procedure, but I am having an issue.
    delimiter |
create procedure get_user_credits_2(guid char(50))
BEGIN
SELECT user_credits.GUID,
    creditwarninglevel,
    creditsexpirydate,
    EmailCreditWarningLevel,
    EmailAddressWarningLevel,
    CustomerName,
    CASE WHEN user_credits.Credits > 0
         THEN sum(user_credits.Credits) + SUM(user_credits.PurchasedCredits)
         ELSE   user_credits.Credits
    END AS 'Credits'
FROM
user_credits
WHERE guid=iguid;
END
|
delimiter ;

Error 1064: You have an error in your SQL syntax, check the manual to your mysql server version for the right syntax to use near 'END' at line 15.

I have checked a few sources, but I can't get this to work. I'm sure it is probably something I am over looking. Thanks
I have checked another question as well on here source: MYSQL stored procedure, case
Image:

A: I solved the issue, for some reason in Navitcat IDE doesn't like the fact you declare a procedure and start with
BEGIN

END

It only cares about the select statement. eg
Select * from table;


text:
Q: Full HD 2D Texture Memory OpenGL I am in the process of writing a full HD capable 2D engine for a company of artists which will hopefully be cross platform and is written in OpenGL and C++.
The main problem i've been having is how to deal with all those HD sprites. The artists have drawn the graphics at 24fps and they are exported as png sequences. I have converted them into DDS (not ideal, because it needs the directx header to load) DXT5 which reduces filesize alot. Some scenes in the game can have 5 or 6 animated sprites at a time, and these can consist of 200+ frames each. Currently I am loading sprites into an array of pointers, but this is taking too long to load, even with compressed textures, and uses quite a bit of memory (approx 500mb for a full scene).
So my question is do you have any ideas or tips on how to handle such high volumes of frames? There are a couple of ideas i've thought've of:

*

*Use the swf format for storing the frames from Flash

*Implement a 2D skeletal animation system, replacing the png sequences (I have concerns about the joints being visible tho)

How do games like Castle Crashers load so quickly with great HD graphics?

A: Well the first thing to bear in mind is that not all platforms support DXT5 (mobiles specifically).
Beyond that have you considered using something like zlib to compress the textures?  The textures will likely have a fair degree of self similarity which will mean that they will compress down a lot.  In this day and age decompression is cheap due to the speed of processors and the time saved getting the data off the disk can be far far more useful than the time lost to decompression.
I'd start there if i were you.

A: 24 fps hand-drawn animations? Have you considered reducing the framerate? Even cinema-quality cel animation is only rarely drawn at the full 24-fps. Even going down to 18 fps will get rid of 25% of your data.
In any case, you didn't specify where your load times were long. Is the load from harddisk to memory the problem, or is it the memory to texture load that's the issue? Are you frequently swapping sets of texture data into the GPU, or do you just build a bunch of textures out of it at load time?
If it's a disk load issue, then your only real choice is to compress the texture data on the disk and decompress it into memory. S3TC-style compression is not that compressed; it's designed to be a useable compression technique for texturing hardware. You can usually make it smaller by using a standard compression library on it, such as zlib, bzip2, or 7z. Of course, this means having to decompress it, but CPUs are getting faster than harddisks, so this is usually a win overall.
If the problem is in texture upload bandwidth, then there aren't very many solutions to that. Well, depending on your hardware of interest. If your hardware of interest supports OpenCL, then you can always transfer compressed data to the GPU, and then use an OpenCL program to decompress it on the fly directly into GPU memory. But requiring OpenCL support will impact the minimum level of hardware you can support.
Don't dismiss 2D skeletal animations so quickly. Games like Odin Sphere are able to achieve better animation of 2D skeletons by having several versions of each of the arm positions. The one that gets drawn is the one that matches up the closest to the part of the body it is attached to. They also use clever art to hide any defects, like flared clothing and so forth.


text:
Q: My Socket.io on IOS fails to handshake with the websocket server I have a Node.js server running Websocket. (using Pomelo).  I am able to run a web application and connect to it (localhost @port 3104).
however, when I try to use socket.io (SocketRocket) for IOS and connect to the same localhost and port, I get this error:
> http://127.0.0.1:3014/socket.io/1/?t=16807
> "ERROR: handshake failed ... The request timed out"

detail of the error:
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x6c723c0
{NSErrorFailingURLStringKey=http://127.0.0.1:3014/socket.io/1/?t=16807, NSErrorFailingURLKey=http://127.0.0.1:3014/socket.io/1/?t=16807, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x6c72400 "The request timed out."}

i tried. 127.0.01, localhost... even explicit IP address.. all fail
any idea what I should check?
and should it be "http" protocol ? or wss?

A: Got it working.. I just cannot run a websocket server.  I have to run a socket.io server... then it works.


text:
Q: I want to Execute the python method by clicking on Html Button....in my django project NoReverseMatch at /studentUpdate/
Reverse for 'student_update' not found. 'student_update' is not a valid view function or pattern name.
I am explaining the code very simply
Here is the code for the html button named update at the end of the form by clicking on that I want to execute python method called student_update
    <form id="form" method="POST" action="{% url 'students' %}">

                    {% csrf_token %}

                        Student ID:
                        <input type="text" name="sid" required="required" class="form-control"/>

                        First name:
                        <input type="text" name="firstname" class="form-control"/>

                        Last name:
                        <input type="text" name="lastname" class="form-control"/>

                        Department:
                        <input type="text" name="department" class="form-control" required="required"/>

                        Section:
                        <input type="text" name="section" class="form-control"/>

                        Year:
                        <input type="text" name="year" class="form-control"/>

                        <button name="save_book" id="save_book" type="submit" class="btn btn-primary" href="{% url 'student_update' %}">

                            Update

                        </button>

                </form>

Here is my url.py file
from django.conf.urls import url, include
from . import views
from django.urls import path, re_path
urlpatterns = [
    url(r'^index$', views.index),
    url(r'^student_update/(\d+)/$', views.student_update, name="updt_stud")
]

Finally Here is my views.py file
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.db.models import Sum
from datetime import date
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
# Create your views here.
from library.models import Book, Category, Student, Borrow
from django.template import loader

def student_update(request):
    return redirect('/students')     #I want my code to reach here

A: The problem is in the url.py  file, the url you have mentioned for the student_update is with the name for the url as :updt_stud
But while calling the url in the html file you are calling the url by name : student_update because which django didn't got to know to go so change it.
Moreover in the url you also have to pass arguments, its because the way you have defined the url for student update.
I hope it will help you!!

A: Add onclick="location.href='{% url 'updt_stud' %}'" in <button></button>, and
url(r'^student_update/(\d+)/$', views.student_update, name="updt_stud"), for calling function from button always put the name="updt_stud" in location.href that you define in url. and in form tag action = "/student_update", that action will match on url regex that you define in url r'^student_update/(\d+)/$'.
<form id="form" method="POST" action = "/student_update">

and
<button name="save_book" id="save_book" type="submit" class="btn btn-primary" onclick="location.href='{% url 'updt_stud' %}'">

 Update
</button>

In views.py
Add
 return render(request, 'new_page.html')

Or any html page you want to render.
You can do with return redirect try both one by one.


text:
Q: When running "php bin/console list", Symfony prints the code for several classes inside the "src/Admin"-directory I've taken over a code base of a Symfony 4.4-project, with a couple of extra bundles installed (Sonata being the biggest one). When I write: php bin/console list, then it prints the source code for several of the classes in the src/Admin-directory. And I can't figure out why.
I've searched the code for print, var_dump and dump, but can't figure out where this is.
I'm not familiar enough with Symfony, to go through the code 'from the top', adding my own dump-statements, narrowing it down, where this code is coming from.
Had this been Laravel, then I would have started in the routes, then moved on to maybe the kernel or middleware, then to the controlles - and in the end the views.
Does anyone have a good suggestion on which files to add dump-statements to, to see where this code is coming from?
... Or if anyone else has a good idea on how to find this code, then I'm all ears.
Is it maybe an entire namespace that is printed? And can one even do that?! Hmm...

This is what it looks like:

A: You'll get this behavior if the code you've inherited uses short open tags <? but your personal dev environment's PHP installation has them disabled. Run php --ini to find where your ini file is and then edit that to change from this:
short_open_tag = Off

To this:
short_open_tag = On

Alternatively, you could edit all the source files and change the short open tags <? to long open tags <?php.


text:
Q: Java Generics extends Let's have two classes in Java (7):
public class A<T> extends HashMap<T, T>{
...
}

and
public class B<T> extends TreeMap<T, T>{
...
}

Is it possible to have a common base class which these two classes would extend?
Thanks.
Clarification: I want that the classes share the same method
public T f(T o){
...
}

A: No, that is not possible. Java does not support multiple inheritence, so each class can only extend a single class. Since both of your classes already extends a different class, you cannot create a class that is a superclass of both of your classes.
A possible solution is to use composition:
public class MyMap<T> extends AbstractMap<T,T> {
    private Map<T,T> delegate;

    public MyMap(Map<T,T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
    }

    public Set<Map.Entry<T,T>> entrySet() {
        return delegate.entrySet();
    }

    // Optionally, implement other Map methods by calling the same methods
    // on delegate.

    public T f(T o) {
        // ...
    }
}

and then:
public class A<T> extends MyMap<T> {
    public A() {
        super(new HashMap<>());
    }
}
public class B<T> extends MyMap<T> {
    public B() {
        super(new TreeMap<>());
    }
}

or simply:
Map<T,T> aMap = new MyMap<>(new SomeOtherMapImplementation(...));

But obviously, now A and B are not themselves subclasses of HashMap and TreeMap respectively, so if that's what you need, you're out of luck :-).

A: As they both implement Map<T,T> you can do something like:
public class A<T> extends HashMap<T, T> {
}

public class B<T> extends TreeMap<T, T> {
}

List<Map<String,String>> list = Arrays.asList(new A<String>(), new B<String>());

A: I think you should create an Abstract class with the method that you want. And then instead os extends HashMap and TreeMap, use this data structures as fields of your new classes depending on your needs.
For instance:
public abstract class MyClass<T> {
   public T f(T o){
       ...
   }
}

public class A<T> extends MyClass<T> {
    private Map<T,T> mapThatINeed;
}


text:
Q: What is the time complexity for this algorithm which finds every prime number up to n Here's the algorithm in question, in pseudocode:
list.add(2)
for (i = 3 to n)
    isPrime=true
    for each (j in list)
        if ((i mod j) = 0)
            isPrime=false
            break
    if (isPrime)
        list.add(i)
return list

My TA today told me that this algorithm had a complexity of O(n^2), but I am quite sure that is incorrect, especially given that there are approximately n/ln(n) prime numbers up to any n, so the inner loop would not iterate more than n/ln(n) times on its last iteration if n itsself were prime. However I think it's actually lower than O(n^2/ln(n)) in reality, but I'm not sure how to determine what it actually is. For example, every even number only iterates the second loop twice.

A: Among n numbers you are checking for being prime there are approximately n / ln(n) actually prime numbers which demands all i / ln(i) already found prime numbers to be tried as divisors. Therefore, the complexity of your algorithm is W(n^2 / ln(n)^2) (W is big-omega) and O(n^2 / ln(n). n^2 / ln(n)^2 growths faster then n * sqrt(n).
For reaching O(n * sqrt(n)) time complexity you should use the following pseudocode:
list.add(2)
for (i = 3 to n)
    isPrime=true
    for each (j in list)
        if j > sqrt(i)
            break
        if ((i mod j) = 0)
            isPrime=false
            break
    if (isPrime)
        list.add(i)
return list

A: The complexity is O((n/log(n))**2).
You analyze it as follows.  There are two sets of numbers that you encounter, primes and composites.
You have O(n/log(n)) primes, each of which you have to test against all smaller primes, for O(n/log(n)) work per prime, for a total of O((n/log(n))**2) work.
You have O(n - n/log(n)) = O(n) composites, each of which has to be tested against at some subset of the primes below sqrt(n) for work bounded above by O(sqrt(n)) so the total work is bounded above by O(n sqrt(n)).
Therefore the O((n/log(n))**2) term dominates.
Of course this isn't the answer your intuition was leading you towards.  You were trying to get intuition for what happens if you are smart and cut off the inner loop when the prime squared exceeds your target number, then how long would it take?  The answer turns out to be O(n sqrt(n) / (log(n))**2).  The reason is that there are O(sqrt(n)/log(sqrt(n)) = O(sqrt(n)/log(n)) primes below sqrt(n), each of which needs to be tested for O(n/log(n)) numbers (see http://mathworld.wolfram.com/MertensTheorem.html for an indication of why this is so).
However at this point we've passed from the world of algorithms to the world of number theory. :D


text:
Q: Node.js Upload multiple images from user and display it I am working on an application using express, where users can upload their images and that are stored in mongodb.
I have tried many modules to be able to upload an image in mongoDB. I have really no idea how I can do this in a easy way.
Does any of you know a good and easy way for uploading images and display them?


text:
Q: how to print firebase data in Agenda | Firebase expo I'm trying to print the data I get from my database but I can't think of how to get the data variable and use it in renderItem(). I've already managed to create keys through useState to use in map(), I just wanted to know a way to get these variables out of useState and be able to use them in react-agenda
import React, { useEffect, useState } from 'react'
import { StyleSheet, View, Text, TouchableOpacity, Modal, TextInput, Alert } from 'react-native'
import { LocaleConfig, Agenda } from 'react-native-calendars'
import DateTimePicker from 'react-native-modal-datetime-picker';

import { getAuth } from 'firebase/auth';
import { getDatabase, ref, onValue, set, push, get, child } from 'firebase/database';

const Calendario = () => {

  const [modalVisible, setModalVisible] = useState(false);
  const [events, setEvents] = useState('');
  const [dateSelected, setDateSelected] = useState('');
  const [description, setDescription] = useState('');
  const [refreshCalender, setRefreshCalender] = useState(false);
  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

  const [data, setmyData]=useState({})

  const db = getDatabase();
  const app = getAuth();
  const refe = ref(db, 'users/' + app.currentUser.uid);
  const dbRef = ref(db);

  const renderItem = (item, data) => {
    return(
      data.map(() => {
      <View style={styles.itemContainer}>
        <Text id={item["$key"]} style={styles.textInf}>{item.title}</Text>
        <Text style={styles.textInf}>{item.details}</Text>
    </View>
    })
    )
  }
  const storeInDB = () => {
    push(refe, {
      date: strDate,
      title: events,
      details: description
    });
  }

  useEffect(()=>{
    onValue(ref(db, 'users/' + app.currentUser.uid), snapshot =>{
      let data = [];
      snapshot.forEach(childsnap => {
        let val = childsnap.val();
        val['$key'] = childsnap.key;
        data.push(val);
      });
      setmyData(data);
    })
  },[]);

  return (
    <>
        <Agenda
          //items={ dataF }
          renderEmptyDate={() => {
            return <View />;
          }}
          renderEmptyData={() => {
            return <View />;
          }}
          selected={new Date()}
          minDate={null}
          renderItem={renderItem}
          markingType="custom"
          refreshing={refreshCalender}
        />
    </>
  )
}

export default Calendario

Data from firebase:

A: I create an array to store the data and converted it to an object using Object.assign(), now the problem is just to render the items
const data = []
var obj = {}
  useEffect(() => {
     get(child(dbRef, 'users/' + app.currentUser.uid)).then((snapshot) => {
       snapshot.forEach(childsnap => {
          let dateD = childsnap.child("date").val()
          let titleD = childsnap.child("title").val()
          let dtsD = childsnap.child("details").val()

          // "yyyy-MM-dd": [{any: "whatever", any2: "whatever"}],
          data.push({
            [dateD] : [{ title: titleD, details: dtsD }],
          });
        })
        obj = Object.assign({}, ...data)

        console.log(obj)
    })
  } ,[])


text:
Q: How to get returning ID in JPA after native query insert I have the following code in JPA to return an auto generated ID after inserting using native query:
Query q = em.createNativeQuery("insert into .... returning ID", Long.class);
q.executeUpdate();

However, I'm getting the following error:
A result was returned when none was expected

A: OK that was an easy one. I have just used q.getSingleResults() and it worked fine!
Query q = em.createNativeQuery(sql);
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();


text:
Q: How to put the return data in a php variable when using ajax post I'm currently using an ajax post to retrieve data from another page. For reusing the returned value in future, I want to assign it to a php variable. Is it possible?
success: function(data) {
 $('#display').html(data);
}

A: You can't. The php file completes its execution in the server first and the result is passed to the browser. The javascript (ie, ajax) part is then executed in your browser. Read the answer here for more info.

A: you can use like:
<script type="text/javascript">
var jvalue = 'this is javascript value';

<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>


text:
Q: Can't bind to 'scrollStrategy' since it isn't a known property of 'ng-template' Facing following error after run npm start command.It will execute successfully but application is not started.enter image description here
If 'scrollStrategy' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component

A: Ok, I was also facing the same 'scrollStrategy' issue in my project. Then i finally checked the @angular packages version. Then i found that the one of my angular package '@angular/cdk' is upper version then my other @angular/xxx packages. I was using Angular 5.x.x version on my project. But i was mistakenly installed v6.x.x version of @angular/cdk package. So i finally changed the version of my angular CDK to 5.x.x. and my angular project is compiling perfectly.
So, You must checked the version of '@angular/---' packages. It should fall in same major (i.e '5'.x.x) version.


text:
Q: I do not need support for older browser then IE11 do I need modernizr? I have came to know about H5BP and modernizr. now I have developed website which is made in flexbox and I do not want support for older browser then IE11. (coz I do not care for IE 6 to 10).
now I have seen that modernizr detects browser support and tells to add "no-XYZ" class to make it work for older browsers. but I do not want to do that hard work to make it work in IE6 to IE10. should I remove modernizr ? from H5BP ?
I'm already using HTML5SHIV.

A: Modernizr isn't about letting you use other browsers, it is about letting you know wether or not a feature is enabled in the users current browser. As you add features to your website, check their compatibility on caniuse.com. If it is not stellar support, consider using Modernizr for fallbacks.

A: HTM5 and CSS3 are the latest versions and have advanced features which are not supported by the older browser engines. To detect these features in browser we will use modernizr library.

Ex :

    if (Modernizr.canvas) {
        alert("This browser supports HTML5 canvas!");
      } else{
        alert("This browser does not supports HTML5 canvas!");
    }


text:
Q: Glassfish Message-Driven bean message size I'm trying to use a message-driven bean in my webapp, but everytime it throws me this exception :
com.sun.messaging.jmq.jmsserver.util.BrokerException: [B4122]: Can not add message 1-127.0.1.1(b0:1a:c1:66:46:a9)-1-1336769823653 to destination PhysicalQueue [Queue]. The message size of 24968685 bytes is larger than the destination individual message byte limit (maxBytesPerMsg) of 10485760 bytes.

After some researches, I've found out that the default limit is -1, so it has to be unlimited.
I've looked everywhere in Glassfish's admin console but withou finding a way to remove this limit.
Even the "new JMS resource" wizard doesn't ask anything about this parameter.
Is there any way to fix it?

A: Why is your message so large? You might want to reconsider how you're doing this.
....
You can update it via the imqcmd command. The value you want to change is MaxBytesPerMsg.
From the SunGlassFish MessageQueue 4.4 Administration Guide or the 4.2 guide.
Updating Physical Destination Properties
The subcommand imqcmd update dst changes the values of specified properties of a physical
destination:
imqcmd update dst -t destType -n destName
                   -o property1=value1 [ [-o property2=value2] ... ]

The properties to be updated can include any of those listed in Table 18–1 (with the exception of the isLocalOnly property, which cannot be changed once the destination has been created).
For example, the following command changes the maxBytesPerMsg property of the queue
destination curlyQueue to 1000 and the maxNumMsgs property to 2000:
imqcmd update dst -t q -n curlyQueue -u admin
                  -o maxBytesPerMsg=1000
                  -o maxNumMsgs=2000


text:
Q: Create new API fields for CS-Cart Users Is there a way i can create custom fields for Users in CS-Cart where i can store a particular value unique to each user using the CS-Cart API?
I want to add two unique fields

A: Users API is cs-cart built-in Entity.  You can find Users entity (php code) from this folder /app/Tygh/Api/Entities/Users.php
you can edit the Users.php for your desired purpose.


text:
Q: How to turn a subroutine into a function? I've written a subroutine that takes in 6 matrices and after some manipulation returns back 3 new ones.
I will use this subroutine fairly often in this notebook so I think it would be easier to turn the whole process into a function M[matrix1, matrix2, matrix3, matrix4, matrix5, matrix6]. Is there a way to do this?
Clear[data1P, data1N, data2P, data2N, data3P, data3N, i]
data1P = matrixIN1;
data2P = matrixIN2;
data3P = matrixIN3;
data1N = matrixIN4;
data2N = matrixIN5;
data3N = matrixIN6;

For[i = 1, i <= Length[data2P], i++,
 AppendTo[data1P, data2P[[i]]];
 AppendTo[data1N, data2N[[i]]];
]

For[i = 1, i <= Length[data3P], i++,
 AppendTo[data1P, data3P[[i]]];
 AppendTo[data1N, data3N[[i]]];
]

matrixOUT1 = data1P;
matrixOUT2= data1N;

matrixOUTp3 =
  matrixOUT1[[All, 2]] -
   matrixOUT2[[All, 2]];

matrixOUT3 =
  Table[{matrixOUT1[[i,1]], matrixOUTp3[[i]]}, {i, 1,
    Length[matrixOUTp3]}];

A: Here is the code converted to function + some corrections:
function[arrays : {__?ArrayQ}] := Module[{
   temp1, temp2, temp3
   },
  temp1 = Join @@ arrays[[{1, 2}]];
  temp2 = Join @@ arrays[[{4, 5}]];

  temp3 = Transpose[{
     temp1[[;; , 1]],
     temp1[[;; , 2]] - temp2[[;; 2]]
     }];

  {temp1, temp2, temp3}

 ]

There is no check if appropriate matrices are of the same length but your code doesn't contain any either.
Things you should read about:
Module, Functions as Procedures tutorial, Part, Join, PatternTest


text:
Q: Open CMD with specific color and title I recently started learning batch and wanted to write a script that opens CMD with a specific color and title. This code opens my CMD and another plain one! How can i get rid of the plain cmd?
Start CMD
title Hacker's CMD
color 04

A: start cmd /k title Hacker's CMD^&color 04

The /k parameter executes the commands and leaves the cmd window open. To pass several commands use an escaped command separator ^& so that the separation occurs in the launched cmd, not in the original batch file.


text:
Q: Autofac trigger lifetimescope creation Is there any way to cause the creation of a new lifetimescope when resolving a component?
Meaning something like

container.registerType().As().TriggersNewScope()

Is there any other way of doing that? Other than taking dependency on ILifetimeScope and to directly resolve through it?
If there isn't, is there a way to abstract the ILifetimeScope? I don't want that part of the application to reference Autofac..
Thanks

A: There's not really a "component triggers lifetime scope creation" thing as such. However, you may be interested in Owned<T>. That causes a component to be resolved in its own little lifetime.

A: You need to register your reused service as InstancePerOwned.
The remaining unsolved part is avoiding reference to Autofac, here is a possible workaround:

*

*Define your IOwned interface in your Autofac agnostic assembly.

*Define and register open-generic CustomOwned implementation in Autofac aware composition root:
class CustomOwned<T> : IOwned<T>, IDisposable
{
    public T Value { get { return _owned.Value; } }
    public CustomOwned(Autofac.Owned<T> owned)
    {
        _owned = owned;
    }

   // IDisposable implementation and whatever additional stuff
}

*Use IOwned instead of Owned in your types.


text:
Q: Merge contact details with existing contact I'm trying to select a user in the addressBook using ABPeoplePickerNavigationController then once a user has been selected, within the delegate method
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person;

I wish to add to the ABRecordRef and then edit/save this record with ABPersonViewController.
My problem is what navigationController to attach the ABPersonViewController to. Any help welcome.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {

    ABPersonViewController *personView = [ABPersonViewController new];

    [self populate:person withData:self.personData];
    personView.displayedPerson =  person;

    personView.personViewDelegate = self;
    personView.allowsEditing = YES;

    [peoplePicker.navigationController pushViewController:personView animated:YES];

//    [self dismissPicker:peoplePicker];
    return YES;

}

A: Were you able to resolve this? The Apple QuickContacts example presents ABPeoplepickerNavigationController and ABPersonViewController from separate buttons rather than combining them which suggests they were not meant to work together...


text:
Q: Not able to install levmar (Levenberg-Marquardt nonlinear least squares algorithms in C/C++) on Ubuntu 16.04 I was trying to install levmar from the link Levenberg-Marquardt nonlinear least squares algorithms in C/C++. Firstly, install suitesparse and metis.
sudo apt-get install libsuitesparse-dev
sudo apt-get install libmetis-dev

Then done the following two steps:
1.Download Levmar and extract it.
2.Open Terminal in that directory and input "make";

After make in the terminal I got the following error:
/usr/bin/ld: cannot find -lf2c
collect2: error: ld returned 1 exit status
Makefile:40: recipe for target 'lmdemo' failed
make: *** [lmdemo] Error 1

Im running on Ubuntu 16.04. Any help how to fix the error?
Thanks

A: I sometimes back jumped into the same issue, but I alternatively install it using pip3. I hope it also helps
pip3 install --user --upgrade pytest levmar

you might want to read more from https://pypi.org/project/levmar/


text:
Q: Why doesn't the array change when I try to modify it via a for-loop I just picked up Python after 3 years in JavaScript, and I'm struggling to understand why the following doesn't change the existing array?
I basically just want to trim each array to the first 5 elements.
data = [[1619740800000, '54474.27000000', '108499.98000000', '30000.00000000', '56989.21000000',
'5.74916200', 1619827199999, '332834.07665858', 23971, '4.30590700', '251576.63190168', '0'],
[1619827200000, '56989.21000000',
'105053.04000000', '12000.00000000', '57794.45000000', '10.12076500', 1619913599999,
'612746.95919066', 45086, '9.12267500', '557156.21495534', '0'], [1619913600000, '57797.36000000',
'98900.00000000', '30000.00000000', '56539.47000000', '6.05304600', 1619999999999, '334919.15726802',
 28754, '5.03377800', '284764.41259450', '0']]

My for loop:
for x in data:
  x = x[:5]

# print(data) outputs the same as above

A: Just do it:
data = [[1619740800000, '54474.27000000', '108499.98000000', '30000.00000000', '56989.21000000',
'5.74916200', 1619827199999, '332834.07665858', 23971, '4.30590700', '251576.63190168', '0'],
[1619827200000, '56989.21000000',
'105053.04000000', '12000.00000000', '57794.45000000', '10.12076500', 1619913599999,
'612746.95919066', 45086, '9.12267500', '557156.21495534', '0'], [1619913600000, '57797.36000000',
'98900.00000000', '30000.00000000', '56539.47000000', '6.05304600', 1619999999999, '334919.15726802',
 28754, '5.03377800', '284764.41259450', '0']]

for i in range(len(data)):
    data[i] = data[i][:5]

A: "I'm struggling to understand why the following doesn't change the existing array?"
I take it your actual question is why what you have tried doesn't work, and not specifically how to do it right, but I will address both.
The reason, as I understand it, is that while the x variable is, on each iteration assigned the result you are looking for (x[:5]) that result is not stored in your data array. It is simply stored in the x variable, during that single iteration, which is a copy of the element in the array, not a reference to the element itself. It is not the same as doing
for i in range(len(data)):
    data[i] = data[i][:5]  # explicitly sets the element

which explicitly sets the array elements
As confirmation, see this:
data = [[1,2,3,4], [5,6,7,8]]
for x in data:
    x = x[:2]  # does indeed set x, but only x
    print(x)

[1,2]
[5,6]
>> print(data)    # but data array is unchanged
[[1,2,3,4], [5,6,7,8]

Alternatively, see this (list comprehension):
data = [x[:5] for x in data]
# this creates a new array, and stores it in data, but has the outcome you want


text:
Q: Picasso not loading all images i have been using Picasso to load my images from drawable and all works fine except that the 3rd image keeps missing and i get a blank screen instead. after a while however the image loads. i am unable to understand why this delay occurs for this image.Any help and explanation is appreciated.
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.home);

      viewPager = (ViewPager) findViewById(R.id.pager);
       final ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);

    Button yourButton = (Button)findViewById(R.id.button_previous);
    yourButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            viewPager.setCurrentItem(getItem(-1), true); //getItem(-1) for prev
        }
        protected int getItem(int i) {
            // TODO Auto-generated method stub
             return viewPager.getCurrentItem() + i;
        }
    });

    Button nextButton = (Button)findViewById(R.id.button_next);
    nextButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            viewPager.setCurrentItem(getItem(+1), true); //getItem(-1) for prev
        }
        protected int getItem(int i) {
            // TODO Auto-generated method stub

             return viewPager.getCurrentItem() + i;
        }
    });

  facebookButton = (Button)findViewById(R.id.fb);
    facebookButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            try {
                //Write file
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

                String filename = "bitmap.png";
                FileOutputStream stream = getApplicationContext().openFileOutput(filename, Context.MODE_PRIVATE);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

                //Cleanup
                stream.close();
                bmp.recycle();

                //Pop intent
                Intent in1 = new Intent(getApplicationContext(), FacebookUpload.class);
                in1.putExtra("image", filename);
                startActivity(in1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    Button btnrand = (Button)findViewById(R.id.button2);
    btnrand.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        View view = (View) viewPager.findViewWithTag("myview" + viewPager.getCurrentItem());
        Log.d("Inside rand", "i am here");
        try{
        //You can use any view of your View instead of TextView
        Random rand = new Random();
        int rndInt = rand.nextInt(141) + 1;
        String drawableName = "c"+ rndInt;
        int resID = getResources().getIdentifier(drawableName, "drawable",  getPackageName());
        ((ImageView) view).setImageResource(resID);

        }
        catch (Exception e)
        {

        }
  }

    });

  }

  class ImagePagerAdapter extends PagerAdapter {

         public int[] mImages = new int[] {

            R.drawable.c1 ,
            R.drawable.c2 ,
            R.drawable.c3 ,
            R.drawable.c4 ,
            R.drawable.c5 ,
            R.drawable.c6 ,
            R.drawable.c7 ,
            R.drawable.c8 ,
            R.drawable.c9 ,

            R.drawable.c11 ,
            R.drawable.c12 ,
            R.drawable.c13 ,
            R.drawable.c14 ,
            R.drawable.c15 ,
            R.drawable.c16 ,
            R.drawable.c17 ,
            R.drawable.c18 ,
            R.drawable.c19 ,
            R.drawable.c20 ,
            R.drawable.c21 ,
            R.drawable.c22 ,
            R.drawable.c23 ,
            R.drawable.c24 ,
            R.drawable.c25 ,
            R.drawable.c26 ,
            R.drawable.c27 ,
            R.drawable.c28 ,
            R.drawable.c29 ,
            R.drawable.c30 ,
            R.drawable.c31 ,
            R.drawable.c32 ,
            R.drawable.c33 ,
            R.drawable.c34 ,
            R.drawable.c35 ,
            R.drawable.c36 ,
            R.drawable.c37 ,
            R.drawable.c38 ,
            R.drawable.c39 ,
            R.drawable.c40 ,
            R.drawable.c41 ,
            R.drawable.c42 ,
            R.drawable.c43 ,
            R.drawable.c44 ,
            R.drawable.c45 ,
            R.drawable.c46 ,
            R.drawable.c47 ,
            R.drawable.c48 ,
            R.drawable.c49 ,
            R.drawable.c50 ,
            R.drawable.c51 ,
            R.drawable.c52 ,
            R.drawable.c53 ,
            R.drawable.c54 ,
            R.drawable.c55 ,
            R.drawable.c56 ,
            R.drawable.c57 ,
            R.drawable.c58 ,
            R.drawable.c59 ,
            R.drawable.c60 ,
            R.drawable.c61 ,
            R.drawable.c62 ,
            R.drawable.c63 ,
            R.drawable.c64 ,
            R.drawable.c65 ,
            R.drawable.c66 ,
            R.drawable.c67 ,
            R.drawable.c68 ,
            R.drawable.c69 ,
            R.drawable.c70 ,
            R.drawable.c71 ,
            R.drawable.c72 ,
            R.drawable.c73 ,
            R.drawable.c74 ,
            R.drawable.c75 ,
            R.drawable.c76 ,
            R.drawable.c77 ,
            R.drawable.c78 ,
            R.drawable.c79 ,
            R.drawable.c80 ,
            R.drawable.c81 ,
            R.drawable.c82 ,
            R.drawable.c83 ,
            R.drawable.c84 ,
            R.drawable.c85 ,
            R.drawable.c86 ,
            R.drawable.c87 ,
            R.drawable.c88 ,
            R.drawable.c89 ,
            R.drawable.c90 ,
            R.drawable.c91 ,
            R.drawable.c92 ,
            R.drawable.c93 ,
            R.drawable.c94 ,
            R.drawable.c95 ,
            R.drawable.c96 ,
            R.drawable.c97 ,
            R.drawable.c98 ,
            R.drawable.c99 ,
            R.drawable.c100 ,
            R.drawable.c101 ,
            R.drawable.c102 ,

            R.drawable.c104 ,
            R.drawable.c105 ,
            R.drawable.c106 ,
            R.drawable.c107 ,
            R.drawable.c108 ,
            R.drawable.c109 ,
            R.drawable.c110 ,
            R.drawable.c111 ,
            R.drawable.c112 ,
            R.drawable.c113 ,
            R.drawable.c114 ,
            R.drawable.c115 ,
            R.drawable.c116 ,
            R.drawable.c117 ,
            R.drawable.c118 ,
            R.drawable.c119 ,
            R.drawable.c120 ,
            R.drawable.c121 ,
            R.drawable.c122 ,
            R.drawable.c123 ,
            R.drawable.c124 ,
            R.drawable.c125 ,
            R.drawable.c126 ,
            R.drawable.c127 ,
            R.drawable.c128 ,
            R.drawable.c129 ,
            R.drawable.c130 ,
            R.drawable.c131 ,
            R.drawable.c132 ,
            R.drawable.c133 ,
            R.drawable.c134 ,
            R.drawable.c135 ,
            R.drawable.c136 ,
            R.drawable.c137 ,
            R.drawable.c138 ,
            R.drawable.c139 ,
            R.drawable.c140 ,
            R.drawable.c141

        };

         @Override
            public int getCount() {
              return mImages.length;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
              return view == ((ImageView) object);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                 Context context =getApplicationContext();
              final ImageView imageView = new ImageView(context);
              int padding = context.getResources().getDimensionPixelSize(
                  R.dimen.padding_medium);
              imageView.setPadding(padding, padding, padding, padding);
              imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

              Picasso.with(context).load(mImages[position]).resize(350, 350)
                .centerCrop().into(imageView); // use ImageView
              ((ViewPager) container).addView(imageView, 0);
              imageView.setTag("myview" + position);

              return imageView;
            }

            @Override
            public void destroyItem(View container, int position,
                    Object object) {
                // TODO Auto-generated method stub
                ((ViewPager) container).removeView (viewPager.getChildAt(position));
            }

  }

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    View view = (View) viewPager.findViewWithTag("myview" + viewPager.getCurrentItem());
    super.onDestroy();
    ((ImageView) view).setImageDrawable(null);
}

}

this is my code


text:
Q: DataBinding: Generic.HashSet`1 does not contain a property with the name I have an entity called Employee that has a Navigation Property called Groups.
I have an entity called Group that is related to an Employee and has fields for Name and Description
I have an EntityDataSource to filter by the Employee selected in GridView1, that has Include Groups, its defined like this:
<asp:EntityDataSource ID="GroupsByEmployeeSource" runat="server" ConnectionString="name=SafetyContext" DefaultContainerName="SafetyContext" EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="Employees" Include="Groups" Where="it.[EID] == @EmpID">
    <WhereParameters>
        <asp:ControlParameter Name="EmpID" Type="Int32" ControlID="GridView1" PropertyName="SelectedDataKey.Value" />
    </WhereParameters>
</asp:EntityDataSource>

GridView3 is used to display the Groups that the Employee belongs to. I have it set up like this:
<asp:GridView runat="server" ID="GridView3" DataSourceID="GroupsByEmployeeSource" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="GroupsByEmployee" runat="server" Text='<%#Eval("Groups.Name") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

And every time I select an employee in GridView1 the follow exception is thrown:
System.Web.HttpException: DataBinding: 'System.Collections.Generic.HashSet`1[[SafetyTrackingConceptApplication.DAL.Group, SafetyTrackingConceptApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'Name'.

I must be missing something, but the Entity Group definitely has a property called Name. Does anyone have any idea what is wrong here?

A: Have/had the same problem. The relationship is returning the collection because of the fk (foreign key) relationship in that the Emp can be in multiple groups, which returns a collection as explained in the comment by AMasoud. So you can have the Groups.Count return the number of times the EmpID shows up the group table, but alas you cannot pinpoint a NAME b/c it will be returning the collection.
If the FK is one to one, or many to one (Not one to many) you will have the ability to pull the name.


text:
Q: Jquery and get values from form I have little form for get the value from some field , but no get works finally , i put my code :
<script>
function pin_vps(id)
{

$('#form7').submit(function() {

var passpin = $('.pin_vps_'+id).attr("value");

alert("ok "+passpin);

});

}
</script>

<?php
$v="18";
?>

<form id="form7" name="form7" method="post" action="?" onsubmit="pin_vps('<?php echo $v;?>');return false;">
<input name="pin_vps" type="text" class="pin_vps_<?php echo $v;?>"/>
<input name="submit" type="button" value="Access">
</form>

When i go and click in submit no happend nothing , i try use onclick in buttom and in form but continue no works
I don´t know what´s bad
Thank´s , Regards !!!

A: I'm not sure exactly what you are trying to do, so maybe providing some more information about your desired end result would help.
However I think the following should give you a head start:
HTML:
<form id="form7" name="form7" method="post" data-number="1" action="?">
    <input name="pin_vps" type="text" class="pin_vps_1" />
    <input name="submit" type="submit" value="Access" />
</form>

JavaScript:
$(document).ready(function () {

    $("#form7").submit(function (e) {

        // Stop the form submitting so you can see the below
        e.preventDefault();

        // Get the value of the field
        var dn = $(this).attr("data-number");
        var passpin = $(".pin_vps_" + dn, this).val();

        alert("ok " + passpin);

    });

});

JSFiddle: http://jsfiddle.net/mnKEf/2/


text:
Q: Does this Maven range dependency error makes sense? I'm working with a "pom" dependency that defines this dependency
<groupId>com.oracle.toplink</groupId>
<artifactId>eclipselink</artifactId>
<version>[12.2.1,12.2.2)</version>

And in the repository, the maven-metadata of eclipselink contains the following
<metadata>
  <groupId>com.oracle.toplink</groupId>
  <artifactId>eclipselink</artifactId>
  <version>12.1.3-0-0</version>
  <versioning>
    <latest>12.2.1-0-0</latest>
    <release>12.2.1-0-0</release>
    <versions>
      <version>12.1.2-0-0</version>
      <version>12.1.3-0-0</version>
      <version>12.2.1-0-0</version>
    </versions>
    <lastUpdated>20161123223550</lastUpdated>
  </versioning>
</metadata>

But Maven throws this error
Couldn't find a version in [12.1.2-0-0, 12.1.3-0-0, 12.2.1-0-0] to match range [12.2.1,12.2.2)
If I'm not wrong, Maven should've matched with the 12.2.1-0-0 version.
Why does this happen?
Also, there are two more versions in the repository 12.2.1-1-0 and 12.2.1-2-0 but these do not appear in the maven-metadata of eclipselink (any idea why?)

A: If really do a comparsion of the version in Maven via:

$ java -jar apache-maven-3.3.9\lib\apache-artifact-3.3.9.jar 12.2.1-1-0 12.2.1
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 12.2.1-1-0 == 12.2.1-1
   12.2.1-1-0 > 12.2.1
2. 12.2.1 == 12.2.1

You see that 12.2.1 is something different than12.2.1-1-0`
Furthermore if you use 12.2.1-0-0 and compare it to 12.2.1 via:

$ java -jar apache-maven-3.3.9\lib\apache-artifact-3.3.9.jar 12.2.1-0-0 12.2.1
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 12.2.1-0-0 == 12.2.1
   12.2.1-0-0 == 12.2.1
2. 12.2.1 == 12.2.1

You see that there is no difference between those versions.

*

*https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning

*https://maven.apache.org/ref/3.3.9/maven-artifact/apidocs/src-html/org/apache/maven/artifact/versioning/ComparableVersion.html

*http://maven.apache.org/ref/3.3.9/maven-artifact/index.html


text:
Q: How to show message of some special characters in laravel I want to display the message of success and error green/red which I am already displaying but here is I am having problem
When I entering a message of some special characters of some other like
return \Illuminate\Support\Facades\Redirect::to('')
                    ->with("modal_message_danger", "Heslo, které jste zadali, je neplatné.");

It shows me only the red bar of error, not the message which is written inside that is "Heslo, které jste zadali, je neplatné."
But when i enter in english language like:
return \Illuminate\Support\Facades\Redirect::to('')
              ->with("modal_message_danger", "password change is incorrect")

Its successfully shows me error message.
What is happening here I need your help. Your help will be appreciated!
@if ($message = \Illuminate\Support\Facades\Session::get('modal_message_danger'))

                        <button type="button" class="close" data-dismiss="alert">×</button>
                        {{ $message }}

@endif


text:
Q: Getting Java IO exception when using jenkins cli , jdk 8.144 , jenkins v2.93 This is the error.

root@myserver#java -jar
  /opt/tomcat/webapps/ROOT/WEB-INF/jenkins-cli.jar -s
http://localhost:8181 -auth ****:**** help
java.io.IOException: Bogus chunk size
at sun.net.www.http.ChunkedInputStream.processRaw(ChunkedInputStream.java:319)
at sun.net.www.http.ChunkedInputStream.readAheadBlocking(ChunkedInputStream.java:572)
at sun.net.www.http.ChunkedInputStream.readAhead(ChunkedInputStream.java:609)
at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:696)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3375)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3368)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3356)
at hudson.cli.CLI$1ClientSideImpl.<init>(CLI.java:658)
at hudson.cli.CLI.plainHttpConnection(CLI.java:684)
at hudson.cli.CLI._main(CLI.java:612)
at hudson.cli.CLI.main(CLI.java:426)

A: On further troubleshooting  I found the issue to be linked to reverse-proxy .
"The HTTP(S) connection mode of the CLI in Jenkins 2.54 and newer does not work correctly behind an Apache HTTP reverse proxy server using mod_proxy. Workarounds include using a different reverse proxy such as Nginx or HAProxy, or using the SSH connection mode where possible."
I used ssh instead .
https://issues.jenkins-ci.org/browse/JENKINS-47279


text:
Q: calling a target from a particular directory I have script that call the below target but before calling this target i want that i should be at the following location which is stored in the below variable ..
todir="${release.deployment.tool}

the target that is called is shownb below..
<target name="deploy-ion" description="Used to deploy to a given aaa.">

so finally when my target deploy-ion is being called i should make sure that  I should be in
directory  stored in todir , please advise how to achieve this.

A: I meant you can use absolute path of your property reference while performing set of tasks inside your target, as by default it uses basedir default value as cur-dir or one which is specified at project level at beginning of your build.xml file.
Also alternatively you can use ant's ant task : https://ant.apache.org/manual/Tasks/ant.html with usage like
<ant dir="${release.deployment.tool}" target="deploy-ion" />


text:
Q: What happens to my existing virtual machines when I change the Active Directory for my Azure subscription I cant find a definative answer on this:
I have an Azure subscription and have some app services and a couple of virtual machines with some iis hosted apps running on them.
I want to try out the new Azure AD B2C.  This will involve adding a new AD but it needs to be the default for my Azure Subscription.
I see that I can change my AD for my subscription* but I do not know the consequences.  Will it affect my existing Virtual machines, app instances or SQL Databases?
The following shows a screen shot of the SQL Databases tab, but VMs and app servise are the same, where the AD name is shown:
Example of SQL Databases, showing the AD name, in this case Default Directory
*itunity.com/article/how-to-change-the-default-directory-for-an-existing-azure-subscription-2494

A: The only impact I could imagine is if you have Windows 10 client VMs that are joined to Azure Active Directory. Beyond that, they should continue to operate with zero impact.


text:
Q: PyTorch: running Neural Network in identical venv-configuration - one working fine, one keeps throwing 'list index out of range' error I set up an virtual environment via 'venv' to build and train a neural network using PyTorch and JupyterLab. However, when working on my computer 'PC 1' everything works fine, but running the same code with identical Python settings on my second computer ('PC 2') keeps constantly an error ('list index out of range') thrown while training.
Any suggestions what might cause this behavior? I'm running out of ideas ...
To be more specific:

*

*On both computers Python 3.7.9 is installed via the Microsoft Store.

*To be clear: both computers access the same *.ipynb and the same data / datasets, which are synced via a cloud service.

I tried:

*

*I synced the created venv (via a cloud), activated venv and runned the *.ipynb via jupyter-lab (on 'PC 2') -> error

*I got my venv-configuration from the working 'PC 1' via  pip freeze > requirements.txt and set up a fresh venv on 'PC 2' using the requirements.txt-> error

Nevertheless I try, the thrown error is always the same.
This is the error thrown:
('julab' is my venv)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9608\2329219183.py in <module>
     10     val_dl = test_loader,
     11     epochs=num_epochs,
---> 12     device='cpu')

~\AppData\Local\Temp\ipykernel_9608\132402798.py in train(model, optimizer, loss_fn, train_dl, val_dl, epochs, device)
     27         num_train_examples = 0
     28
---> 29         for batch in train_dl:
     30
     31             optimizer.zero_grad()

d:\<CLOUD>\<SUBFOLDER>\julab\lib\site-packages\torch\utils\data\dataloader.py in __next__(self)
    650                 # TODO(https://github.com/pytorch/pytorch/issues/76750)
    651                 self._reset()  # type: ignore[call-arg]
--> 652             data = self._next_data()
    653             self._num_yielded += 1
    654             if self._dataset_kind == _DatasetKind.Iterable and \

d:\<CLOUD>\<SUBFOLDER>\julab\lib\site-packages\torch\utils\data\dataloader.py in _next_data(self)
    690     def _next_data(self):
    691         index = self._next_index()  # may raise StopIteration
--> 692         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    693         if self._pin_memory:
    694             data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)

d:\<CLOUD>\<SUBFOLDER>\julab\lib\site-packages\torch\utils\data\_utils\fetch.py in fetch(self, possibly_batched_index)
     47     def fetch(self, possibly_batched_index):
     48         if self.auto_collation:
---> 49             data = [self.dataset[idx] for idx in possibly_batched_index]
     50         else:
     51             data = self.dataset[possibly_batched_index]

d:\<CLOUD>\<SUBFOLDER>\julab\lib\site-packages\torch\utils\data\_utils\fetch.py in <listcomp>(.0)
     47     def fetch(self, possibly_batched_index):
     48         if self.auto_collation:
---> 49             data = [self.dataset[idx] for idx in possibly_batched_index]
     50         else:
     51             data = self.dataset[possibly_batched_index]

d:\<CLOUD>\<SUBFOLDER>\julab\lib\site-packages\torch\utils\data\dataset.py in __getitem__(self, idx)
    288         if isinstance(idx, list):
    289             return self.dataset[[self.indices[i] for i in idx]]
--> 290         return self.dataset[self.indices[idx]]
    291
    292     def __len__(self):

~\AppData\Local\Temp\ipykernel_9608\2122586536.py in __getitem__(self, index)
     32
     33     def __getitem__(self, index):
---> 34         image_name = os.path.join(self.image_dir, self.image_files[index])
     35         image = PIL.Image.open(image_name)
     36         label = self.data[index]

IndexError: list index out of range

And as this might help, this is my requirements.txt:
anyio==3.6.1
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
attrs==21.4.0
Babel==2.10.3
backcall==0.2.0
beautifulsoup4==4.11.1
bleach==5.0.1
certifi==2022.6.15
cffi==1.15.1
charset-normalizer==2.1.0
colorama==0.4.5
cycler==0.11.0
debugpy==1.6.0
decorator==5.1.1
defusedxml==0.7.1
dill==0.3.5.1
entrypoints==0.4
fastjsonschema==2.15.3
fonttools==4.33.3
idna==3.3
importlib-metadata==4.12.0
importlib-resources==5.8.0
ipykernel==6.15.0
ipython==7.34.0
ipython-genutils==0.2.0
jedi==0.18.1
Jinja2==3.1.2
joblib==1.1.0
json5==0.9.8
jsonschema==4.6.1
jupyter-client==7.3.4
jupyter-core==4.10.0
jupyter-server==1.18.0
jupyterlab==3.4.3
jupyterlab-pygments==0.2.2
jupyterlab-server==2.14.0
kiwisolver==1.4.3
MarkupSafe==2.1.1
matplotlib==3.5.2
matplotlib-inline==0.1.3
mistune==0.8.4
nbclassic==0.4.0
nbclient==0.6.6
nbconvert==6.5.0
nbformat==5.4.0
nest-asyncio==1.5.5
notebook-shim==0.1.0
numpy==1.21.6
packaging==21.3
pandas==1.3.5
pandocfilters==1.5.0
parso==0.8.3
pickleshare==0.7.5
Pillow==9.2.0
prometheus-client==0.14.1
prompt-toolkit==3.0.30
psutil==5.9.1
pycparser==2.21
Pygments==2.12.0
pyparsing==3.0.9
pyrsistent==0.18.1
python-dateutil==2.8.2
pytz==2022.1
pywin32==304
pywinpty==2.0.5
pyzmq==23.2.0
requests==2.28.1
scikit-learn==1.0.2
scipy==1.7.3
Send2Trash==1.8.0
six==1.16.0
sklearn==0.0
sniffio==1.2.0
soupsieve==2.3.2.post1
terminado==0.15.0
threadpoolctl==3.1.0
tinycss2==1.1.1
torch==1.12.0
torchsummary==1.5.1
torchvision==0.13.0
tornado==6.1
traitlets==5.3.0
typing_extensions==4.3.0
urllib3==1.26.9
wcwidth==0.2.5
webencodings==0.5.1
websocket-client==1.3.3
zipp==3.8.0

Has anyone an idea what's the problem and how to solve it? Many thanks in advance!

A: [solved] see comments above...


text:
Q: Sonar Issues/search API JSON result has single quotes I'm using the sonarQube 6.4 web api to get a list of issues

http://sonar-server:9000/api/issues/search?componentKeys=Project_key&sinceLeakPeriod=true&statuses=OPEN,REOPENED&types=BUG

This gives me a Json object which has single quotes,

..."message":"Make this function anonymous by removing its name:
  'function() {...}'."...

Because of that highlighted content in the JSON I'm unable to process the JSON from Groovy.
Is the JSON returned by the sonar is valid ?
if so, is there any way to process this kind of JSON in groovy.
Let me know if the full JSON object is needed.

A: According to http://json.org/ and https://jsonformatter.curiousconcept.com/  the JSON response is valid. Single quotes and brackets {} must not be escaped. The issue comes from your Groovy parser.


text:
Q: Switching to Ubuntu from Windows I've been using Ubuntu for a while now. I still have windows installed and it's taking up the majority of my hard drive space. I want to fully switch to Ubuntu though. I've backed up everything I need from Windows and I'm ready to get rid of it. I just don't know how to do it. Here is a Screenshot from gParted.

A: Using gparted you should be able to select the ntfs partitions you want to delete and delete them - Once deleted you have to format the unpartitioned space into ext4 or fat32 (again using gparted) - If you dont want to completely remove windows you can shrink the windows partition down using diskmgmt.msc from windows
If you decide to completely remove Windows via gparted as described you will have to either 1) flag your sda5 partition as boot or 2) create a new partition for /boot and and move the files from its current location to the new /boot partition. Also you will want to remove windows from the grub menu -
A tool that I use to 'fix' my grub boot loader is (http://sourceforge.net/projects/boot-repair-cd/files/) - I have this installed on a usb that i keep in my toolbox
If you want to manually do this:
Make a bootable disk for Gparted - (http://gparted.org/livecd.php)
I use this to make bootable usb's - (http://unetbootin.sourceforge.net/) - however you want will be good bud.
Gparted can be used to make a boot partition (mine is formatted ext2 but i dont think theres any issue with making it all ext4) - minimum size of this partition is 200 mb (you dont want it to be too big at all) and you will want to flag it as /boot.
Some examples for you: (Things are named aptly so you can logically see the process)
/dev/sda2 - 200 MB new boot partition
/dev/sda1 - 50 GB existing linux partition

Make mount points.
mkdir /mnt/newboot /mnt/existing

Mount the partitions:
mount /dev/sda2 /mnt/newboot
mount /dev/sda1 /mnt/existing

Copy /boot files:
cp -a /mnt/existing/boot/* /mnt/newboot/

Unmount the boot partition from /mnt and remount to /boot:
umount /dev/sda2
mount /dev/sda2 /newboot

To remove windows from Grub:
sudo gedit /boot/grub/grub.cfg

You can (put a #) in front of each line to "comment out" the entries pertaining to Microsoft Windows - or if you are comfy with just deleting them - so be it.  I usually make a copy of any conf file i mess with and save it in my home dir just in case i screw something up.


text:
Q: Call to undefined function mysqli_init() An uncaught Exception was encountered
Type: Error
Message: Call to undefined function mysqli_init()
Filename: /home/sourcecars/public_html/carsonbarlcon.com/system/database/drivers/mysqli/mysqli_driver.php
Line Number: 135
Backtrace:
File: /home/sourcecars/public_html/carsonbarlcon.com/application/hooks/EloquentHook.php
Line: 31
Function: database
File: /home/sourcecars/public_html/carsonbarlcon.com/application/hooks/EloquentHook.php
Line: 46
Function: loadDatabase
File: /home/sourcecars/public_html/carsonbarlcon.com/index.php
Line: 316
Function: require_once
Install mysqli php extension

A: *

*please check php-mysqli is installed?

*check php.ini and make sure the extension is loaded.
extension=php_mysqli.dll

*if it's a php framework make sure in the framework config.php file what driver you are using.


text:
Q: How to define an iterator interface type? I've written a class that implements IEnumerable<T>. I have a method that returns MyClass. If I try to  yield return from within that method, the compiler tells me "... cannot be an iterator block because ... is not an iterator interface type".
So, how can I define my own interface iterator type? Does it have to be "abstract" (can't have any methods defined)?
What I want to do is write a bunch of chainable methods, so every method should return an instance of MyClass. But I need MyClass to be some kind of enumerable. Rather than using some underlying data type, I was hoping I could just yield return everywhere.

@Oded:
class SharpQuery : IEnumerable<HtmlNode>
{
    public SharpQuery Find(string selector)
    {
        foreach (var n in this)
        {
            // filter the results
            yield return node;
        }
    }
}

A: I think when you use yield return x you will be producing an IEnumerable of X type. So in your case it would be IEnumerable
Inheriting from one class would not automatically mean it will implicitly cast itself to that type. So if you write
class SharpQuery
{
    public IEnumerable<HtmlNode> RepositoryItems { get; set; }
    public IEnumerable<HtmlNode> Find(string selector)
    {
        foreach (var n in this.RepositoryItems)
        {
            // filter the results
            yield return node;
        }
    }
}

it works. IEnumerable is not same as SharpQuery.

A: According to section 8.2 of the C# Language Specification Version 4.0:

A block that contains one or more yield statements is called an iterator block. Iterator blocks are used to implement function members as iterators.

Section 10.14 specifies that the return type of an iterator must be one of the following:

*

*IEnumerator

*IEnumerable

*IEnumerator<T>

*IEnumerable<T>
According to section 10.14.4, invoking an iterator does not immediately execute the code in the iterator block. Instead, an enumerator object that implements the following interfaces is created and returned:

*

*IEnumerator

*IEnumerator<T>

*IDisposable
The enumerator object is typically an instance of a compiler-generated nested class with private accessibility.

A: No, that's not possible. To see why consider that you have a class Zoo that implements IEnumerable<Animal> but also has lots of other members. A Zoois an IEnumerable<Animal> but not necessarily vice versa - a sequence of animals is just a sequence of animals. There's no zoo keeper, no shops, no entrance fee or any of the other things that makes a zoo a zoo.
When you use yield return x the return type cannot be Zoo because you don't have a zoo - you just have a sequence of animals.
What you can do instead is to call it as new Zoo(foo()) where foo returns an IEnumerable<Animal> and add a constructor to Zoo that accepts an IEnumerable<Animal>.


text:
Q: If condition and a proc sql inside a macro program I have a control to verify.
I want to write a macro variable who includes an SQL proc in case the condition is verified.
Exemple:
%Macro Control1(List) / minoperator mindelimiter=' ';

%IF &Control1 in &List. %Then %do;

proc sql;

create table work.&Control1 as

Select id, count(id) as number

From data.&Produit.

group by id
having calculated number > 1
;
quit;

%end;

%mend;

%let list = &control1. &control2 &Control4 ;

%Control1(&List);

If we do the same process to control3 the proc sql doesn't run because control3 doesn't belong to the list.
I might have some mistakes in the syntax
/*CONTROL1 and PRODUIT ARE ALREADY DECLARED */

A: Your main problem is that you need to let SAS know that you want to use in as an operator in your macro logic.
To enable use of IN as an operator in macro language then you need set the MINOPERATOR option.  To insure it always works for your macro independent of how the system option is set add it to the %macro statement.
%macro Control1(List) / minoperator mindelimiter=' ';

But you also have a number of other issues.
When defining a parameter to the macro you just want to type the name you want to parameter to have.  Your example has an & before the name which would be invalid syntax and that is used to reference the value of macro variable and you cannot use the value to macro variable to name your parameter.  So when defining the macro just list the name
%macro control1(list) .....

Note than when you CALL the macro is fine to reference a macro variable when passing in the parameter value to the macro, as you have done in your example call.
The %if statement has multiple problems. The first appears to just be a typo with an extra e added to the end of the list macro variable's name.  The second is a logical mistake.  The value the macro variable CONTROL1 is never going to be the same as that value with double quote characters around it.  Also the () around the list of values for the in operator are not needed, but they won't cause any actual problems.
%if &control1 in &list %then %do;

Your SELECT statement is missing a comma between the two variables you are selecting.
select id,count(id) as number

The condition in your HAVING clause is not valid syntax.  Are you trying to test if the count is larger than 1?  Plus if you want to reference a variable you have calculated you need to use the CALCULATED keyword.
having calculated number > 1

Finally it is potentially confusing to reference two macro variables, CONTROL1 and PROUDUIT, in your macro that are not defined by the code (or even documented in a comment).  They are not input parameters. You have not declared them as local macro variables.  Or done anything to insure that they will exist.


text:
Q: Non blocking wait for condition evaluation in c# I have a class which has a property called ActiveDelay which is used to define a duration during which a condition evaluation should wait before checking if the condition is still true after that time. The property SetpointA is the value used to compare the given value to.
Below is what I am currently doing
public void EvaluateCondition(T value)
{
    if(value.Equals(SetpointA))
    {
        Task.Delay(ActiveDelay).ContinueWith(_ => EvaluateConditionDelayed(GetValue())).Wait();
    }
}

private void EvaluateConditionDelayed(object value)
{
    if (value.Equals(SetpointA))
    {
        Console.WriteLine("Waited and worked");
    }
    else
    {
        Console.WriteLine("Condition now false");
    }
}

I am calling the function EvaluateCondition twice, once with a TimeSpan of 5 seconds and another time with a TimeSpan of 2 seconds and I expect that the 2 second call should finish before the 5 second call but what actually happens is that the 5 second call waits and then the 2 second call waits.
I assume there is somethings to do with async and await here but I haven't found information that helps me.
Something I want to make absolutely clear, THESE DELAYS SHOULD NOT PAUSE THE PROGRAM, they should only wait externally and allow the rest of the program to run unaffected.
EXTENSIVE CODE SECTION
Here is an extensive version of the above
public class AlarmCondition
{
    #region Property declaration
    public TimeSpan ActiveDelay { get; set; } // Need to be historised ?
    public TimeSpan ClearDelay { get; set; } // Need to be historised ?
    #endregion

    #region Constructor
    public AlarmCondition() { }

    public AlarmCondition(TimeSpan activeDelay, TimeSpan clearDelay)
    {
        ActiveDelay = activeDelay;
        ClearDelay = clearDelay;
    }
    #endregion

}

public class EqualCondition<T> : AlarmCondition
{
    #region Property declaration
    public T SetpointA { get; }
    #endregion

    #region Constructor
    public EqualCondition() { }

    public EqualCondition(TimeSpan activeDelay, TimeSpan clearDelay) : base(activeDelay, clearDelay)
    {
        SetpointA = setpointA;
    }
    #endregion

    public void EvaluateCondition(T value)
    {
        if(value.Equals(SetpointA))
        {
            Task.Delay(ActiveDelay).ContinueWith(_ => EvaluateConditionDelayed(value));
        }
    }

    private void EvaluateConditionDelayed(T value)
    {
        if (value.Equals(SetpointA))
        {
            Console.WriteLine("Waited and worked");
        }
        else
        {
            Console.WriteLine("Condition now false");
        }
    }
}

// In another file and namespace
public class ConsoleDisplay
{
    public static void Main(string[] args)
    {
        EqualCondition<bool> condition1 = new EqualCondition<bool>(new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 5));
        EqualCondition<bool> condition2 = new EqualCondition<bool>(new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 5));

        condition1.EvaluateCondition(true);
        condition2.EvaluateCondition(true);
    }
}

A: You can return Task from your method so the caller will decide if he wants to wait for the result. For example:
public async Task EvaluateCondition(T value)
{
    if(value.Equals(SetpointA))
    {
        await Task.Delay(ActiveDelay);
        EvaluateConditionDelayed(GetValue());
    }
}

Or just remove .Wait() (which blocks) from your current implementation if you don't want caller to have an option for such decision. The task should still print in the console even without it (if your program runs long enough):
public void EvaluateCondition(T value)
{
    if(value.Equals(SetpointA))
    {
        Task.Delay(ActiveDelay).ContinueWith(_ => EvaluateConditionDelayed(GetValue()));
    }
}

UPD
To start multiple EvaluateCondition and wait for them to finish in parallel you can use Task.WhenAll:
var ev1Task = EvaluateCondition(someVal1);
var ev2Task = EvaluateCondition(someVal2);
await Task.WhenAll(ev1Task, ev2Task);

If you don't want to await then just skip the await Task.WhenAll(ev1Task, ev2Task) (and fix the warnings).


text:
Q: Confusion about the expected distance between two gaussian random variables This math stack exchange answer gives a very nice solution for the expected squared L2 norm of any gaussian random variable:
$$ \mathbb{E}\{\|Z\|^2\} = \| \mu \|^2 + Tr(\Sigma)$$
I walked through the derivation and it all makes sense to me, but I'm having trouble lining this up with my intuition about the gaussian distribution. As I understand, we can visualize the covariance $\Sigma$ as an ellipsoid, where the major/minor axes are given by the eigenvectors of $\Sigma$, and the eigenvalues tell us the scale of the ellipsoid in that direction. Also, the i'th diagonal element of $\Sigma$ is the variance of $Z_i$.
So $Tr(\Sigma)$ is the sum of the variances of $Z_i$. It makes sense that this should be the case. However, we also should be able to rotate the gaussian distribution about the mean and still have the same value for $\mathbb{E}\{\|Z\|^2\}$. But doing so would involve changing $Tr(\Sigma)$, right?
To concisely summarize: Why is $Tr(\Sigma)$ invariant to rotations about the mean?

A: The question has been answered, but I would like to point out that your identity has nothing to do with the Gaussian distribution and it would hold for any random vector $Z$; rather it is a simple consequence of the bias-variance decomposition of the mean squared error:
$$E[\|\hat\theta-\theta\|^2]=\|E[\hat\theta]-\theta\|^2+ tr(V(\hat\theta)),$$
where $\hat \theta$ is some random vector thought of as an estimator for parameter $\theta$. Your identity is the case where $\hat\theta=Z\sim N(\mu,\Sigma),\theta=0.$

Here is a simple proof to convince you. First, recall some properties:

*

*$V(X)=E[XX']-E[X]E[X']$

*$tr(A+B)=tr(A)+tr(B)$

*$tr(AB)=tr(BA)$.

Then we have
$$\begin{align}tr(V(\hat\theta))&=tr(V(\hat\theta-\theta))\\
&=tr(E[(\hat\theta-\theta)(\hat\theta-\theta)']-E[\hat\theta-\theta]E[(\hat\theta-\theta)'])\quad (1)\\
&=tr(E[(\hat\theta-\theta)(\hat\theta-\theta)'])-tr(E[\hat\theta-\theta]E[(\hat\theta-\theta)'])\quad (2)\\
&=tr(E[(\hat\theta-\theta)'(\hat\theta-\theta)])-tr(E[\hat\theta-\theta]'E[\hat\theta-\theta])\quad (3)\\
&=E[\|\hat\theta-\theta\|^2]-\|E[\hat\theta]-\theta\|^2\\
\implies E[\|\hat\theta-\theta\|^2]&=\|E[\hat\theta]-\theta\|^2+ tr(V(\hat\theta))& \end{align}$$

A: Your rotation would entail replacing $\Sigma$ with $U \Sigma U^\top$ for some rotation $U$. Then $\operatorname{Tr}(U \Sigma U^\top) = \operatorname{Tr}(\Sigma U^\top U) = \operatorname{Tr}(\Sigma)$.


text:
Q: How to use Data Contracts as Model for scaffolding in MVC5 I have defined DataContracts in a different Library and I am referencing it in the MVC5 Application. In Visual Studio I want to use this Model and Generate Views using Scaffolding.
The Problem is when I click on Add View in the Action method inside Visual Studio 2013 I can see only Model defined in the MVC Application and not the entities in defined in Data Contracts.
How can I make a DataContracts appear in Model Dropdown in Visual Studio 2013 while adding View?


text:
Q: Firebase dynamic links, show another activity in action I try to show another activity in AppInviteApi.getInvitation callback.
mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this , this )
    .addApi(AppInvite.API)
    .build();
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, this, autoLaunchDeepLink)
    .setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
    @Override
    public void onResult(@NonNull AppInviteInvitationResult result) {
        if (result.getStatus().isSuccess()) {

            Intent intent = result.getInvitationIntent();
            String deepLink = AppInviteReferral.getDeepLink(intent);
            String[] strings=  deepLink.split("\\%");
            String key =strings[strings.length-1];
            Intent intent2=new Intent(GroupsActivity.this,MainActivity.class);
            intent2.putExtra("groupKey",key);
            startActivity(intent2);
        } else {
        }
    }
});

After this action, I observe an endless cycle in which consecutive  MainActivity and GroupsActivity starts. How to correctly start an another activity in this case?

A: I've got the same problem. The endless cycle.
I start wrong intent.
you have to check your code
Intent intent2=new Intent(GroupsActivity.this,MainActivity.class);
            intent2.putExtra("groupKey",key);
            startActivity(intent2);

Check this line.
new Intent("your context", "activity your wanna go.");


text:
Q: How to get randomForest model output in probability using Caret? I am trying to use Caret for building random forest model for binary classification. I have used randomForest source package to do this in past and it worked fine but using Caret my output is binary rather then probability.
With type='prob', it gives error
Error in [.data.frame(out, , obsLevels, drop = FALSE) :  undefined columns selected
I am using the same syntax (I hope) for both. This is what I used to get with source randomForest package.
>fit = randomForest(x = a[,-1], y = as.factor(a[,1]),ntree=120)
>head(predict(fit, newdata = test_data[,-c(1:2)], type = "prob")[,2])
         1          2          3          4          5          6
0.04166667 0.03333333 0.55833333 0.80000000 0.87500000 0.04166667

Now, using Caret I am trying to do the same but its not accepting " type='prob' " in predict function, giving me the error
>rf_model<-train(x = a[,-1], y = as.factor(a[,1]),method="rf",ntree=120)
>head(predict(rf_model, test_data[,-c(1:2)], type="prob"))
Error in `[.data.frame`(out, , obsLevels, drop = FALSE) :
undefined columns selected

Rather when I take out the "type", it gives me
>head(predict(rf_model, test_data[,-c(1:2)]))
[1] 0 0 1 1 1 0
Levels: 0 1

How do I get output in probabilities?
I need to create multiple algorithms after this and I think Caret would be more homogeneous to do that. I am sure I am missing something here but being new to Caret I don't know what.

A: UPDATE: I found the solution through here. Apparently, caret's train is not good with handling 0 and 1 binary class values in target variable. Changing them to any string ('r' and 's') worked perfectly.
> a$dv<-gsub('0','r',a$dv)
> a$dv<-gsub('1','s',a$dv)
> rf_model<-train(x = a[,-c(1:2)], y = as.factor(a[,2]),method="rf",ntree=120)
> head(predict(rf_model, test_data[,-c(1:2)], type="prob"))
      r           s
1 0.9750000 0.025000000
2 0.9916667 0.008333333
3 0.2583333 0.741666667
4 0.2833333 0.716666667
5 0.1583333 0.841666667
6 1.0000000 0.000000000

A: Try to keep type = "prob", so that the predictions will be:
prd <- predict(rf_model, test_data[,-c(1:2)], type="prob")
but do whatever in Caret with:
as.factor(as.numeric(prd >= .5))

A: It works fine with caret v6.0-41:
library(caret)
set.seed(1)
rf_model <- train(x = iris[,-5], y = as.factor(iris[,5]), method="rf", ntree=120)
tail(predict(rf_model, iris[, -5], type="prob"))

    setosa  versicolor virginica
145      0 0.000000000 1.0000000
146      0 0.000000000 1.0000000
147      0 0.008333333 0.9916667
148      0 0.000000000 1.0000000
149      0 0.000000000 1.0000000
150      0 0.025000000 0.9750000

R version 3.0.3 (2014-03-06)
Platform: x86_64-w64-mingw32/x64 (64-bit)
I think the problem comes from your training data (a[,-1]) and testing data (test_data[,-c(1:2)]) not having exactly the same columns.

A: You've probably long ago resolved this...but on current rev of caret, type = "prob" for a 2 level factor outputs 2 columns:  probability of 0, probability of 1 (or whatever your 2 levels are).