text:
Q: Is there a way to have a table with values that references the columns themselves of another table? I have a database where data about users is stored in a table that looks like this
|_firstname_|_lastname_|_age_|...
|   John    | Johnson  |  21 |...
...

i.e. using the normal relational database model.
If I instead switched to an EAV model for storing the above data, the columns (called attributes in EAV) themselves would be stored in a table and would have unique column (attribute) ID:s. The benefit of this is that I could use these ID:s in another table to connect data to the columns themselves, such as whether the column is hidden or showed in the user UI (below also using an EAV model):
|____column_id____|___attribute___|___value___|
| <firstname_id>  |    hidden     |   false   |
| <lastname_id>   |    hidden     |   false   |
|    <age_id>     |    hidden     |   true    |
...

However, I would like to stick to the relational database model for the user data table (the table shown first), since querying otherwise becomes a lot slower, but I would still like to connect values to the columns like I can if I were to use an EAV model.
Is there a way of having a table that stores data about the columns themselves of the user data table in a rigorous way?

A: The simplest implementation of EAV may have just three tables: entity, attribute and value. An example of this setup is shown here:

and so your table could look like :
|attribute_id| name       | is visible |
|10          | firstname  | 1          |
|11          | lastname   | 1          |
|12          | age        | 0          |

|entity_id  | entity_name |...
|1          | person1     |
|2          | person2     |

|row_id |attribute_id| entity_id | entity_id  |
|155    |10          | 1         | John       |
|156    |11          | 1         | Doe        |
|199    |12          | 1         | 28         |
|....    ....         ....        ....
|255    |10          | 2         | Ali        |
|256    |11          | 2         | Smith      |
|279    |12          | 2         | 25         |


text:
Q: Multiple Follow ID's causing Status 401 error for Twitter stream API I am only receiving an error when I add multiple twitter USERid's. When I just one at at time, it's fine, no errors.
Here is my code: https://hastebin.com/bitabojuhe.js
When I add more than one, it returns this error. The keys are fine because as soon as I delete the array and just make one user ID it works again. Very strange issue.
Error: Status Code: 401
at Request.emit
at ClientRequest.emit
at HTTPParser.parserOnIncomingClient [as onIncoming
at HTTPParser.parserOnHeadersComplete
at TLSSocket.socketOnData
at TLSSocket.emit
at addChunk
at readableAddChunk

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-language in params I'm using CodeIgniter framework I would like my urls to be like
http://localhost/myproject/en/
http://localhost/myproject/fr/
But as you know en/ and /fr are interpreted as controllers.
How, by adding as http://localhost/myproject/controller?lang=fr, can I convert it to http://localhost/myproject/lang/controller/?


text:
Q: Android stop asynctask I have created an asynctask to show progress dialog while ghetting the users location. I want to run this asynctask for 30 seconds and if in these 30 seconds I haven't found the users location I would like just to kill the task and show an error message.
My code so far is like this:
userLocation = new AsyncTask<Void, Void, Void>() {

            private ProgressDialog locationDialog = new ProgressDialog(MainActivity.this);

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                locationDialog.setMessage(getResources().getString(R.string.getting_location));
                locationDialog.setCancelable(false);
                locationDialog.setIndeterminate(true);
                locationDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                    try {
                        latitude = locationProvider.getLatitude();
                        longitude = locationProvider.getLongitude();
                        Thread.sleep(10000);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
            //  getLocation.cancel(true);
                if (latitude != 0 && longitude != 0) {
                    locationDialog.dismiss();
                    getData();
                } else {
                    locationDialog.dismiss();

                    alertDialog.show();

                    Log.d("Couldn't get location", "Couldn't get location");
                }
            }
        };
        userLocation.execute((Void[])null);

How should I edit my code so that if the latitude and longitude after 30 seconds is 0, just kill the asynctask and show some kind of error message. Any ideas?

A: You should make a handler which cancels the Asynctask (http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean))
Send a delayed message to this Handler like:
Handler.sendMessageDelayed(msg, delayMillis)

private android.os.Handler mHandler = new android.os.Handler() {

  @Override
  public void handleMessage(Message msg) {
      (Your AsyncTask object).cancel(true);
  }
}


text:
Q: Why my keyboard hit is evaluating false I'm a C++ noob coding the snake game. The whole program draws the board, fruit and snake head perfectly, however I cannot seem to make the snake head coordinates change using a keyboard hit function. When going through the input function which gets keyboard strokes for snake movement, it appears that the if(kbhit) evaluates to false when running program,what is my error and how can I get the snake head to move?
Thanks.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <conio.h>
using namespace std;

int X, Y, fruitX, fruitY;
enum eDir { STOP = 1, UP = 2, DOWN = 3, RIGHT = 4, LEFT = 5 }; //declare variables
eDir direction;
const int height = 20;
const int width = 20;
int board[height][width];
bool gameOver;

void setup()
{
    gameOver = false;
    srand(time(NULL));          // initilize game set up
    fruitX = (rand() % width);
    fruitY = (rand() % height);
    X = height / 2;
    Y = width / 2;
    direction = STOP;
    int board[height][width];
};

void draw()
{
    system("cls");

    for (int i = 0; i < width + 2; i++)
        cout << '#';

    cout << endl;

    for (int i = 0; i < height; i++)    //loop through matrix to draw board
    {
        for (int j = 0; j < width; j++)
        {

            if (j == 0)
                cout << '#';
            if (i == Y && j == X) // draw snake head
                cout << 'T';
            else if (i == fruitY && j == fruitX) // draw fruit
                cout << 'F';
            else
                cout << ' ';

            if (j == width - 1)
                cout << '#';
        }
        cout << endl;
    }

    for (int i = 0; i < width + 2; i++)
        cout << '#';

    cout << endl;
};

void input()
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'w':
            direction = UP;
            break;
        case 's':
            direction = DOWN;
            break;
        case 'a':
            direction = LEFT;
            break;
        case 'd':
            direction = RIGHT;
            break;
        default:
            break;
        }

    }
};

void logic()
{
    switch (direction)
    {
    case UP:
        Y--;
        break;
    case DOWN:
        Y++;
        break;
    case LEFT:
        X--;
        break;
    case RIGHT:
        X++;
        break;
    default:
        break;
    }
};

int main()
{
    setup();
    while (!gameOver)
    {
        draw();
        input();
        logic();
        return 0;
    }
};

A: For one thing, you do return 0; inside your game loop which kills the program after only one iteration which I assume you did not intend.
I made snake using a similar method and mine looks like this:
bool play = true;

while(play) {
    while (_kbhit) {
        switch (_getch) {
        case 'w':
            //code
            break;
        case 's':
            //code
            break;
        case 'a':
            //code
            break;
        case 'd':
            //code
            break;
        }
    }
}

That method worked for me and I think the only difference is that I used a while loop instead of an if.


text:
Q: If an open set is evenly covered by $p$, then its open subset is also evenly covered by $p$. If $U$ is an open set evenly covered by $p: E\to B$ and $W$ is an open set contained in $U$, then $W$ is also evenly covered by $p$.
I'm trying to prove this statement, but have a difficulty.
So by definition, we have a partition of $p^{-1}(U)$ into slices, say, $\{V_\alpha\}$. The obvious choice of a partition of $p^{-1}(W)$ would be $\{V_\alpha \cap p^{-1}(W)\}$, which is a collection of disjoint open sets in $E$. Clearly, the union of this collection is $p^{-1}(W)$, so we're left to show that for each $\alpha$, the restriction of $p$ to $V_\alpha \cap p^{-1}(W)$ is a homeomorphism of $V_\alpha \cap p^{-1}(W)$ onto $W$. This is what I'm struggling to show.
First, this restriction is clearly injective, since it is a restriction of an injective function, and so it has an inverse, which is again a restriction of the inverse of $p|V_\alpha$, so is continuous as well. But how can I show that the image is $W$? That is, $p(V_\alpha \cap p^{-1}(W))=W$? I would greatly appreciate any help on this.

A: Here are two general facts about a set theoretic map $f:X\to Y$ -

*

*If $B\subseteq Y$ then $f(f^{-1}(B))=B$ when $f$ is surjective.

*If $U,V\subseteq X$ then $f(U\cap V)=f(U)\cap f(V)$ when $f$ is injective.
Now in your case $p|_{V_\alpha}$ is a bijection. So, $$p(V_\alpha\cap p^{-1}(W))=p(V_\alpha)\cap p(p^{-1}(W))=U\cap W=W$$


text:
Q: Firestore adds search conditions and cannot continue to monitor When the search condition is not added, the changes can be listened to in real time, but after I add the search condition, I cannot continue to monitor the changes. Why?
original code
 db.collection("Users").document("pZOLUl9tyVdOKzyeUScIZ8BysPm1")
.collection("RechargeCoin")
.order(by: "date", descending: true)
.addSnapshotListener { (snapshot, error) in

Code after adding search criteria
  db.collection("Users").document("pZOLUl9tyVdOKzyeUScIZ8BysPm1")
.collection("RechargeCoin")
.whereField("review2", isEqualTo: "未確認")
.order(by: "date", descending: true)
.addSnapshotListener { (snapshot, error) in

Modified code cannot listen for changes

A: Every query on Firestore needs an index that matches the exact fields that you order/filter on. When no such index exists, the query can't be executed and the SDK throws an error.
The behavior you're describing typically means that the necessary index is missing. You'll want to catch and log any errors coming from the Firestore API calls and then check in the error message for a URL. This URL takes you directly to the Firestore console in a page where you can create the necessary index with a single click (all fields will be prepopulated in the URL already).


text:
Q: How to use JavaScript variables multiple times in HTML How can you display one variable multiple times in HTML? When the variable banana increases it only increases for one of the spans using the variable banana.
<!DOCTYPE html>

Example Code

<button class="button" onclick="Addbanana()">Add 1 Banana</button>

Bananas =  0

Bananas =  0

Bananas =  0

A: *

*Instead of using banana IDs, use banana classes. IDs are meant to be unique... but since you have three places where you want to use it, you're better off using classes.

*Since you're then using classes, use getElementsByClassName instead of getElementById

*This returns an array-like object, so iterate through it, and change the innerHTML as you did before

*???

*Profit!

A: <!DOCTYPE html>

Example Code

<button class="button" onclick="Addbanana()">Add 1 Banana</button>

Bananas =  0

Bananas =  0

Bananas =  0


text:
Q: What is the meaning of a code block after a "use module"? What is the significance and what is the effect of something like this (I think it is object oriented):
use My::Confusing::Code
{
   CITY  => { MODIFY      => 1,
              DEFAULT     => My::Even::more::complicated->func(),
            },
   STATE => { MODIFY      => 1,
              DEFAULT     => 'Concatenate()',
            },
   COUNTRY => { MODIFY       => 1,
                REQUIRED     => 0,
                DEFAULT      => 'Gabon',
               },
}

What would the My::Confusing::Code package/module/class do with the stuff in the curly braces.  Do the curly braces enclose a code block or a hash reference?

A: It's a hash reference.
When you do use Module::Foo @stuff;, what's happening behind-the-scenes is:
BEGIN {
    require "Module/Foo.pm";
    Module::Foo->import( @stuff );
};

Normally, the parameters passed to import are used to ask for symbols to be exported into your namespace. (The typical way to do this is to use the import subroutine from the standard Exporter module.) But in this case, the module author has written a custom import method that takes a hashref and does stuff with it.


text:
Q: Instance vs Class variables and Random Numbers Ruby Hello I am writing a code for a simple die of (n) sides and it works fine:
class Die

  def initialize(sides)
    @sides = sides
    raise ArgumentError if sides < 1
  end

  def roll
    roll_number = rand(@sides) + 1
  end
end

However, when I change my initialized variable from instance to class the random numbers generated go from integers to a bunch of small floating point numbers around 1.
class Die

  def initialize(sides)
    HERE --> @@sides = sides
    raise ArgumentError if sides < 1
  end

  def roll
    roll_number = rand(@sides) + 1
  end

end

I wanted to know what may cause this difference?

A: In the second code snippet, you're initializing the class variable @@sides but still passing the instance variable @sides to rand(). Since @sides is not initialized, you are passing nil to the call to rand(), so Kernel#rand gives a float instead of integer.

A: There's an error in your code, in your second version of Die you actually never call the right variable in your roll method.
It should be:
  def roll
    roll_number = rand(@@sides) + 1
  end

Instead yours was evaluating to:
roll_number = rand(nil) + 1

According to the rand library if you don't supply an argument rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.


text:
Q: Multiple meta key and value search in the query I am have this following API code for $_REQUEST
$metakey        = explode(',',$wpdb->escape($_REQUEST['key']) );
$metavalue      = explode(',',$wpdb->escape($_REQUEST['value']) );

$meta = array();

$i = -1;

foreach ($metakey as $key) {

    $i++;

    if( $metavalue[$i] && trim($metavalue[$i]) != "")
        $meta[] = array( 'key' => $key, 'value' => $metavalue[$i] );
    else
        $meta[] = array( 'key' => $key );

}

$meta['relation'] = 'AND';

$args = array();
$args['meta_query'] = $meta;

$query = new WP_Query( $args );

It gives the right result:
api.php?key=fruit,drink&value=cherry,whiskey

It gives the right result for fruit -> cherry and drink -> any:
api.php?key=fruit,drink&value=cherry

But this program do not for fruit -> any and drink -> whiskey:
api.php?key=fruit,drink&value=any,whiskey

How to pass the meta_value empty value or "any" string?

A: You don't have any conditions for "any" as a given value in your code, so it won't be treated as any, but as "any".
But your code checks if given value is not empty, so passing it like so should work:
api.php?key=fruit,drink&value=,whiskey

PS. I'm not sure if that's the best way of passing arguments to your api ;)


text:
Q: Symfony3 – Form submission with clearMissing – nullified properties always – how to fix this? i'm using "Symfony ~3.3".
If i send in request only bar property (without zyx because i don't need to change it), i get error:

Type error: Argument 1 passed to AppBundle\Entity\Foo::setZyx() must be of the type string, null given, called in /full/path/to/project/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 636

My question is simple: why clearMissing parameter is ignored and how to achive editing only selected properties?

Some code here:
Controller:
class FooController extends Controller
{
    /**
     * @Rest\Patch("/foo/{id}", requirements={"id": "\d+"})
     *
     * @Rest\RequestParam(name="bar", nullable=true)
     * @Rest\RequestParam(name="zyx", nullable=true)
     *
     * @param int          $id
     * @param ParamFetcher $pf
     *
     * @return Response
     *
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
     */
    public function editAction(int $id, ParamFetcher $pf) : Response
    {
        $foo = $this->repository->find($id);
        if (!$foo) throw $this->createNotFoundException();

        $form = $this->createForm(FooType::class, $foo);
        $form->submit($pf->all(), false); // <––––– HERE

        if (!$form->isSubmitted() || !$form->isValid())
            throw new BadRequestHttpException($this->view($form->getErrors(true))->getData());

        $foo = $form->getData();
        $this->em->merge($foo);
        $this->em->flush();

        return $this->responder->respond($foo);
    }
}

Doctrine entity:
/**
 * @ORM\Entity()
 */
class Foo
{
    /**
     * @Assert\NotBlank()
     * @Assert\Length(min="3", max="190")
     * @ORM\Column(type="string", length=190)
     */
    private $bar;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(min="3")
     * @ORM\Column(type="text")
     */
    private $zyx;

    public function __construct(string $bar, string $zyx)
    {
        $this->bar = $bar;
        $this->zyx = $zyx;
    }

    public function getBar() : string { return $this->bar; }
    public function getZyx() : string { return $this->zyx; }

    public function setBar(string $v) { $this->bar = $v; }
    public function setZyx(string $v) { $this->zyx = $v; }
}

Form type:
class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('bar', TextType::class)
            ->add('zyx', TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class'      => Foo::class,
            'csrf_protection' => false,
            // todo Better way to workaround constructor requirements?
            'empty_data'      => new Foo('_', '_'),
        ]);
    }
}

Changing controller like this will solve issue.. but.. that's really ugly and decreases maintainability. Is here any other way?
class FooController extends Controller
{
    public function editAction(int $id, ParamFetcher $pf) : Response
    {
        $foo = ...;

        $form = $this->createForm(FooType::class, $foo);

        $submit = [];
        $bar = $pf->get('bar');
        $zyx = $pf->get('zyx');
        if (!empty($bar)) $submit['bar'] = $bar;
        if (!empty($zyx)) $submit['zyx'] = $zyx;
        $form->submit($submit, false);

        ...
    }
}

A: Um this doesn't work?
      public function __construct(string $bar, string $zyx = ""){
          if( strlen( $zyx  ) > 0 )  $this->zyx = $zyx;
          $this->zyx = $zyx;
         ...
      }

If you felt inclined to cheat on the setter you could do this
  public function __set( $key, $value ){
      if( !method_exits( $this, '_'.$key ) ) throw new Exception('unknown method' );

      if( !empty( $value ) )  $this->'_'.$key( $value );

  }

  protected function  _setZyx(string $v) { $this->zyx = $v; }

Then when you call the setZyx() ( undefined ) it uses the magic set method that filters out empty values....  I don't use Symphony so I don't know if they check method_exists() etc..  I just thought it would be fun
UPDATE
Looking at your update you can do it this way too
    $submit = [];
    $submit['bar'] = $pf->get('bar');
    $submit['zyx'] = $pf->get('zyx');

    $submit = array_filter( $submit ); //you may need a custom callback,

    $form->submit($submit, false);

But it may be more maintainable that way, you could even extend $form class and override the submit function and bake it in that way.
I am not a symphony user ( so I don't know the convention for overriding stuff )  but personally I would do something like this after extending the $form class
  public function submit( $submit, $arg1, $filter = false ){
      //sorry not sure what the second arg is, but anyway

      if( $filter ){
          if( gettype( $filter ) == 'boolean' )
              $submit = array_filter( $submit );
          else
              $submit = array_filter( $submit, $filter );
      }

      parent::submit( $submit, $arg1 );
  }

Then it's backed into the class, and you can either call true or give it a closure to use as the filter, such as
    $form2->submit( $submit, false, function( $item ){
         return strlen( $item );
    });

You could also wrap it in another function inside a base controller or some helper class ( and pass $form to it ), then you don't need the code all over the place.


text:
Q: Perl MySQL Problem I'm a complete Perl noob, I'm a PHP programmer and I'm trying to learn Perl, currently using Tizag's tutorial.
I am running it on a Windows Xampp Install located at c:\xampp -
I have this code, which is giving me an error.
use strict; use warnings;
use CGI::Simple;
use DBI;

$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "root";
$pw = "";

$connect = Mysql->connect($host, $database, $user, $pw);

@databases = $connect->listdbs;
foreach $database (@databases) {
    print "$database
";
}

The error:

Can't locate CGI/Simple.pm in @INC (@INC contains: C:/xampp/perl/site/lib/ C:/xampp/perl/lib C:/xampp/perl/site/lib C:/xampp/apache) at C:/xampp/htdocs/testing/learn_perl/index.pl line 5. BEGIN failed--compilation aborted at C:/xampp/htdocs/testing/learn_perl/index.pl line 5. ,

A: You don't need CGI::Simple for any of the code that you have shown us. If you are planning to turn your program into a CGI application at a later date, then I recommend that you use CGI rather than CGI::Simple. One of the most obvious advantages of CGI is that it is included with the standard Perl installation so you don't need to install it yourself.
But that's just the start of your problems. It looks like you've found a terrible tutorial. You would probably do better using the resources linked to from learn.perl.org.

A: Copy paste from: http://startperl.blogspot.com/2007/11/perl-module-how-to-install-perl-module.html
There is a ppm utility provided with every active state perl installation, atleast I got it with perl Vesion 5.8.X All you have to do is follow the below steps

*

*Click Start

*Click Run

*Type cmd and press enter

*Type ppm and press enter

*Once you get the ppm utility prompt
like ppm> type install modulename
eg. install CGI::Simple

The ppm utility will carry the installation of the perl module for you.

A: You should install CGI::Simple module from the CPAN.
One easy way how to install modules from the CPAN is:
curl -L http://cpanmin.us | perl - --sudo App::cpanminus

and after it you can install modules with simple:
cpanm Some::Module

e.g.
cpanm CGI::Simple

A: Ouch, that tutorial does not look very good.  Try this instead, and let me explain what it does:
#!c:\strawberry\perl\bin\perl.exe -T

use strict;
use warnings;

use CGI;
use CGI::Carp qw(fatalsToBrowser);
use DBI;

my $host = 'localhost';
my $database = 'store';
my $tablename = 'inventory';
my $user = 'root';
my $pw = '';

my $dbh = DBI->connect("DBI:mysql:$database;host=$host",
    $user, $pw, { RaiseError => 1 })
    or die "Unable to open database: $DBI::errstr";

my $stmt = $dbh->prepare('SHOW DATABASES');
$stmt->execute();
my $databases = $stmt->fetchall_arrayref();
$dbh->disconnect();

my $page = new CGI;
print $page->header();
print $page->start_html();
foreach $database (@$databases) {
    print $database->[0] . '
';
}
print $page->end_html();

The first line is a standard script header to let the web server know what binary to run.  In this case, I added the '-T' flag to turn on taint mode in Perl.  This will help for security.
You did add 'use strict' and 'use warnings', very good.  Get into the practice of always having these at the top of your scripts.
The next three use statements are libraries from CPAN that will be included in this script.  In this case I've used CGI for HTML generation, CGI::Carp for outputing error messages to the browser (this can help with debugging), and DBI for using databases.  If you ever get the error message you've posted ('Can't locate ...') then that means you're trying to use a library that you haven't installed from CPAN yet.  You can look at this document to get help on installing libraries.
Next I setup local variables.  Since I've turned on strict mode above, every new variable must be prefixed by 'my' or 'our', depending on the scope that I want.
Now I connect to the database using the DBI module.  Here I'm using the mysql library, so make sure that DBD::mysql is installed.  I've also passed an optional parameter called 'RaiseError'; this will ensure that any SQL errors will cause an error.  If I did not turn this on I would have to check the return variable for any SQL call I made.  I've also decided to terminate the script using the 'die' operation if there is any issues with connecting.  You may want to change this to a redirect for production; anything after the 'or' keyword will be executed on errors.
Then I perform my actual SQL operations.  Using my database handle, I prepare a statement and execute it.  I then retreive all of my results into a array reference for later use.  Then I disconnect from the database.
The last block actually prints out the HTML.  I create a new CGI object, then print out the header.  I start the HTML, and then print out each database found.  In the foreach statement, I need to let Perl know that $databases is actually an array reference, so I include the @ symbol before the variable.  Then, since each row is another array reference, I get the first column using the '->[0]' operator.  Finally I finish off the HTML.


text:
Q: How to express the solution points of a matrix in terms of parameters? This is a question which would be helpful to have answered in your response:
"The solution points of the equations
2x+4y = 8
3x+6y = 12
can be expressed in terms of parameter as?"


text:
Q: Sonar Login Issue I installed sonar 2.9.
When i try to log in using sonar/sonar credentials, authentication fails. I have not modified sonar.properties for any username/password.
Am i missing something ?

A: Is this a new install? In that case the default credentials are "admin/admin".
If this is an upgrade to a previous install you can recover the admin password by following the FAQ entry:
http://docs.codehaus.org/pages/viewpage.action?pageId=231080480&navigatingVersions=true#FrequentlyAskedQuestions-Ilosttheadminpassword


text:
Q: Is it possible protect cells and ranges in google sheets after data entry using app script? Is it possible protect cells and ranges in google sheets after first data entry using app script? I am new to the script game.  I use a drop down list and need to lock the cell / range data after the data change.

A: Using onEdit simple trigger (https://developers.google.com/apps-script/guides/triggers/) you can detect the modify and with methods of Class Protection you can lock a range of cells (https://developers.google.com/apps-script/reference/spreadsheet/protection).


text:
Q: Deploying two web projects (one mvc, one webapi) to one Azure App Service In my solution, I have one MVC app which I'll host on www.domain.com
I also have one Web API project, which will be hosted on api.domain.com
Is it possible to deploy these to one (for penny-pinching reasons) App Service, or are they (and should be) separate?

A: With Azure App Service (except the free and shared tiers), you don't pay per app but per server in a App Service Plan.
Thanks to that, you can for example deploy 42 apps in the same App Service Plan for the same price than 1 app.
App Service pricing page can be found at https://azure.microsoft.com/en-us/pricing/details/app-service/
I hope this helps.
Regards,


text:
Q: Graphics Slow or Not Even Loading I made this to generate a checkerboard, and flip the tiles (switch colors) 10 times, every 10 seconds. However, the graphics either do not load, or do not update.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class ShapeTest extends JPanel implements ActionListener {
private static int FRAME_HEIGHT = 500;
private static int FRAME_WIDTH = 500;
private static JFrame frame = new JFrame();

Color color1 = Color.BLACK;
Color color2 = Color.WHITE;
javax.swing.Timer timer = null;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            setAttributes();
        }
    });
}

public static void setAttributes() {
    frame.add(new ShapeTest());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("FrameTest");
    frame.pack();
    frame.setVisible(true);
}

/* Constructor */
public ShapeTest() {
    timer = new Timer(5000, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (color1 == Color.BLACK) {
                color1 = Color.WHITE;
                color2 = Color.BLACK;
                repaint();
            } else {
                color1 = Color.BLACK;
                color2 = Color.WHITE;
                repaint();
            }
        }
    });
    timer.start();
}

protected void painComponent(Graphics g) {
    super.paintComponent(g);
    for (int x = 0; x < FRAME_WIDTH; x = x + 10) {
        for (int y = 0; y < FRAME_HEIGHT; y = y + 10) {
            if (x % 20 == 0) {
                g.setColor(color2);
                g.fillRect(x, y, 10, 10);
                y = y + 10;
                g.setColor(color1);
                g.fillRect(x, y, 10, 10);
            } else {
                g.setColor(color1);
                g.fillRect(x, y, 10, 10);
                y = y + 10;
                g.setColor(color2);
                g.fillRect(x, y, 10, 10);
            }
        }
    }
}

public Dimension getPreferredSize() {
    return new Dimension(FRAME_WIDTH, FRAME_HEIGHT);
}

@Override
public void actionPerformed(ActionEvent arg0) {

}

}

Here is the revised code based on the answer below, however, it still doesn't seem to run.

A: Don't use thread sleep Thread.sleep() In a Swing program. Use a Swing Timer. And define a Color object globally, so it can be accessed from timer and paintComponent. Then repaint in the timer Try this out:
import java.awt.*;
import javax.swing.*;

public class ShapeTest extends JPanel {
    private static int FRAME_HEIGHT = 500;
    private static int FRAME_WIDTH = 500;
    private static JFrame frame = new JFrame();

    Color color1 = Color.BLACK;                      <-- Color objects
    Color color2 = Color.WHITE;
    javax.swing.Timer timer = null;                  <-- Declare Timer object

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                setAttributes();
            }
        });
    }
    public static void setAttributes() {
         frame.add(new ShapeTest());                  <-- Add the panel
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setTitle("FrameTest");
         frame.pack();                    <--- Pack.
         frame.setVisible(true);
    }

    /* Constructor */
    public ShapeTest(){
        timer = new Timer(5000, new ActionListener(){   <-- "sleeps" 5 seconds (real word is "delay")
            public void actionPerformed(ActionEvent e){
                if (color1 == Color.BLACK){
                    color1 = Color.WHITE;                <-- Alternate colors
                    color2 = Color.BLACK;
                    reapaint();                          <-- repaint
                } else {
                    color1 = Color.BLACK;                <-- Alternate colors
                    color2 = Color.WHITE;
                    repaint();
                }
            }
        });
        timer.start();                         <-- Start timer
    }

    protected void paintComponent(Graphics g){
        super.paintComponent(g);

         for (int x = 0; x < FRAME_WIDTH; x = x + 10) {
             for (int y = 0; y < FRAME_HEIGHT; y = y + 10) {
                 if (x % 20 == 0) {
                     g.setColor(color2);      <-- Just us the color Object
                     g.fillRect(x, y, 10, 10);
                     y = y + 10;
                     g.setColor(color1);
                     g.fillRect(x, y, 10, 10);
                 } else {
                     g.setColor(color1);
                     g.fillRect(x, y, 10, 10);
                     y = y + 10;
                     g.setColor(color2);
                     g.fillRect(x, y, 10, 10);
                 }
             }
         }
    }

    public Dimension getPreferredSize(){
        return new Dimension(FRAME_WIDTH, FRAME_HEIGHT);     <-- preferred size of panel
    }

}

A: Two things.
First, you should be calling super.paintComponent from your JComponent#paintComponent to ensure that you don't get any paint artifacts, especially because JComponent is transparent
Secondly, you should be adding your components first and the showing you frame...
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            addComponents();
            setAttributes();
        }
    });
}

Should you need to add new components to your frame after it's made visible, you may need to call revalidate and repaint to ensure that the content is updated correctly...


text:
Q: Clearing textbox makes it inaccessible See the atttached fiddle. I have a trial in which pressing buttons will place them into a textbox. I want users to be able to "start over" and hit the "clear" button to erase their answer. The clear button works, but afterwards, pressing other buttons does not put them back into the textbox as before.
Current code for "clear" button:
function CLEAR(){
letters.value = "";
};

https://jsfiddle.net/xxPoLyGLoTxx/ea6rnwLr/

A: Replace
letters.clear = "";

with
letters.innerHTML = "";

Here is the updated fiddle

A:

function F() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "F");
}
function H() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "H");
}
function J() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "J");
}
function K() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "K");
}
function L() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "L");
}
function N() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "N");
}
function P() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "P");
}
function Q() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "Q");
}
function R() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "R");
}
function S() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "S");
}
function T() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "T");
}
function Y() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', "Y");
}
function BLANK() {
  document.getElementById('letters').insertAdjacentHTML('beforeend', " ");
}
function CLEAR(){
  letters.innerHTML = "";
};
html {
 background: white;
 background-size: cover;
 height: 100%;
 width: 100%;
 top:0;
 left:0;
 bottom: 0;
 right:0;
}
#wrapper{
  height: 90%;
  top: 5%;
 width: 100%;
 left: 0;
 position: absolute;
}
#row1 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 10%;
}
#button1{
  position: absolute;
  left: 0%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: left;
}
#button2{
  position: absolute;
  left: 48%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: both;
}
#button3{
  position: absolute;
  right: 0%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: left;
}
#button4{
  position: absolute;
  left: 43%;
  top: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#button5{
  position: absolute;
  left: 0%;
  bottom: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#button6{
  position: absolute;
  bottom: 0%;
  right: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#row2 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 20%;
}
#row3 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 30%;
}
#row4 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 40%;
}
#finalrow {
 position: absolute;
 width: 40%;
 height: 20%;
  left: 30%;
  top: 50%;
}
#letters{
  position: absolute;
  left: 25%;
  top: 30%;
  color: red;
  width: 175px;
  height: 25px;
}

Select the letters in the order presented. Use the blank button to fill in forgotten items.

<button onclick="F()" id="button1" value="F">F</button>
<button onclick="H()" id="button2" value="H">H</button>
<button onclick="J()" id="button3" value="J">J</button>

<button onclick="K()" id="button1" value="K">K</button>
<button onclick="L()" id="button2" value="L">L</button>
<button onclick="N()" id="button3" value="N">N</button>

<button onclick="P()" id="button1" value="P">P</button>
<button onclick="Q()" id="button2" value="Q">Q</button>
<button onclick="R()" id="button3" value="R">R</button>

<button onclick="S()" id="button1" value="S">S</button>
<button onclick="T()" id="button2" value="T">T</button>
<button onclick="Y()" id="button3" value="Y">Y</button>

<button onclick="BLANK()" id="button4" value="BLANK">BLANK</button>

  <textarea id="letters" disabled></textarea>

<button onclick="CLEAR()" id="button5" value="CLEAR">CLEAR</button>

<button type="submit" id="button6" value="SUBMIT">DONE</button>

A:

var lettersEle = document.getElementById('letters');

function setlettersValue(val) {
   lettersEle.innerHTML += val.value
}

function BLANK() {
  lettersEle.innerHTML = "";
}
function CLEAR(){
  letters.innerHTML = "";
};
html {
 background: white;
 background-size: cover;
 height: 100%;
 width: 100%;
 top:0;
 left:0;
 bottom: 0;
 right:0;
}
#wrapper{
  height: 90%;
  top: 5%;
 width: 100%;
 left: 0;
 position: absolute;
}
#row1 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 10%;
}
#button1{
  position: absolute;
  left: 0%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: left;
}
#button2{
  position: absolute;
  left: 48%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: both;
}
#button3{
  position: absolute;
  right: 0%;
  top: 0%;
  height: 25px;
  width: 25px;
  float: top;
  clear: left;
}
#button4{
  position: absolute;
  left: 43%;
  top: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#button5{
  position: absolute;
  left: 0%;
  bottom: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#button6{
  position: absolute;
  bottom: 0%;
  right: 0%;
  height: auto;
  width: auto;
  float: top;
  clear: left;
}
#row2 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 20%;
}
#row3 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 30%;
}
#row4 {
 position: absolute;
 width: 40%;
 height: 5%;
  left: 30%;
  top: 40%;
}
#finalrow {
 position: absolute;
 width: 40%;
 height: 20%;
  left: 30%;
  top: 50%;
}
#letters{
  position: absolute;
  left: 25%;
  top: 30%;
  color: red;
  width: 175px;
  height: 25px;
}

Select the letters in the order presented. Use the blank button to fill in forgotten items.

<button onclick="setlettersValue(this)" id="button1" value="F">F</button>
<button onclick="setlettersValue(this)" id="button2" value="H">H</button>
<button onclick="setlettersValue(this)" id="button3" value="J">J</button>

<button onclick="setlettersValue(this)" id="button1" value="K">K</button>
<button onclick="setlettersValue(this)" id="button2" value="L">L</button>
<button onclick="setlettersValue(this)" id="button3" value="N">N</button>

<button onclick="setlettersValue(this)" id="button1" value="P">P</button>
<button onclick="setlettersValue(this)" id="button2" value="Q">Q</button>
<button onclick="setlettersValue(this)" id="button3" value="R">R</button>

<button onclick="setlettersValue(this)" id="button1" value="S">S</button>
<button onclick="setlettersValue(this)" id="button2" value="T">T</button>
<button onclick="setlettersValue(this)" id="button3" value="Y">Y</button>

<button onclick="BLANK()" id="button4" value="BLANK">BLANK</button>

  <textarea id="letters" disabled></textarea>

<button onclick="CLEAR()" id="button5" value="CLEAR">CLEAR</button>

<button type="submit" id="button6" value="SUBMIT">DONE</button>


text:
Q: Best way to store a 2D-array with column and row names I am trying to find the best way to store in Redux a 2D array with row and column names.
In terms of priorities, I would rank code readability and maintainability above performance. Hence, accessing a value through table[row][col] would be preferable.
I have thought about two solutions:

*

*First, storing it in three distinct variables colNames, rowNames and table. Accessing values would still be doable. But, for example, removing a column would then require to modify both colNames and rowNames. Incrementing some value from row and column names would require to access all three variables.

var rowNames = ["row1", "row2", "row3"];
var colNames = ["col1", "col2", "col3"];
var table = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

*

*The other way would be to store a single variable table as an Object. It becomes easy to access values. But it is harder to correctly update it in Redux to respect immutable state.

var table = {
    row1: {
        col1: 1,
        col2: 2,
        col3: 3
    },
    row2: {
        col1: 4,
        col2: 5,
        col3: 6
    },
    row3: {
        col1: 7,
        col2: 8,
        col3: 9
    }
};

Some other idea would be to use Immer JS with the second solution to improve code readability.
What is then the best way to store such a value in Redux ?
Solution I chose
I ended up using the second solution with a single variable. Once the modification of this table is properly made in Redux reducers, it makes accessing and displaying said table easy.

A: I do think your solution is quite nice and adapted to rendering in an html table. However you will have to iterate over Object.keys(table) to go through the rows.
Another solution could be to do somehing like that so you can iterate over objects directly:
var table = [
    {
        name: "row1",
        col1: 1,
        col2: 2,
        col3: 3
    },
    {
        name: "row2",
        col1: 4,
        col2: 5,
        col3: 6
    },
    {
        name: "row3",
        col1: 7,
        col2: 8,
        col3: 9
    }
];

This solution also has it's problems: you have to specifically take the name property out of the object while iterating for rows. You would also have to iterate over Object.keys of the inner object avoiding the treatment of the "name" column.
Hope this help as an overview of your problem :)


text:
Q: Do professional software developers still dream of creating industry/world-changing apps? I'm a hobby programmer. The absence of real world deadlines, customer feedback, or performance reviews leaves me free to daydream about having and implementing The Next Great Idea That Changes the World. Of course I'm aware I probably have a better chance of winning the lottery, but it's fun to imagine knocking out some fully-homebrewed app that destroys the status quo.
I know many professional programmers have side projects, some for profit others not. I was wondering on the way to work this morning (non-IT boring work) if having to code for your food tended to dampen the dreaming? Does greater experience leave you jaded and more focused on the projects at hand?
Not trying to be a downer, just interested in the mindset of the real software professional :-)

A: Not I.  Not even trying.
The world doesn't want to be saved, nor improved.
I actually just like to write code and solve problems.  I don't expect the next Sudoku puzzle I solve to cure world hunger either.
If I was actually trying to improve the world, writing silly programs that only benefit the already well-to-do wouldn't be the way I'd be going about it.  I'd be in some third world hell hole trying to help dig people out.  That's not what I'm doing.
Edit: I do someday dream of making an AI pet out of a remote control jeep though.  Figure the brain can be in a PC with the jeep being sort of a wireless remote body.

A: I think that's why people get into software development, that idea of changing the world.
I mean, we sure as hell don't get into it so we can spend our days maintaining legacy applications, putting up with office politics, and performing various monotonous tasks...

A: I've known some hobbyist programmers.  Looking back on it, they thought the same thing you did.  They thought they were going to change the world.
Looking back on it, they were trying to solve very basic problems that had already been solved. To someone outside the field of software development and computer science, the concepts seemed mind-blowing.  But for the professionals in the field, solving the world's problems or contributing to the growth of the field usually involves a very strong mastery of the field itself, along with years of professional experience.
Just check out the answers to the question, Does it Really Take 5 to 10 Years or More to be a Really Good Programmer?  In order to solve problems in this field, you have to learn everything you can about it, and that type of learning only comes from being a professional.
I hope this doesn't discourage you.  If you do have great ideas, that's awesome!  I'm not saying you don't or can't contribute.  But what I encourage you to do is take a step back and ask yourself if your assessment is accurate.
It helps if you have friends who are professional programmers.  But if you live in a world that doesn't involve any pros, then perhaps you could benefit by getting involved in professional organizations or projects.
If nothing else, this will give you a baseline from which you can more accurately assess your ideas and have someone to bounce them off of.
To answer your question, I have some ideas for improving the Spring Framework that are based upon my reasons for Why I Will Never Use Spring Tag Libraries in My HTML.
These ideas aren't really life-changing, but it took me years of working with Developers and Designers to understand that a lot of the marketing behind frameworks is just that, marketing.  Because I do this 10 hours a day, I'm a little less motivated to work on it in my spare time.

A: Yes.
Those who don't, typically change careers.

A: My hope is that at least some of the applications I build are useful to the people I write them for and change their lives in a small way. That's challenging enough to achieve and I'm happy if someone comes back to me for modifications to a system after six months because it means they've found it useful and are still using it.

A: Absolutely
If anything, coding for my food as you say has made me dream more.  The experience I have gained over the years allows me to have a better idea of the actual work that would be involved to achieve the dream, but I still dream.

A: Some may get in the field because they want to change the world, many though go into software development because it seems to be easy money at the time (relatively high pay for no physical labour, 9-5 job in an air conditioned office, maybe a company car and other benefits).
Or they just slither into it because their originally chosen field of work dries up and they happen to have the right skills acquired as a side effect or hobby already.
Was I looking to change the world when I started programming? No. I was just trying to make my job a bit easier by automating some of the data analysis during my physics labs.
And that "making the job easier" ended up being a job in itself, making other peoples' jobs a bit easier by making software to enable them to do that job more efficiently than they would otherwise be able to do it.
It's a job, it has its ups and downs. Some days you love it, some days you hate it, but overall it's just a job (albeit a nice one compared to others I could think of, if you like solving puzzles).

A: Like you and probably most programmers out there, I have a dream. But I don't dream of changing the world... instead, I dream of writing an article, a little library, a framework or a book which fills some sort of gap which others have left out.

A: I think this might depend upon what you are defining as a world changing program. Depending upon where you work, the programs you write might have a huge impact on things (i.e. wrote the software that assisted in the image analysis used to identify a new planet) but you find that you may be quite distant from the actual discovery that was made even though you were involved in writing the software that lead to it. Likewise, on the corporate side, odds are that unless you are working in some sort of research group or a start-up, it is unlikely that you will see a major direct impact from the software you write, but there does seem to be a "long tail" from software as the developers for Microsoft Office likely indirectly assisted in a number of major discoveries due to the analysis tools built into Excel or the like.


text:
Q: How to fetch API from swagger file using kong gateway I have create a service, a route, an auth, a consumer, a username and a password in the kong admin UI through curl command.  Below there is the command that I have used and it's showing in the kong admin UI.
I have installed Kong as docker container with image version is kong/kong-gateway:2.8.1.2-alpine
curl -X POST http://x.x.x.x:8001/services \
  --data name=admin-api \
  --data host=x.x.x.x \
  --data port=8001

curl -X POST http://x.x.x.x:8001/services/admin-api/routes \
  --data paths\[\]=/admin-api

curl -X POST http://x.x.x.x:8001/services/admin-api/plugins \
        --data "name=basic-auth"  \
        --data "config.hide_credentials=true"

curl -d "username=first-consumer&custom_id=1" http://x.x.x.x:8001/consumers/

curl -X POST http://x.x.x.x:8001/consumers/first-consumer/basic-auth \
    --data "username=first-consumer" \
    --data "password=my-password"

curl -s -X GET \
  --url http://x.x.x.x:8000/admin-api \
  --header 'Authorization: Basic Zmlyc3QtY29uc3VtZXI6bXktcGFzc3dvcmQK'

Below command I get 200 ok response
curl -i -X GET --url http://20.69.125.27:8000 --header "Host: petstore.swagger.io" --header "apikey: apisec"

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 734
Connection: keep-alive
Date: Wed, 10 Aug 2022 11:52:06 GMT
Server: nginx
Last-Modified: Tue, 02 Aug 2022 12:23:11 GMT
Vary: Accept-Encoding
ETag: "62e9172f-2de"
Expires: Thu, 11 Aug 2022 11:52:06 GMT
Cache-Control: max-age=86400
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Accept-Ranges: bytes
X-Kong-Upstream-Latency: 322
X-Kong-Proxy-Latency: 52
Via: kong/2.8.1.2-enterprise-edition

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
    <link rel="stylesheet" type="text/css" href="index.css" />
    <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />

im getting above output in html but i want in json format
How to get fetch on https://petstore.swagger.io/v2/swagger.json through curl as json file from kong setup ?


text:
Q: Find and change HTML tag containing four-digit year while leaving text content intact I am looking for a four digit year between a
 tag.  I then want to switch just the
 tag to a
.  I can find them with
\d{4}
, but how do I just replace the

 with

 and leave the year intact?
I have a locally saved html file that has 100+ years scattered in a large file. I need to switch the p tags out for h1 only on the year paragraphs, which are always p 4 digit year. I am going to use a text editor to do it then upload the file live.
The text editors I have are - Visual Studio, Sublime, Dreamweaver, and Notepad++.

A: Here you go if you use vim:
:%s/
\(\d\{4\}\)<\/p>/
\1<\/h1>/g

The above expression means: substitute (s) in the whole file (%) every occurrence (g) of
(\d{4})
 with the first parenthesised expression \1 surrounded by the
 tag (the special escaping of ( and { is there just because vim wants it)
Or if you use other editors that accept regular expressions in searching and back references in replacement:

*

*search:
(\d{4})

*replace with:
BR_1
 where BR_1 is the back reference notation in your editor (for example $1, \1, etc.)

A: You can try something like this:
if (regex match) {
    $("p").replaceWith('
' + $("p").html() + '
');
}

https://jsfiddle.net/lemoncurry/oL0dcqnu/


text:
Q: Limit a C++ Variable's Scope I have a C++ program that has the following form:
int main(){
    int answer;

    ...

    MEMORY_CONSUMING_DATA_ARRAY temp;
    a few operations on the above;
    answer=result of these operations;

    ... //More code
}

That is, I have a small block of code which doesn't seem to warrant its own function, but which uses a great deal of memory.
I'd like to bring the memory-consuming variable (a class) into existence within a limited scope to produce a result and then have it destroyed. A helper function would do this easily enough, but it seems like over-kill in the scenario in which I'm working.
Any thoughts on how to accomplish this?
Thanks!

A: Justin's answer is fine but if you are performing this operation again and again then you may want to reuse this memory.
EDIT
As pointed out static will make the memory not allocate on the stack which may benefit you, also it would be optional if you needed to zero the memory each time, if you were going to copy over the same amount each time and not going to read past this point then you could save a call to zeromemory or other initialisation call.
int main(){
    int answer;

    ...

    {
      static MEMORY_CONSUMING_DATA_ARRAY temp; // make this static or a member perhaps
      temp = 0; // initialise it every time to clear the memory or zeromemory or other op
      a few operations on the above;
      answer=result of these operations;
    }
    ... //More code
}

A: if destruction is what you need:
int main() {
    int answer;

    ...
    { // << added braces
      MEMORY_CONSUMING_DATA_ARRAY temp;
      a few operations on the above;
      answer=result of these operations;
    }
    ... //More code
}

so that would work for a collection/object backed by a dynamic allocation, such as std::vector.
but for large stack allocations... you're at the compiler's mercy. the compiler may decide it's best to cleanup the stack after your function returns, or it may incrementally perform cleanup within the function. when i say cleanup, i am referring to the stack allocations your function required -- not destruction.
To expand on this:
Destruction of a dynamic allocation:
int main() {
    int answer;
    ...
    { // << added braces
      std::vector<char> temp(BigNumber);
      a few operations on the above;
      answer=result of these operations;
      // temp's destructor is called, and the allocation
      // required for its elements returned
    }
    ... //More code
}

versus a stack allocation:
int main() {
    int answer;
    ...
    {
      char temp[BigNumber];
      a few operations on the above;
      answer=result of these operations;
    }

    // whether the region used by `temp` is reused
    // before the function returns is not specified
    // by the language. it may or may not, depending
    // on the compiler, targeted architecture or
    // optimization level.

    ... //More code
}


text:
Q: tracking changes in journal aricles prepared using rmarkdown to communicate with non R users As a fairly new R user, I find that r-markdown is amazingly efficient for writing research articles with many numbers, graphs and tables. My question is: when different collaborators (non R users) have made some changes in the knitted Word manuscript file, what is the best way to track those changes in the r-markdown file, and the final Word file?
I noticed some similar questions were asked and answered a few years ago, including: MS Word track changes and RMarkDown.
With new features and new packages such as reviewer and trackmd recently becoming available, I wonder if anyone could suggest an updated workable workflow for this. Thanks.


text:
Q: How to unit test a variable in vue and vuetify with jest? This might be pretty simple.
I have a component that renders a receive a message via props and renders it in a v-card-text. It doesn't do that in an optimal way, the whole v-if is messy, but it works.
<template>

    <!-- Needed to be rendered big -->
    <div v-if="start == true" class="ma-0">
        <v-card class="text-xs-right" dark color="rgb(0,140,69)" height="50" width="1060" >

            <v-btn dark text icon @click= "isOpen = !isOpen;"  color="rgb(0,140,69)" >
                <v-icon dark>fullscreen</v-icon>
            </v-btn>

            <v-btn class="mx-2" icon dark small color="rgb(0,140,69)">
                <v-icon dark>thumb_up</v-icon>
            </v-btn>

        </v-card>

        <v-card  v-model='text' color="" height="200" width="1060">
            <v-card-text ref="tcardbig" color="rgb(0,140,69)" style="color:rgb(0,140,69);display:flex;height:100%;justify-content:center;" class="display-2 font-weight-black align-center"> {{text}}</v-card-text>
        </v-card>
    </div>

    <!-- Needed to be rendered small -->
    <div v-else class="ma-2">
        <v-card class="text-xs-right" dark color="rgb(0,140,69)" height="50" width="500" >

            <v-btn dark text icon @click= "isOpen = !isOpen;"  color="rgb(0,140,69)" >
                <v-icon dark>fullscreen</v-icon>
            </v-btn>

            <v-btn class="mx-2" icon dark small color="rgb(0,140,69)">
                <v-icon dark>thumb_up</v-icon>
            </v-btn>

        </v-card>

        <v-card  v-model='text' color="" height="350" width="500">
            <v-card-text ref="tcardsmall" color="rgb(0,140,69)" style="color:rgb(0,140,69);display:flex;height:100%;justify-content:center;" class="display-2 font-weight-black align-center"> {{text}}</v-card-text>
        </v-card>
    </div>

</template>

<script>
export default {
  data(){
      return {
          text: 'lorem ipsum',
          start: true
      }
  },
  props: ['textProps', 'startProps'],
  mounted(){
      this.text = this.textProps
      this.start = this.startProps
  }
}
</script>

I'm trying to unit test it with jest. How do I check if the text is properly rendered?
In other how I check the {{text}} in the  OR how I check if the text variable of the component has the value I sent via prop. What am I doing wrong?
import {createLocalVue, mount} from '@vue/test-utils'
import textCard from './textCard.vue'
import Vue from 'vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)
const localVue = createLocalVue()

describe('textCard.vue', () => {

    const wrapper = mount(textCard,
        {
            localVue,
            vuetify,
            propsData: {
              text: 'Random Text',
              start: false
            },
        }
        )
    it('renders a vue instance', () => {
        expect(mount(textCard).isVueInstance()).toBe(true);
    });

    const content = wrapper.find({ ref: 'tcardsmall' })

    it('Checks the if the variable text is correct', () => {
        expect(content.selector).toMatch('Random Text')
      })

}

)


text:
Q: Simple counter using AsyncTask class This is a simple counter using AsyncTask class:
   static private class AsyncTaskRunner extends AsyncTask<Integer, Integer, Integer> {

    @Override
    protected Integer doInBackground(Integer...prams) {
       while(t){
           i++;
           publishProgress(i);
           try {
               Thread.sleep(200);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

        return null;
    }

    @Override
    protected void onPostExecute(Integer result) {

    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Textview.setText(String.valueOf(values[0]));
    }
}

i is an Integer witch rising every 0.2 seconds and the value of it shows in Textview.So when i run my app the value of i show in textview and increase and update fast using asynctask class.
This is my question:
Why some times my Text view show a smaller value of i,for example afte 54 it shows 53 and then rising again!

A:
onProgressUpdate(Progress...), invoked on the UI thread after a call
  to publishProgress(Progress...). The timing of the execution is
  undefined. This method is used to display any form of progress in the
  user interface while the background computation is still executing.
  For instance, it can be used to animate a progress bar or show logs in
  a text field.

The timing of the update on your UI thread is not guaranteed so you could see the events come out of order like you describe.  You might want to add logic to your progress to just not decrease the value at all and only increase, basically skip the value if it is less than what you saw last time.

A: There are main UI thread and other worker thread, to update Textview using AsyncTask, you should use publishProgress
The official help gives detailed explanation and sample, read it and try modify your codes.

A: You should not be implementing this via an AsyncTask.  All AsyncTasks share the same thread, sleeping on it will block any other task in the system.  This is acceptable only for very short tasks.  If your timer runs forever, no other async task in your app will ever work.  If you want a timer, use a handler or a thread, not an AsyncTask.


text:
Q: Handling line breaks in textarea elements with ASP MVC and jquery unobtrusive validation Viewmodel:
public class ViewModel
{
    [Display(Name = "Message")]
    [StringLength(500, ErrorMessage = "Your message must be {1} characters or fewer.")]
    public string Message { get; set; }
}

View (extract):
<div class="form-field-group">
    @Html.LabelFor(m => m.Message , "Your message:")
    @Html.TextAreaFor(m => m.Message )
    @Html.ValidationMessageFor(m => m.Message )
</div>

I'm also using the unobtrusive validation like so in the web.config:
<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

Absolutely textbook stuff, and it seems to work wonderfully.
The problem!
So my understanding of the HTML spec for line breaks in form data is that it gets encoded as CR LF. And that's certainly what I see when I debug the controller action that handles the post of this viewmodel.
However, when reading the value of the input through javascript, the line breaks vary depending on browser (IE6-8 seem to give CRLF whereas Chrome and Firefox recent builds on windows give just LF).
This means that if you enter text with line breaks, the jquery validators will let through what they see as, say, 498 characters, but by the time it reaches the model binding, it's been converted to 504 and ModelState.IsValid is (correctly) false.
Anyone got any ideas about the nicest/simplest way to correct this?

A: MVC unobtrusive validation (jquery.validate.unobtrusive.js) makes use of jquery.validate.js.
So the simplest way to fix this issue is to change the behavior of what maxlength does in jquery.validate.js (this is what jquery.validate.unobtrusive.js attaches to via it's adapter).
The code below will change maxlength and fix the issue:
(function ($) {

    if ($.validator && $.validator.methods && $.validator.methods.maxlength) {

        $.validator.methods.maxlength = function (value, element, param) {
            if (typeof value === 'string') {
                value = value.replace(/\r?\n/g, "\r\n");
            }

            var length = $.isArray(value) ? value.length : $.validator.prototype.getLength($.trim(value), element);
            return $.validator.prototype.optional(element) || length <= param;
        };
    }

})(jQuery);

Something to note is this won't cause an issue on non windows platforms (or cause different issues) http://en.wikipedia.org/wiki/Newline.
You could also solve this by creating your own validation attribute and implementing IClientValidatable adding your own client side validation http://www.falconwebtech.com/post/2012/04/21/MVC3-Custom-Client-Side-Validation-with-Unobtrusive-Ajax.aspx. The disadvantage of this is remembering to use your attribute rather than standard StringLength one. You have to decide what is best for your situation.


text:
Q: Comparing RMSE to model I'm assessing the accuracy of the prediction of my model using the RMSE on a new data set. Now the RMSE in itself doesn't give any indication of whether it is a good model since there is no threshold that says it is 'good'. My question is, would it make sense to calculate the RMSE for a null model with just the mean as a predictor and compare this to the RMSE of my model? Or should I compare the RMSE of the model on the 'train' data to the RMSE of the 'test' data?
The model that I'm currently using is the best with all my available predictors based on BIC scores, but I'm trying to figure out how well the model actually does. I've also calculated the adj. R-square, which says that 20.7% of the variance is explained by my model, but I doubt whether this is a good accuracy measurement.

A: Your suggestion about using a null model is similar to $R^2$. $R^2$ is defined as $1-MSE/V$, where $MSE$ is the model's mean squared error and $V$ is the variance of the observed output. You can think of the variance as the mean squared error of a null model that always gives the mean as its predicted output. Even here, the question is: how much better can you do? This is very hard to answer. The reason is that it's hard to know whether the error reflects variation in the output that's fundamentally unpredictable from the input (e.g. 'noise', but could be something else), or whether additional structure is present that the model has simply failed to capture. Sometimes looking at the residuals can give a hint. Under some circumstances, it's possible to estimate the 'noise' level. For example, if you have many repeated trials where inputs are identical, you can measure variability of the output for equal inputs. This gives a bound on the maximum possible performance. You would typically encounter this situation in the context of controlled experiments. Or, you may be able to do something similar if you have access to a known 'correct model' (e.g. in a theoretical setting, or if you're modeling a well understood physical system). Otherwise, it's hard to know whether there's a better model out there.
Looking at the training vs. test error can give you some idea about the extent to which your model is overfitting (the expected training error would be lower than the expected test error). There can be variability here when using a small number of samples and/or few repetitions. A gap between training and test error isn't a problem per se, but a large gap might signal a problem. Even so...one model that overfits might still have better generalization performance than another model that doesn't.
Instead of asking how good your model is, you can also ask how bad it is. You could use a significance testing approach to see whether your prediction is better than 'chance'. For example, you might compare the test error on real data to the test error on permuted data (where relationships between the input/output have been destroyed, and any apparent performance is due to sampling variability or overfitting).


text:
Q: Trying to understand keras SimpleRNN I have a medical longitudinal data on which I am doing a research.
To start with I am working with 4000 rows of sample with 3 time-steps(3 columns) of a bone size corresponding to size of bone measured in 3 different months.
I am done with the basic model. Now I want to be sure if my understanding of the model is correct.
model = Sequential()
model.add(layers.SimpleRNN(units=10, input_shape=(3,1),use_bias=True,bias_initializer='zeros',activation="relu",kernel_initializer="random_uniform"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(loss='binary_crossentropy', optimizer='sgd')
model.summary()

model.fit(trainX,train_op, epochs=100, batch_size=50, verbose=2)
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

Following are my few doubts around this model :

*

*Here return_sequences is False , then shouldn't I get only the last output from RNN layer. Why the output is of shape(None, 10) from RNN layer? I assumed it should be (sample size,1) .

Also my below mentioned logic is flawed but I need to resolve it which is :
Units corresponds to output units. Initially my guess was that since there are 3 time-steps there has to be 3 output units but I was surprised that even if give units= 128 or 10,1 the model worked. How and why it is happening ? This question along with the above one confuses me more.

*input_shape corresponds to -[sample size, number of time steps, features]. Here, I am measuring 1 bone size over 3 time periods. Is my understanding correct when I say the input shape is (sample size, 3,1) ? Moreover, I have confusion regarding how numpy represents 3d array. It seems, to get required dimension I need to input as - #features, observations/sample_size, timesteps . Do I have to reshape my inputs according to how numpy represents 3d or should i let it be. ?

Moreover, how can I build a model if i have different set of features measured over different time frame or have various time steps ? How can i incorporate with the above model.

A: *

*Yes, you get the last output, which is a 10-dimensional vector, not a one-dimensional vector, so getting shape (samples, 10) is correct.

*Number of units has nothing to do with timesteps, the number of timesteps is how many times the neurons are applied recurrently, so its orthogonal to the number of features or units.

*Yes, shape of your inputs should be (samples, 3, 1) and the input_shape should be (3, 1), all of this is correct in your code. I am not sure what you are talking about on "how numpy represents 3d array", the shape is clear, numpy does not do any modifications to input shapes.


text:
Q: How does the view communicate with the model? I am wondering how the view communicates with the model.
As I understand the controller directs the correct information to the model.
class Controller
{
    public function action()
    {
        if(isset($_POST) )
        {
            $this->model->someMethod($_POST['foo'],$_POST['bar']);
        }
    }
}

The model does it's business.
class Model
{
    public function someMethod($foo,$bar)
    {
        // do something
    }
}

The view has to somehow know how to communicate with the model to get it's current state. But how it this done?
class View
{
    public function action()
    {
        // ask the model what is going on
    }
}

How does the view know what happened and if everything went the correct way. I though of getting some state of the model with a 'getState()' method on the model. The state is some string the view knows what to do with But it doesn't seem the right way to me. How does the view know if somebody is logged in for example? Should the view actually know about this?

A: It is interesting, that it you look at the brief description of the MVC pattern in the GoF's book, or look at the original article about the pattern in SmallTalk, you will see that controller controls the user interaction with the view.
View is usually directly subscribed to the model changes. You can have several views to the same model and each reflects the model changes without any controller.
A controller is something that is attached to a specific view to handle user unput and to transform it into a higher level abstraction (i.e. intention to update something in the model, or pass a message to a subview, or something else).
In a GUI, a view is usually subscribed to the model using some implementation of Observer pattern. In PHP it does not make much sense, since everything is rendered by request (there is usually no shared state between requests), thus, a view can just query a method on the model.

A: If you want to explore MVC and MVC-inspired patterns, you should start by reading GUI Architecture by Martin Fowler. Considere it your mandatory literature.

In classical MVC pattern the view observes the model layer for changes in its state. This approach is not really viable in PHP. You still can attempt to apply it, but the benefits will be dwarfed by additional complexity.
There are other approaches.
Model2 MVC (or colloquially known as "Web MVC") gets rid of the observers. Since in web application you have simple request-response workflow and since controllers and views naturally form pairs, you can take an advantage of it. When you know which controller will be used for altering models state, you also at the same time have information about which view will be utilized for the response.
This means that, instead of relaying on the observers, view already knows which parts of model layer could be changed and request the information.
A different approach is called MVP. To explore this, you will be better off if you read the defining publication of the pattern.


text:
Q: Evernote oAuth error php I'm having issues getting an access token from Evernote using oAuth in my codeigniter app.
I am able to successfully get my temporary credentials but when I ask for my access token. I get the following error.

"Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)"

$_SESSION['requestToken'] = $requestTokenInfo['oauth_token'];
$_SESSION['requestTokenSecret'] = $requestTokenInfo['oauth_token_secret'];
$_SESSION['oauthVerifier'] = $_GET['oauth_verifier'];
print_r($_SESSION);
$accessToken = $client->getAccessToken($_SESSION['requestToken'], $_SESSION['requestTokenSecret'], $_SESSION['oauthVerifier']);

The print_r function correctly prints out the 3 parameters returned to me by Evernote as the temporary credentials.
I am using php 5.4.9 on an Ubuntu 12 server. I have installed the Pecl OAuth extension. Thank you very much in advance for any help.

A: To check if everything is working well, you should use their sample application.
To do so, clone the github repository you mentionned earlier, then edit the sample/oauth/config.php file by filling the variables :
define('OAUTH_CONSUMER_KEY', 'your key');
define('OAUTH_CONSUMER_SECRET', 'your secret');

// Replace this value with FALSE to use Evernote's production server
define('SANDBOX', TRUE);

then go to http://your.domain.com/evernote-sdk-php/sample/oauth/index.php to test your settings and follow the steps that appears. At the end of the test you should have a list of all your notebook, or Error before it.
Once everything is done you can have a look at the code they provide as an example to understand how the PHP code works.
hope this help as this did the trick for me with python ;)


text:
Q: Advanced search in Outlook 2007 - can I turn on Search subfolders by default? When I do an Advanced Search (CTRL-SHIFT-F) in Outlook 2007, the Search subfolders option is always off by default.
I have to click the Browse button and enable the checkbox at the bottom of the dialog every time.
In Outlook 2002, it remembered the setting.
Can Outlook 2007 be made to remember this setting?

A:
Can Outlook 2007 be made to remember
  this setting?

in a word, no.


text:
Q: Question related to PDE , Solve IBVP Suppose that an external force per unit length given by
$f$($t$, $x$) = $h$($x$) sin ($ωt$), $ω$ > $0$
with $h$ piecewise continuous on the interval [$0$, $L$] acts on a string with fixed
endpoints at $x$ = $0$ and $x$ = $L$. Solve the IBVP
$∂_{tt}u$ = v$^2$$∂_{xx}u$ + $f(t, x)$ $∀$ $t$ > $0$, $x$ $∈$ ($0$, $L$),
$u(0, x) = 0  ,∀ x ∈ [0, L],$
$∂_{t}u(t, x)$$|_{t=0}$ = $0$ $∀ x ∈ [0, L]$,
$u(t, 0) = 0 = u(t, L) ∀ t ≥ 0.$

Here are my thoughts :
I assume its homogenous form with forced, hence we get
$u(x,t)$ = $(\sum\limits_{n=0}^{\infty}$ $u_{n}(t)$ $sin$ ($\frac{n\pi x}{L}$))
$u_{n}(t)$ functions to be determined
For each fixed $t$ we can determine Fourier series of $f(x,t)$ = $(\sum\limits_{n=0}^{\infty}$ $f_{n}(t)$ $sin$ ($\frac{n\pi x}{L}$))
Where coefficients  $f_{n}(t)$ is given by $f_{n}(t)$ = $\frac{2}{L}$ $\int_{{0}}^{L}$ $f (x,t)$ $sin$ ($\frac{n\pi x}{L}$) $dx$
$f_{n}(t)$ = $\frac{2}{L}$ $\int_{{0}}^{L}$ $h (x)$ $sin(ωt$) $sin$ ($\frac{n\pi x}{L}$) $dx$
With proper integral properties $f_{n}(t)$  substitute in above PDE
$(\sum\limits_{n=0}^{\infty}$ [$u$$''$ + ($\frac{n\pi x}{L}$)$^2$ $u_{n}(t)$] ] $sin$ ($\frac{n\pi x}{L}$)) =  $(\sum\limits_{n=0}^{\infty}$ $f_{n}(t)$ $sin$ ($\frac{n\pi x}{L}$))
By equating coefficients:
$u_{n}$$''(t)$ + ($\frac{n\pi x}{L}$)$^2$ $u_{n}(t)$ = $f_{n}(t)$
So these are nonhomogeneous-constant coefficients that can be solved using the variation of parameters.
$u_{n}(t)$ = $\frac{L}{n\pi x}$ $\int_{{0}}^{t}$ $f_{n}(s)$ $sin$ ($\frac{n\pi x}{L}$)$(t-s)$ $ds$
So based on $h(x)$ we get $f_{n}(s)$ then subsititute we get formal solution of PDE
$u(x,t)$ = $(\sum\limits_{n=0}^{\infty}$ $u_{n}(t)$ $sin$ ($\frac{n\pi x}{L}$))
$u(x,t)$ = $(\sum\limits_{n=0}^{\infty}$ {$\frac {L}{n\pi x}$ $\int_{{0}}^{t}$ $f_{n}(s)$ $sin$ ($\frac{n\pi x}{L}$)$(t-s)$ $ds$} $sin$ ($\frac{n\pi x}{L}$)
In the end, we got the solution by the method of separation of variables
Am I solving right?
Because it is a project question and I want to make sure to get a full mark on it


text:
Q: Is there a (relatively easy!) way to create relationships between taxonomies WITHOUT needing a post as an intermediary All of the answers I've found so far - here and elsewhere - involve creating a (custom) post - which would be 'overkill' because in this instance many of the 'terms' would only appear once.
Specific example to explain what I'm trying to accomplish:
Person A may be the composer of Song 1;
Person A may be the lyricist of Song 2;
Person A may be both the composer and lyricist of Song 3;
Person A may have been the presenter of Show 1.

I (think I!) want to have one taxonomy of 'person' (i.e. so that Person A is only entered once) with other taxonomies of 'composer', 'lyricist' and 'presenter'. Then on the actual post for Song 1, Song 2, Show 1, etc. I have each person:relationship. A search for Person A would then show that (s)he is connected to:
Song 1, as 'composer';
Song 2, as 'lyricist';
Song 3, as 'composer' and as 'lyricist';
Show 1, as 'presenter'.

Alternatively, if I'm asking the impossible and have to relate through a 'person' custom post, is there an 'easy' (i.e. automatic) way to create it, i.e. when I'm inputting data for a song, show, etc. and just want to enter a name?
Should add that "No ... looked for ages (or tried clever ways) but haven't found a solution" is an acceptable answer. Not the one I was hoping for but at least it might convince me to stop looking / trying!

A: Using standard Wordpress functionalities this is, simply, not possible, unless using complicated and poorly performing tricks.
The method I suggest you is to create your custom table where store relationship.
It should consists of 5 columns:
person_id | post_id | post_type | taxonomy | term_id

Now, copying out your example:
Person A may be the composer of Song 1;
Person A may be the lyricist of Song 2;
Person A may be both the composer and lyricist of Song 3;
Person A may have been the presenter of Show 1.

and assuming:
'Person A' is a term of 'people' taxonomy with term_id 66
'Composer' is a term of 'talents' taxonomy with term_id 30
'Lyricist' is a term of 'talents' taxonomy with term_id 40
'Presenter' is a term of 'talents' taxonomy with term_id 50
'Song 1' is a post with the id 1
'Song 2' is a post with the id 2
'Song 3' is a post with the id 3
'Show 1' is a post with the id 9

To rapresent the relationships in your example we need 5 rows in the table
66 | 1 | 'post' | 'talents' | 30
66 | 2 | 'post' | 'talents' | 40
66 | 3 | 'post' | 'talents' | 30
66 | 3 | 'post' | 'talents' | 40
66 | 9 | 'post' | 'talents' | 50

Knowing a person id you know all his/her talents and to which posts are related. Same way, knowing a post id you know all people related and which is the talent involved in that particular post.
Getting and showing data it's a cinch: once people, talents, song and shows are wordpress standard entities (posts, terms) you have to do nothing to create url for show them selectively and you can make the better use of template hierarchy as well. Getting custom associations is very easy, few lines of sql and you are done.
Store custom associations is a bit harder: not being part of wordpress core you have to built entirely the UI for the scope. Nothing impossible: you need just a metabox with some rows (or better the ability to dinamically add rows) and for every row two select menus: one for people one for talent.
Note that this method allow link people with every post type and every taxonomy: maybe now you will use only standard post type and 'talents' but in the future... I always like design in a flexible manner to avoid refactoring at every change.
Hope it helps.

A: If you want an out of the box way to do this I'd say use Advance Custom Fields, it has a friendly UI and it's really simple to use and understand, you can either choose a relationship type or a post object then with some work on your theme you'll get the relation between post types or taxonomies.
http://www.advancedcustomfields.com/resources/field-types/relationship/
http://www.advancedcustomfields.com/resources/field-types/post-object/
Else I'd go for G. M. answer.

A: So here is the thing with a structure like this. It goes both ways. Person A can be the composer of poem 1, and singer of song 2, and you can associate them via metas. However, the thing is, Person A him/herself is a composer & singer to begin with. So you might want to do something like this:
  Create Person as a CPT, create new Persons and add traits to them like singer or composer. Then create CPT for different types of entertainment, like one for TV shows and one for Poems. And then link Person via a meta field.


text:
Q: Error catching when inserting multiple object types We have a page inserting three different object types. Historically, it has attempted to insert one and, assuming no errors (try and catch), moved to the next. Until all objects were inserted. If there was an error on the third object type, it would delete the first two inserted objects, give the user a chance to fix the errors, and then try again.
We are now using different permission sets, and not all users have the ability to delete these objects. Is there a way to check for insert errors all at once so we can avoid deleting the already inserted object?

A: Yes, you can use Savepoints for Transaction Control
The code will look like below:
Savepoint sp = Database.setSavepoint();
try{
 insert obj1;
 insert obj2;
 insert obj3;
}
Catch(Exception ex){
 //If an exception occurs, rollback the transaction --> no records will be inserted
 Database.rollback( sp );
}


text:
Q: Integral solution of two variable equation Need to solve below question:
Find all solutions in integers $x$ and $y$ of the equation->>   $xy + 5x -8y = 79$
Any hint is welcome.

A: It's $$xy+5x-8y-40=39$$ or
$$(y+5)(x-8)=39,$$ and solve a number of systems:
$$x-8=-39$$ and $$y+5=-1...$$
For $$x-8\in\{-39,-13,-3,-1,1,3,13,39\}$$  you'll get all integer solutions.


text:
Q: jquery load function pull certain value Hi I have found a value on a website that changes every 10 minutes on the server and id like to pull that value onto my site via jquery load function im not sure I am doing it right but sample code is below.
$('#contentDiv').load('http://www.windfinder.com/windstatistics/beirut span#current-windspeed');

A: It is possible to do it but you would need a proxy. On your local machine you can utilize Fiddler but the same job on your webpage could be done by using jQuery & YML.
Reference

A: The Same-Origin Policy policy of browsers will prevent this from working. Basically, the browser protects users from attacks whereby injected scripts "call home" with data. There are ways around it if you control the target site, allowing certain domains to have access (not applicable here I know). More details at http://en.wikipedia.org/wiki/Same-origin_policy
However, Same-Origin Policy is a browser feature, so if you get the required value from server-side code, you'll be fine.
So:
JQuery  -->  Your Server --> Target Page

Edit
Just seen @uiwarrior's answer. This is the same ... act as a proxy for getting the data. You don't indicate the server-side language, but this would be relatively easy to using something like Html Agility Pack for .NET, or phpQuery for PHP (which is like JQuery on the server)


text:
Q: Finding the smallest number lexicographically I'm trying to print smallest number. My prof calls it lexicographical order I think.
For example, I have this list :
[27312,31539]
[49494,26089]
[2946,28149]

The result should be:
27312
26089
28149

Why 28149 is smaller than 2946 so, 2 = 2, but the next int 8<9 ,so it prints 28149.
Is it possible to implement this using lambda ?

A: You can use the min function with str as a key function:
print(min([27312,31539], key=str))
print(min([49494,26089], key=str))
print(min([2946,28149], key=str))

This outputs:
27312
26089
28149


text:
Q: Why is it possible to store a str value on a int type variable on Python using typing I come from a java background and i'm starting with python 3.x and types.
In java it's not possible to do something like this:
num:int = 5;
name:str = num
num = "hola"

print(type(num)) # <class 'int'>

The interpreter doesn't complain when storing an int value in a str variable or viceversa.
I didn't find any example of using this var_name: type_name = 5 kind of asignations in python's official 3.6.7 docs, but, again, the interpreter think it's ok.
Why is this possible?


text:
Q: Distinct number of changes in real time data Hi I am taking in data in real time where the value goes from 1009 , 1008 o 1007 to 0. I am trying to count the number of distinct times this occurs, for example the snippet below should count 2 distinct periods of change.

1008
1009
1008
0
0
0
1008
1007
1008
1008
1009
9
0
0
1009
1008

I have written a for loop as below but I can't figure out if the logic is correct as I get multiple increments instead of just the one

if(current != previous && current < 100)
x++;
else
x = x;

A: You tagged this with the LabVIEW tag. Is this actually supposed to be LabVIEW code?
Your logic has a bug related to the noise you say you have - if the value is less than 100 and it changes (for instance from 9 to 0), you log that as a change. You also have a line which doesn't do anything (x=x), although if this is supposed to be LV code, then this could make sense.

A: The code you posted here does not seem to make sense to me if I understand your goal.  My understanding is that you want to identify this specific pattern:
1009
1008
1007
0
And that any deviation from this sequence of numbers would constitute data that should be ignored.  To this end, you should be monitoring the history of the past 3 numbers.  In C you might write this logic in the following way:
#include <stdio.h>

//Function to get the next value from our data stream.
int getNext(int *value) {

  //Variable to hold our return code.
  int code;

  //Replace following line to get gext number from the stream.  Possible read from a file?
  *value = 0;

  //Replace following logic to set 'code' appropriately.
  if(*value == -1)
    code = -1;
  else
    code = 0;

  //Return 'code' to the caller.
  return code;

}

//Example application for counting the occurrences of the sequence '1009','1008','1007','0'.
int main(int argc, char **argv) {

  //Declare 4 items to store the past 4 items in the sequence (x0-x3)
  //Declare a count and a flag to monitor the occurrence of our pattern
  int x0 = 0, x1 = 0, x2 = 0, x3 = 0, count = 0, occurred = 0;

  //Run forever (just as an example, you would provide your own looping structure or embed the algorithm in your app).
  while(1) {

    //Get the next element (implement getNext to provide numbers from your data source).
    //If the function returns non-zero, exit the loop and print the count.
    if( getNext(&x0) != 0 )
         break;

    //If the newest element is 0, we can trigger a check of the prior 3.
    if(x0 == 0) {

      //Set occurred to 0 if the prior elements don't match our pattern.
      occurred = (x1 == 1007) && (x2 == 1008) && (x3 == 1009);
      if(occurred) {
        //Occurred was 1, meaning the pattern was matched.  Increment our count.
        count++;
        //Reset occurred
        occurred = 0;
      }

    //If the newest element is not 0, dont bother checking.  Just shift the elements down our list.
    } else {

      x3 = x2;  //Shift 3rd element to 4th position
      x2 = x1;  //Shift 2nd element to 3rd position
      x1 = x0;  //Shift 1st element to 2nd position

    }

  }

  printf("The pattern count is %d\n", count);

  //Exit application
  return 0;

}

Note that the getNext function is just shown here as an example but obviously what I have implemented will not work.  This function should be implemented based on how you are extracting data from the stream.
Writing the application in this way might not make sense within your larger application but the algorithm is what you should take away from this.  Essentially you want to buffer 4 elements in a rolling window.  You push the newest element into x0 and shift the others down.  After this process you check the four elements to see if they match your desired pattern and increment the count accordingly.

A: If the requirement is to count falling edges and you don't care about the specific level, and want to reject noise band or ripple in the steady state then just make the conditional something like
if ((previous - current) > threshold)

No complex shifting, history, or filtering required. Depending on the application you can follow up with a debounce (persistency check) to ignore spurious samples (just keep track of falling/rising, or fell/rose as simple toggling state spanning a desired number of samples).
Code to the pattern, not the specific values; use constant or adjustable parameters to control the value sensitivity.


text:
Q: Tikzpicture: How to caption with multiple axis Is there a way to caption multiple axes with tikzpicture? I don't want to use subfigures since each axis (and its corresponding figure) is connected via an arrow to another axis.
I have something similar to this:
\begin{figure}
\begin{tikzpicture}
\begin{axis} %axis 1
<code for plot here>
\draw node (bar1) at (some_coordinates){};
\end{axis}

\begin{axis}[ %axis 2
xshift = 3in
]
<code for plot here>
\draw node (bar2) at (some_coordinates) {};
\end{axis}

\begin{axis}[ %axis 3
xshift = 3in,
yshift = -3in,
]
<code for plot here>
\draw node (bar3) at (some_coordinates) {};
\end{axis}

\draw [->,thick,color=red,dashed] (bar1) -- (bar2);
\draw [->,thick,color=red,dashed] (bar2) -- (bar3);
\end{tikzpicture}
\end{figure}

Is it possible to add a caption to each axis?

A: Multiple axes environments are hard to connect, but at least you could use a groupplot by loading the groupplots library. Here is an example:
\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=1.12}
\begin{document}

\begin{figure}[ht]
\centering
\begin{tikzpicture}

\begin{groupplot}[group style={group size=2 by 2},height=7cm,width=7cm]
\nextgroupplot
\addplot coordinates {(0,0) (1,1) (2,2)};
\draw node (bar1) at (1,0){bar1};
\nextgroupplot
\addplot coordinates {(0,2) (1,1) (2,0)};
\draw node (bar2) at (1,2){bar2};
\nextgroupplot
\addplot coordinates {(0,2) (1,1) (2,1)};
\draw node (bar3) at (1.5,1){bar3};
\nextgroupplot
\addplot coordinates {(0,2) (1,1) (1,0)};
\end{groupplot}

\draw [->,thick,color=red,dashed](bar1)--(bar2);
\draw [->,thick,color=red,dashed](bar2)--(bar3);

\end{tikzpicture}
\end{figure}

\end{document}

A: If you want actual numbered captions, you can use \captionof in a node placed below the axis. You can have subfigure numbering if you prefer that, see e.g. https://tex.stackexchange.com/a/250032/586
\documentclass{article}
\usepackage{pgfplots}
\usepackage{capt-of}
\begin{document}
\begin{figure}
\begin{tikzpicture}[every axis/.style={width=7cm}]
\begin{axis}[name=axis1] %axis 1
\addplot {rnd};
\node (bar1) at (1,1){};
\end{axis}

\begin{axis}[ %axis 2
xshift = 3in,
name=axis2
]
\addplot {rnd};
\node (bar2) at (1,1) {};
\end{axis}

\begin{axis}[ %axis 3
xshift = 3in,
yshift = -3in,
name=axis3
]
\addplot {rnd};
\node (bar3) at (1,1) {};
\end{axis}

\draw [->,thick,color=red,dashed] (bar1) -- (bar2);
\draw [->,thick,color=red,dashed] (bar2) -- (bar3);

\begin{scope}[every node/.style={text width=7cm,align=left}]
\node [below] at (axis1.south) {\captionof{figure}{First caption}};
\node [below] at (axis2.south) {\captionof{figure}{Second caption}};
\node [below] at (axis3.south) {\captionof{figure}{Third caption}};
\end{scope}
\end{tikzpicture}
\end{figure}
\end{document}


text:
Q: UI router: if resolve function is given as a named dependency, resolve only executes once I've been using resolves extensively in my angular project and it has come to a point where for the sake of readability I want to move all of my resolve functions to independent modules (some states would then even be able to share the same resolve functions without me having to rewrite them).
So, a simplified example of what I had:
angular.module("stream", [
  "resources.groups",
  "ui.router"
]).config(function ($stateProvider) {
  $stateProvider.state("stream", {
    url: ... ,
    views: ... ,
    resolve: {
      groups: function (groups) {
        console.log("Resolving groups");
        return groups.get();
      }
    }
  }
});

angular.module("conversations", [
  "resources.groups",
  "ui.router"
]).config(function ($stateProvider) {
  $stateProvider.state("conversations", {
    url: ... ,
    views: ... ,
    resolve: {
      groups: function (groups) {
        console.log("Resolving groups");
        return groups.get();
      }
    }
  }
});

In this case, "Resolving groups" would be logged every single time the state changed to either stream or conversations from whichever other states (except of course child states of stream and conversations). Eg, visit stream (groups resolved) -> visit state3 -> visit conversations (groups resolved) -> visit stream (groups resolved)
However, when I refactored it to the following, the resolve is now only ever called once when I visit whichever state it is used on. Eg, visit state3 -> visit stream (groups resolved) -> visit conversations (NOT resolved here or ever again) -> visit state3 -> visit stream -> visit conversations .... The following caused this behavior:
angular.module("stream", [
  "resolves.groups",
  "ui.router"
]).config(function ($stateProvider) {
  $stateProvider.state("stream", {
    url: ... ,
    views: ... ,
    resolve: {
      groups: "resolveGroups"
    }
  }
});

angular.module("conversations", [
  "resolves.groups",
  "ui.router"
]).config(function ($stateProvider) {
  $stateProvider.state("conversations", {
    url: ... ,
    views: ... ,
    resolve: { groups: "resolveGroups" }
    }
  }
});

angular.module("resolves.groups", [
  "resources.groups"
]).factory("resolveGroups", function (groups) {
  return groups.get();
});

How do I achieve a situation where the resolve function is shared and reused from an external service, but it still executes every time there is a transition to a state which uses it?

A: The problem with the service approach is that AngularJS services are singletons, so they will be (lazily) instantiated only once.
However, since the injectables which are mapped to names in resolve objects are nothing more than simple independent data structures (arrays of strings and a function at the end), you can expose them at config-time in a constant :
angular.module('myApp.resolvers')
  .constant('myAppResolvers', {
    groups: ['groups', function (groups) {
      return groups.get();
    }],
    myOtherThing: ['$http', 'myService', '$q', function ($http, myService, $q) {
      // code for resolving some other thing
    }]
  });

And then in your config :
myApp.config('$stateProvider','myAppResovers', function ($stateProvider, myAppResolvers) {
  $stateProvider.state("stream", {
    url: ... ,
    views: ... ,
    resolve: {
      groups: myAppResolvers.groups
    }
}

So code reuse is achieved.


text: Q: My Informatiion design tool is getting closed without prior notice? I'm a beginer in IDT (SAP BO client tool Information design tool).After establishing a connection and starting a session, it closes automatically when i add some tables(1 or 2  tables added and it will be closed.. i mean the entire IDT))