text:
Q: Posting to Facebook Graph Api is slow I am creating a new Facebook app and there are actions attached to it, like the 'Listening to xxx' on Spotify.
Trouble is that the call takes around 6-7 seconds which is quite a long time. Beneath my code is the results of curl_getinfo. Is it supposed to be this slow?
    $attachment = array(
        'access_token' => $access_token,
        'album' => 'sergeant peppers',
    );

    $opts = array(
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_USERAGENT => 'facebook-php-3.1',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $attachment,
        CURLOPT_URL => 'https://graph.facebook.com/me/APPNAME:listening'
    );
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

The results of curl_getinfo:
[url] => https://graph.facebook.com/me/APPNAME:listening
[content_type] => text/javascript; charset=UTF-8
[http_code] => 400
[header_size] => 557
[request_size] => 238
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 6.002449
[namelookup_time] => 0.024892
[connect_time] => 0.179322
[pretransfer_time] => 0.77444
[size_upload] => 362
[size_download] => 212
[speed_download] => 35
[speed_upload] => 60
[download_content_length] => 212
[upload_content_length] => 362
[starttransfer_time] => 1.775707
[redirect_time] => 0
[certinfo] => Array
    (
    )

[redirect_url] =>

A: Well, you have gotten a http 400 return (bad request), which indicates something went wrong. Maybe if you get your request right the request will be faster?
This post: php cURL error in facebook api
indicates that you should remove 'CURLOPT_POST => true'
I also suggest adding 'CURLOPT_VERIFYPEER => false' if you still have problems.

A: No, it is not. This answer discusses the expected timings of the Facebook Graph API in more detail, though its problem diagnosis isn't applicable to your issue here.
Your best bet on discovering your bottleneck is network diagnostics, such as traceroute, dig, and the profiling features of cURL (as you're showing here). If you have a peer in a different locality, you can also try profiling from that location to see what changes.
Best of luck to you. This is extremely topical information, but it should be enough to get you started.


text:
Q: How can I use this code to play more sounds?    //Action to play Audio//
 -(IBAction)playAudio:(id)sender {
[self.loopPlayer play];
}

 //Action to stop Audio//
-(IBAction)stopAudio:(id)sender {
if (self.loopPlayer.isPlaying) {
    [self.loopPlayer stop];
    self.loopPlayer.currentTime = 0;
    self.loopPlayer.numberOfLoops = -1;
    [self.loopPlayer prepareToPlay];
    }
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//Code that gets audio file "trap synth"//
NSURL* audioFileURL = [[NSBundle mainBundle] URLForResource:@"trapsynth" withExtension:@"wav"];
self.loopPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];

}

This is the code i'm using with one button to play the sound when the button is tapped and stop the sound when the button is released. How would I go about adding more sounds to more buttons? I want to have more buttons that play and stop different sounds just like this.
property (nonatomic, strong) AVAudioPlayer *loopPlayer;

This code is also in my ViewController.h file

A: If you want to play different sounds at the same time you should look into creating separate AVAudioPlayers - if you create a different one for each sound, then you can easily control (play/stop) each of them separately with a specific button.

A: On the simplest level, you could do something like this, which allows you to use the same button handlers for all your audio.  The playAudio checks the tag of the Play button you press (be sure to set the tag value in IB, to 1,2,etc). There really only need be one Stop button.
You could enhance this in many ways, like attempting to reuse the AVAudioPlayer somehow, and loading the audio on the fly instead of all at the beginning.  Or storing your audio file info in an array, creating an array of AVAudioPlayers for management, etc. But this is a start.
-(IBAction)playAudio:(id)sender {
    // first, stop any already playing audio
    [self stopAudio:sender];

    if([sender tag] == 1){
        [self.loopPlayer1 play];
    } else if([sender tag] == 2){
        [self.loopPlayer2 play];
    }
}

-(IBAction)stopAudio:(id)sender {
    if (self.loopPlayer1.isPlaying) {
        [self.loopPlayer1 stop];
        self.loopPlayer1.currentTime = 0;
        self.loopPlayer1.numberOfLoops = -1;
        [self.loopPlayer1 prepareToPlay];
    } else if (self.loopPlayer2.isPlaying) {
        [self.loopPlayer2 stop];
        self.loopPlayer2.currentTime = 0;
        self.loopPlayer2.numberOfLoops = -1;
        [self.loopPlayer2 prepareToPlay];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL* audioFileURL1 = [[NSBundle mainBundle] URLForResource:@"trapsynth" withExtension:@"wav"];
    self.loopPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];

   NSURL* audioFileURL2 = [[NSBundle mainBundle] URLForResource:@"trapsynth" withExtension:@"wav"];
    self.loopPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
}

AND, in the .h file;
property (nonatomic, strong) AVAudioPlayer *loopPlayer1;
property (nonatomic, strong) AVAudioPlayer *loopPlayer2;

A: Ok although the answer provided by Miro is on the write track the code example given has issues.
Should be this in viewDidLoad -
- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL* audioFileURL1 = [[NSBundle mainBundle] URLForResource:@"trapsynth" withExtension:@"wav"];
    self.loopPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL1 error:nil];

   NSURL* audioFileURL2 = [[NSBundle mainBundle] URLForResource:@"other_audio_file" withExtension:@"wav"];
    self.loopPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL2 error:nil];
}

also stopAudio: method should be this
-(IBAction)stopAudio:(id)sender {
    if (self.loopPlayer1.isPlaying && (sender.tag == 1)) {
        [self.loopPlayer1 stop];
        self.loopPlayer1.currentTime = 0;
        self.loopPlayer1.numberOfLoops = -1;
        [self.loopPlayer1 prepareToPlay];
    }
    if (self.loopPlayer2.isPlaying && (sender.tag == 2)) {
        [self.loopPlayer2 stop];
        self.loopPlayer2.currentTime = 0;
        self.loopPlayer2.numberOfLoops = -1;
        [self.loopPlayer2 prepareToPlay];
    }
}

And finally for playAudio:
-(IBAction)playAudio:(id)sender {
    if([sender tag] == 1){
        [self.loopPlayer1 play];
    }
    if([sender tag] == 2){
        [self.loopPlayer2 play];
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function calls from data.map are not executed synchronously I am trying to call same function from map. Depending upon number of entries function will be called.
Here is my code
    getDetails = (inputData) => {
      const data = {
         accountName: "test",

       };
     let url = `/rest/jarvis/reports/v1/getData`;
       let thisdata = this;
       post(url, data)
         .then((response) => {
           if (
             response.data &&
             response.data.sb &&
             response.data.sb.length > 0
           ) {
         this.props.bs.betDetails = {
               data: [...response.data.sportsbookBets],
               exportAccesses: response.data.exportAccesses,
             };
             this.props.bs.betDetails.data.map((value, index) => {
               console.log("Index Value --->", index);
               this.getEventDetails(value, index);
             }),
               this.updateReducer({
                 ...this.props.bs,
               });
       }
    }
    }
    getEventDetails = async (value, index) => {
       let _this = this;
       let myPromise = new Promise(function (myResolve, myReject) {
         console.log("Index Value at the entry--->", index);
      const data = {
         accountName: "test",

       };
      let url = `/rest/jarvis/reports/v1/getBetEventData`;

         post(url, data).then((response) => {
    if (response.data) {
       console.log("Index Value inside--->", index);
               _this.eventIdIndexMap.set(
                 list.eventId != null
                   ? list.eventId
                   : _this.props.bs.betEventRequest.EventId,
                 index
               );
        _this.props.bs.testEventDetails[
                 _this.eventIdIndexMap.get(
                   list.eventId != null
                     ? list.eventId
                     : _this.props.bs.betEventRequest.EventId
                 )
               ] = _this.props.bs.betEventResponse;

    }}}
 await myPromise;
}

Here problem I am facing is inside post call of 'getEventDetails' index values are not getting in sequence.
I have used promise await and async but it is not working.
Can someone please tell me how to get it properly ?

A: map calls its callback function without await. You can use asynchronous functions in the callback function but they won't be executed in order.
But you can create your own map with await:

async function map(array, cb) {
    const result = [];
    for (const element of array) {
        result.push(await cb(element));
    }
    return result;
}

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
    console.log(await map([3, 2, 1], async el => { await sleep(el * 100); return 2 * el; }));
})();

or create your own Array.prototype.syncMap:

Array.prototype.syncMap = async function(cb) {
    const result = [];
    for (const element of this) {
        result.push(await cb(element));
    }
    return result;
}

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
    console.log(await [3, 2, 1].syncMap(async el => { await sleep(el * 100); return 2 * el; }));
})();

It looks like you don't even need a result. You can write your own Array.prototype.syncForEach:

Array.prototype.syncForEach = async function(cb) {
    for (const element of this) {
        await cb(element);
    }
}

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

[3, 2, 1].syncForEach(async el => { await sleep(el * 100); console.log(2 * el); });
[30, 20, 10].forEach(async el => { await sleep(el * 10); console.log(2 * el); });

As you can see in the output the functions in syncForEach are executed in order and the functions in forEach are executed out of order.


text:
Q: Compare a group of characters with a string C++ I have a 2D vector that is holding characters for a word search game.  I have to take a string (the word I'm searching for) and go through the whole list to compare the string and a group of characters to see if they match and output where I found the match in the 2D vector.  I am just confused on how to go about the comparison of strings and a group of characters.
This is the bit that I started trying to compare:
bool SearchWord::SolveRowsRight(int index)
{
    string findWord = GetWord(index);
    for(int i = 0; i < board.size(); i++)
    {
        for(int j = 0; j < board.size() - findWord.size(); j++)
        {
            if(findWord == board[i][j])
                return true;
        }
    }
    return false;
}


text:
Q: Using Lambda with lists I am trying to check if a string object is in a list. Simply written as:
if str in list:

The problem I am facing is that this list, is not a list of strings, but a list of tables. I understand that nothing is going to happen if I do this comparison directly. What I would like to do is access an attribute of each of these tables called 'Name'.
I could create a new list, and do my comparison against that:
newList = []
for i in list:
    newList.append(i.Name)

But as I am still a newbie, I am curious about Lambda's and wondered if it would be possible to implement that instead?
something like (... but probably nothing like):
if str in list (lambda x: x.Name):

A: You can write
if str in [x.Name for x in list]

Or more lazily,
if str in (x.Name for x in list)

In the latter (with parens) it builds a generator, while in the former (with brackets), it builds first the full list.

A: Lambdas pretty much doesn't needed here. You can just check it directly:
for table in my_list:
    if string in table.Name:
        #do stuff

Or using list comprehension, if you want it that way:
if string in [table.Name for table in my_list]:
    #do interesting stuff

More efficiently, as @Tim suggested, use a generator expression:
if string in (table.Name for table in my_list):

But if you insist in using lambdas:
names = map(lambda table: table.Name, my_list)
if string in names:
    #do amazing stuff!

Here's a little demo:
>>> class test():
    def __init__(self, name):
        self.Name = name

>>> my_list = [test(n) for n in name]
>>> l = list(map(lambda table: table.Name, my_list)) #converted to list, it's printable.
>>> l
['a', 'b', 'c']

Also, avoid using names of built in functions such as str, list for variable names. It will override them!
Hope this helps!

A: I guess you're looking for any:
if any(x.Name == s for x in lst):
   ...

If the list is not large and you need these names somewhere else, you can create a list or a set of names:
names = {x.Name for x in lst}
if s in names:
    ....

The lambda you wrote is already in python, and called attrgetter (in module operator):
names = map(attrgetter('Name'), lst)

Note that comprehensions are usually preferred to that.

A: you can use filter
>>> foo = ["foo","bar","f","b"]
>>> list(filter( lambda x:"f" in x,foo))
['foo', 'f']

update
i keep this answer because someone may come here for lambdas but for this problem @arbautjc 's answer is better.


text:
Q: How to serialize armadillo's vector How can I serialize arma::Col? Below are a MWE and the error output.
MWE:
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <iostream>
#include "armadillo"

namespace mpi = boost::mpi;

struct S
{
    int i;
    arma::Col<double>::fixed<3> cvector;

    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar& i;
        ar& cvector;
    }
};

int main()
{
    mpi::environment env;
    mpi::communicator world;

    S s;

    if (world.rank() == 0)
    {
        s.cvector[0] = 2;
        s.cvector[1] = 2;
        world.send(1, 0, s);
    }
    else
    {
        world.recv(0, 0, s);
        std::cout << s.cvector[0] << std::endl;
        std::cout << s.cvector[1] << std::endl;
    }

    return 0;
}

Error output (skipping "required from" stuff):
error: 'class arma::Col<double>::fixed<3ull>' has no member named 'serialize'; did you mean 'set_size'?
         t.serialize(ar, file_version);
Edit: This post seems to be related to my question and unfortunately it is unanswered.

A: The real crux of the issue here is that you want to add a serialize() member function to the various Armadillo objects, but that doesn't appear to be possible... except that thanks to a clever use of the preprocessor in Armadillo, it is!
Take a look at Mat_bones.hpp and Col_bones.hpp... you'll see something like this, inside of the class definitions of Mat and Col:
public:

#ifdef ARMA_EXTRA_COL_PROTO
  #include ARMA_INCFILE_WRAP(ARMA_EXTRA_COL_PROTO)
#endif

It made me very happy when I found this, because now I can do something like define a file called Mat_extra_bones.hpp:
//! Add a serialization operator.
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);

and then Mat_extra_meat.hpp:
// Add a serialization operator.
template<typename eT>
template<typename Archive>
void Mat<eT>::serialize(Archive& ar, const unsigned int /* version */)
{
  using boost::serialization::make_nvp;
  using boost::serialization::make_array;

  const uword old_n_elem = n_elem;

  // This is accurate from Armadillo 3.6.0 onwards.
  // We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call.
  ar & make_nvp("n_rows", access::rw(n_rows));
  ar & make_nvp("n_cols", access::rw(n_cols));
  ar & make_nvp("n_elem", access::rw(n_elem));
  ar & make_nvp("vec_state", access::rw(vec_state));

  // mem_state will always be 0 on load, so we don't need to save it.
  if (Archive::is_loading::value)
  {
    // Don't free if local memory is being used.
    if (mem_state == 0 && mem != NULL && old_n_elem > arma_config::mat_prealloc)
    {
      memory::release(access::rw(mem));
    }

    access::rw(mem_state) = 0;

    // We also need to allocate the memory we're using.
    init_cold();
  }

  ar & make_array(access::rwp(mem), n_elem);
}

Then, in your program, all you need to do is
#define ARMA_EXTRA_MAT_PROTO mat_extra_bones.hpp
#define ARMA_EXTRA_MAT_MEAT mat_extra_meat.hpp

and the serialize() function will be a member of the Mat class.  You can easily adapt this solution for other Armadillo types.
In fact this is exactly what the mlpack library (http://www.mlpack.org/) does, so if you are interested you can take a closer look at the exact solution I implemented there:
https://github.com/mlpack/mlpack/tree/master/src/mlpack/core/arma_extend

A: Since arm::Col::fixed doesn't support serialisation itself, you can either write it in your S class, or write a class that wraps it and serialises it.  I'd recommend the 2nd option since it will let you use arm::Col::fixed in anything that you want to serialise without repeating.

A: According to @UKMonkey answer I wrote a working example. Actually for this case there is no need to split serialize tosave and load.
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
//#include <boost/serialization/split_free.hpp>
#include <iostream>
#include "armadillo"

namespace mpi = boost::mpi;

typedef arma::Col<double>::fixed<3> cvector;

//BOOST_SERIALIZATION_SPLIT_FREE(cvector)

namespace boost
{
    namespace serialization
    {
        /*template<class Archive>
        void save(Archive& ar, const cvector& cv, unsigned int)
        {
            std::cout << "saving" << std::endl;
            ar& cv[0];
            ar& cv[1];
            ar& cv[2];
        }
        template<class Archive>
        void load(Archive& ar, cvector& cv, unsigned int)
        {
            std::cout << "loading" << std::endl;
            ar& cv[0];
            ar& cv[1];
            ar& cv[2];
        }*/
        template<class Archive>
        inlide void serialize(Archive& ar, cvector& cv, unsigned int)
        {
            ar& cv[0];
            ar& cv[1];
            ar& cv[2];
        }
    }
}

struct S
{
    int i;
    cvector c;

    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int)
    {
        ar& i;
        ar& c;
    }
};

int main()
{
    mpi::environment env;
    mpi::communicator world;

    S s;

    if (world.rank() == 0)
    {
        s.i = 3;
        s.c[0] = 2.;
        s.c[1] = 4.;
        world.send(1, 0, s);
    }
    else
    {
        world.recv(0, 0, s);
        std::cout << s.i << std::endl;
        std::cout << s.c[0] << std::endl;
        std::cout << s.c[1] << std::endl;
    }

    return 0;
}


text:
Q: connection string on virtual dedicated server not working I'm moving from a shared hosting to Virtual Dedicated Server (both at GoDaddy).
Suprisingly, everything went fine up until now. However, now my web application seems unable to connect to the database (which I created on the server).
I tried several options, including giving it the server name etc. for example:
<add name="dbname" connectionString="Data Source=servername\SQLEXPRESS2008;Initial Catalog=theDB;User Id=servername\usernameAcceptedByMangmentStudio;Password=mypwd; Trusted_Connection=False;"/>

also:
<add name="dbname" connectionString="Data Source=.\SQLEXPRESS2008;Initial Catalog=theDB;User Id=usernameAcceptedByMangmentStudio;Password=mypwd; Trusted_Connection=False;"/>

also:
<add name="dbname" connectionString="Data Source=servername\SQLEXPRESS2008;Initial Catalog=theDB; Integrated Security=True;>

(this is how it works on my local machine).
nothing seems to work. any ideas? thanks in advance.

A: It seems you don't know whether you have a named instance or a default instance. Or even the difference between the two.
First I'll explain the quickest way to determine which you have, then I'll explain the differences.
You need to connect to your server (I assume you can remote desktop or something similar), then open Control Panel > Administrative Tools > Services. In that list there should be an item called SQL Server, and it will either look like this:

SQL Server (MSSQLSERVER)

Or this:

SQL Server (some_name)

The former is a default instance. If this is what you see, then the connection string should be:
"Data Source=localhost;..."

The latter is a named instance. If this is what you see, your connection string should be:
"Data Source=localhost\some_name;..."

If you see both, then you need to tell us how you initially connected to this instance in order to create the database (and you need to decide which one you want to use, since you probably don't need both).
If that doesn't help, you need to be more specific than "doesn't work." Are you unable to connect to the server, or the database? What is the actual error message? When you created the database, did you use the User Instances / AttachDbFileName features? Can you show a screen shot of the connection dialog in Management Studio that is successful? Is your app on the server or on your local machine? Is it possible you should be specifying the IP address instead of various local references? Have you contacted GoDaddy support about your problem? They are far better equipped to help you than a programming Q&A site, since they can connect to your server in 10 seconds and tell you exactly how you should be referencing the SQL Server instance.
As for the differences, named instances are typically used when you need to install multiple individual instances of SQL Server. This is not usually a requirement on a production machine; much more common on development machines where you must test multiple versions, simulate different environments, or temporarily during a migration or side-by-side upgrade. A default instance listens out of the box on port 1433. Named instances run on other ports and usually use the SQL Browser service for remote machines to identify how exactly to connect to them.

A: If your DB has UserName and Password(SQL Server Authentication) just simply use this:
<add name="dbname" connectionString="Data Source=yourServerName;Initial Catalog=YourDB;User ID=YouruserId;Password=YourPassWord" providerName="System.Data.SqlClient"/>

FYI: Make sure your database Server Authentication is SQL Server and WindowsAuthentication mode
You can check also : Connection strings for SQL Server 2008 for more info.
Regards


text:
Q: Yii2 migration does not work on Heroku Recently, I created Yii2 application(basic template) and successfully deployed it on Heroku. Then I wanted to set up database, so I added postgresql addon for heroku application and configured db config like this:
if (getenv("YII_ENV") == 'prod') {
    $url = parse_url(getenv("DATABASE_URL"));
    $dsn = 'pgsql:host='.$url['host'].';port='.$url['port'].';dbname='.substr($url["path"], 1);
    $username = $url["user"];
    $password = $url["pass"];
} else {
    $dsn = 'mysql:host=localhost;dbname=yii2_quizie';
    $username = 'root';
    $password = '1234';
}

return [
    'class' => 'yii\db\Connection',
    'dsn' => $dsn,
    'username' => $username,
    'password' => $password,
    'charset' => 'utf8',
];

After that I've set two heroku config variables: YII_ENV=prod and YII_DEBUG=false.
Then I added simple migration and tried to run it using heroku run bash and then running php yii migrate
That's what I've received:
~ $ php yii migrate
Exception 'ReflectionException' with message 'Class yii\gii\Module does not exist'

in /app/vendor/yiisoft/yii2/di/Container.php:415

Stack trace:
#0 /app/vendor/yiisoft/yii2/di/Container.php(415): ReflectionClass->__construct('yii\\gii\\Module')
#1 /app/vendor/yiisoft/yii2/di/Container.php(358): yii\di\Container->getDependencies('yii\\gii\\Module')
#2 /app/vendor/yiisoft/yii2/di/Container.php(151): yii\di\Container->build('yii\\gii\\Module', Array, Array)
#3 /app/vendor/yiisoft/yii2/BaseYii.php(340): yii\di\Container->get('yii\\gii\\Module', Array)
#4 /app/vendor/yiisoft/yii2/base/Module.php(354): yii\BaseYii::createObject('yii\\gii\\Module', Array)
#5 /app/vendor/yiisoft/yii2/base/Application.php(304): yii\base\Module->getModule('gii')
#6 /app/vendor/yiisoft/yii2/base/Application.php(267): yii\base\Application->bootstrap()
#7 /app/vendor/yiisoft/yii2/console/Application.php(114): yii\base\Application->init()
#8 /app/vendor/yiisoft/yii2/base/Object.php(107): yii\console\Application->init()
#9 /app/vendor/yiisoft/yii2/base/Application.php(206): yii\base\Object->__construct(Array)
#10 /app/vendor/yiisoft/yii2/console/Application.php(79): yii\base\Application->__construct(Array)
#11 /app/yii(22): yii\console\Application->__construct(Array)
#12 {main}

Anyone knows solution to this? On the local machine migration works perfectly fine.

A: Problem solved by running composer install in heroku shell. This is really weird, because heroku was suppose to automatically do it after upload of application.

A: Usually you don't want to install -dev stuff in production, YII_ENV must be defined as 'prod' both in the web/index.php and the yii script command itself.


text:
Q: I cannot update a join table with manyToMany property using nestjs and typeorm I have set up a many to many relation between a user table and a spot table.
Here is the user entity:
@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ default: '' })
  first_name: string;

  @Column({ default: '' })
  last_name: string;

  @Column({ default: '' })
  email: string;

  @Column({ default: '' })
  adress: string;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  createdAt: Date;

  @ManyToMany(() => SpotEntity, (spot) => spot.users)
  @JoinTable({
    name: 'spot_user',
    joinColumn: {
      name: 'user_id',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'spot_id',
      referencedColumnName: 'id',
    },
  })
  spots: Spot[];
}

And here is the spot entity:
@Entity('spot')
export class SpotEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ default: '' })
  title: string;

  @Column({ default: '' })
  description: string;

  @Column({ default: '' })
  address: string;

  @Column({ default: '' })
  coordinates: string;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  createdAt: Date;

  @ManyToOne(() => TagEntity, (tag) => tag.spots)
  tag: TagEntity;

  @ManyToMany(() => UserEntity, (user) => user.spots)
  users: User[];
}

This creates the join table as it should.
But now I am a bit confused as to how add a spot to a user.
To do so I added a service like so, which has access to both user and spot repository:
I a able to get the spot and the user, but the spot never saves into the user, and the join table is never updated.
  async addSpotToUser(id?: number, spotId?: number): Promise<void> {
    const mySpot = Object.values(spotId)[0];
    const user = await this.userRepository.findOneBy({ id: Number(id) });
    const spot = await this.spotRepository.findOneBy({ id: mySpot });
    user.spots.push(spot);
    this.userRepository.save(user);
  }
}


text:
Q: Resource exhaustion event: the JVM was unable to allocate memory from the heap I'm trying to fetch more than 1 million records in the microservices. I'm getting an error. I need to keep increasing the app memory for the service in order to fetch a huge amount of data. Is there any method I can use to fetch huge data instead of increasing the app memory.
2022-10-11T11:22:04.898+08:00 [APP/PROC/WEB/0] [ERR] Resource exhaustion event: the JVM was unable to allocate memory from the heap.
2022-10-11T11:22:04.898+08:00 [APP/PROC/WEB/0] [ERR] ResourceExhausted! (1/0)

        @Value("${batch-size}")
        private int batchSize;

    public void archiveTableRecords(JdbcTemplate sourceDbTemplate, JdbcTemplate targetDbTemplate,
        ArchiveConfigDTO archiveObj) {
            try {
                String sourceTable = archiveObj.getSourceTable();
                String archive_months =archiveObj.getArchiveCriteriaMonths();
                List<Object> primaryKeyValueList = new ArrayList<>();
                String compareDate1 = getCSTDateNew(archive_months);
                logger.info("Archive criteria date: {}", compareDate1);
                List<Map<String, Object>> sourceRecords = sourceDbTemplate
                        .queryForList(ArchiveSQLQueries.buildSQLQueryToFetchSourceRecords(sourceTable), compareDate1);
                int sourceRecordsSize = sourceRecords.size();
                logger.info("Fetched {} {} record(s)", sourceRecords.size(), sourceTable);
                if (sourceRecordsSize > 0) {
                    int recordsInserted = copySourceRecords(targetDbTemplate, archiveObj.getTargetTable(),
                            archiveObj.getPrimaryKeyColumn(), sourceRecords, primaryKeyValueList);
                    if (recordsInserted > 0)
                        deleteSourceRecords(sourceDbTemplate, sourceTable, archiveObj.getPrimaryKeyColumn(),
                                primaryKeyValueList);
                }
            } catch (Exception e) {
                logger.error("Exception in archiveTableRecords: {} {}", e.getMessage(), e);
            }
        }

    public static String buildSQLQueryToFetchSourceRecords(String sourceTable) {
            StringBuilder sb = new StringBuilder("SELECT * FROM " + sourceTable + " where update_dts <= ?");
            return sb.toString();
        }

        public int copySourceRecords(JdbcTemplate targetDbTemplate, String targetTable, String primaryKeyColumn,
                List<Map<String, Object>> sourceRecords, List<Object> primaryKeyValueList) {
            int result = 0;
            logger.info("Copying records to {}", targetTable);
            int[][] insertResult = targetDbTemplate.batchUpdate(
                    ArchiveSQLQueries.buildSQLTargetRecordInsertionQuery(targetTable, sourceRecords.get(0),
                            primaryKeyColumn),
                    sourceRecords, batchSize, new ParameterizedPreparedStatementSetter<Map<String, Object>>() {
                        @Override
                        public void setValues(PreparedStatement ps, Map<String, Object> argument) throws SQLException {
                            int index = 1;

                            for (Entry<String, Object> obj : argument.entrySet()) {
                                if (obj.getKey().equals(primaryKeyColumn))
                                    primaryKeyValueList.add(obj.getValue());
                                else
                                    ps.setObject(index++, obj.getValue());
                            }
                        }
                    });

            result = getSumOfArray(insertResult);
            logger.info("Inserted {} record(s) in {}", result, targetTable);
            return result;
        }

I have tried above code when fetching the data somehow i'm getting error .

A: Judging by method names, you copy from one table to another. Do it in batches using LIMIT and OFFSET. Simplified example:
SELECT *
FROM table
WHERE condition
ORDER BY column_which_ensures_last_added_data_is_fetched_last
LIMIT 5
OFFSET 0;

For the next batch change the offset using the number of processed records. Refer to the documentation for more examples. ORDER BY a column so you get oldest data first, newest last to ensure you won't get duplicates. If primary key is auto incremented id, it's good choice for this purpose.
If you need the count for logging purposes either use COUNT function, or calculate number of processed entities using count of batches.
SELECT COUNT(*)
FROM table
WHERE condition;

Algorithm pseudo code:
int processed = 0;
List<Map<String, Object>> list = //fetch using above query, replace offset with processed
while(!list.isEmpty()) {
  //copy contents of list to target
  //handle exceptions, data not inserted in target, etc.
  processed += list.size();
  list = //fetch using above query, replace offset with processed
}


text:
Q: Android, simplexml serial.read from an empty file woes Following suggestions on this site, I have adopted SimpleXML from org.simpleframework.xml.
I use this code to deserialize my class from a file on disk:
      try {
            myPoints = serial.read(Points.class, new File(getFilesDir(), "points.xml"));
            Log.i(TAG, "Number of Points: " + myPoints.getSize());
        } catch (FileNotFoundException e) {
            Log.d(TAG, "No data found!");
        } catch (Exception e) {
            Log.d(TAG, "Uncaught exception: ", e.getMessage());
        }

In the event the contents of file "points.xml" is not legal xml (in my case it's an empty file), serial.read breaks (an exception occurs in Persister.class, sorry I don't have simplexml sources...).
Should I check for xml consistency beforehand?
Can anybody help?

A: No need to validate before-hand since you won't be able to fix the problem.  Just make sure it fails gracefully (as your code appears to be doing).
You may, however, want to see if the file is empty or not in the case of a deserialization error.  An empty file is likely not a problem where as a malformed XML file is!


text:
Q: use translate method with one parameter I tried to use translate method with one parameter
I know that it takes a table and deletechars but I only want to use the deletechars one ...
this my code
import os

def re_name():
    pic_dir = r"C:\Users\Maysara\Desktop\aaa"
    file_list = os.listdir(pic_dir)
    os.chdir(pic_dir)
    for item in file_list :
         new_name = item.translate(None,"1234567890")
         os.rename(item,new_name)
    print("done")

re_name()

I have this error

Traceback (most recent call last):
    File "C:/Users/Maysara/PycharmProjects/untitled1/hello.py", line 14, in
      re_name()
    File "C:/Users/Maysara/PycharmProjects/untitled1/hello.py", line 10, in re_name
      new_name = item.translate(None,"1234567890")
  TypeError: translate() takes exactly one argument (2 given)


text:
Q: What is the type of QML this in C++? I want to pass the QML item reference to C++. It works using the id explicitly:
Item {
  id: qmlitem
  x: CppObj.getValue(qmlitem)
}

// c++
int getValue(QObject * qmlItem) {
  return 0;
}

if I pass this:
Item {
  x: CppObj.getValue(this)
}

QObject * qmlItem is 0x0.
If I replace
int getValue(QObject * qmlItem)

by
int getValue(void * qmlItem)

qmlItem is not 0x0 - it has a value but of which type?  Is it possible to obtain the QObject* from it?

A: In QML, the value of this is currently undefined. Passing it to C++ will not yield any meaningful result. Whatever its content may be, it is not a reference to the current QML item. So just stick to your first solution and pass an ID.


text:
Q: How to create Postgres database containing dot in it's name? I am trying to create the Postgres database using the terminal,
Normally we can create the database like
CREATE DATABASE mydatabase;
but I wanted to create with the database with a dot. like
CREATE DATABASE my.database;
I was trying to escape the characters. but it doesn't work
CREATE DATABASE my.\database;
CREATE DATABASE my\.database;
as an expected output, it should create the database named my.database

A: you should create the database using
create database "my.database";


text:
Q: Trouble formatting a sequence I'm trying to type this problem but I'm having issues as to how I go about the bit within the braces on the right side of the equals sign.

Here's my attempt at formatting this question.
\documentclass{article}
\usepackage{amsmath, amssymb}

\begin{document}

\[
\left\{a_t\right\}_{t=1}^4 \text{ defined recursively by } a_t=
\left\{(x,y)\Bigg|
\begin{cases}
x=t \\
y=9-t^2
\end{cases}
\right\}
\]

\end{document}

A: You can use an array. I present also the version without the inner brace, which I find unnecessary, and my preferred one at the bottom with a single line.
\documentclass{article}
\usepackage{amsmath, amssymb}

\begin{document}

\[
\{a_t\}_{t=1}^4
\text{ defined recursively by }
a_t=
\left\{(x,y)\;\middle|\;
\left\{\begin{array}{@{}c@{}}
x=t \\
y=9-t^2
\end{array}\right.
\vphantom{\Bigg|}
\right\}
\]

\[
\{a_t\}_{t=1}^4
\text{ defined recursively by }
a_t=
\left\{(x,y)\;\middle|\;
\begin{array}{@{}c@{}}
x=t \\
y=9-t^2
\end{array}
\right\}
\]

\[
\{a_t\}_{t=1}^4 \text{ defined recursively by }
a_t=\{(x,y) \mid x=t, y=9-t^2 \}
\]

\end{document}

A: I propose this simple code, using an aligned environment, and the \set command, as defined by the \DeclarePairedDelimiterX command from mathtools:
\documentclass{article}
\usepackage{mathtools, amssymb}

\DeclarePairedDelimiterX{\set}[1]\{\}{\setargs{#1}}
\NewDocumentCommand{\setargs}{>{\SplitArgument{1}{;}}m}
{\setargsaux#1}
\NewDocumentCommand{\setargsaux}{mm}
{\IfNoValueTF{#2}{#1}{\nonscript\,#1\nonscript\;\delimsize\vert\nonscript\:\allowbreak #2\nonscript\,}}

\begin{document}

\[
\set{a_t}_{t=1}^4 \text{ defined recursively by } a_t=
\set[\bigg]{(x,y);
\begin{aligned}
x & =t \\[-0.5ex]
y & =9-t^2
\end{aligned}}
\]

\end{document}

A: welcome to TeX-SE. Try to fit your cases into a matrix environment, like in the following:
\documentclass{article}
\usepackage{amsmath, amssymb}

\begin{document}

\[
\left\{a_t\right\}_{t=1}^4 \text{ defined recursively by } a_t=
\left\{(x,y)\Bigg|\,
\begin{matrix}
x=t \\
y=9-t^2
\end{matrix}
\right\}
\]

\end{document}


text:
Q: How to update mongodb filed value into null without omitting it via mongoengine? I am using flask-mongoengine and here is a problem confused me.
1. Models
class Student(Document):
    name = StingField()
    info = DictField(default={'address':None,'age':20},null=True)

*update address

student = Student.objects(id=id).first()
student.info['address'] = 'LA'
student.save()

it works well

*empty address

student = Student.objects(id=id).first()
student.info['address'] = None
student.save()

Here is the problem. The document in the collection omit the 'address' field.  It only show like this: info:{"age":20}.
Question:
How to keep the field exist in the collection even its value is null ?
(I know that using update instead of save can do this, but what if I insist using save, are ther any method to solve it?)


text:
Q: Upload file Directly to FTP Server in Python Is there any way to directly send files from one API to another FTP server without downloading them to local in Python 3.
Currently we downloading from one API to local and then sending it to FTP server, want to avoid that hop from data flow by directly sending files to server.

A: you can use byte data of the file(it will store as in-memory) and pass that to another API.

A: One of the options would be having another API function (TransferFile, ...), which will transfer data from API server to FTP site. Then you just call that API method from your code without downloading data to the local server.

A: The FTP protocol has provision for initiating a data transfert between two remote hosts from a third party client. This is called the proxy mode. Unfortunately, most servers disable it for security reasons, because it used to be a very efficient way for DOS attacks.
If you have control on both servers and if both use FTP and if they are not publicly exposed, this can be very efficient.
In any other use case, the data will have to pass through the client. The best that can be done is to open both connections and transfer data to the target host as soon as it has been received from the source without storing it on disk.


text:
Q: Database Design - Storing n weeks data in database and update each week I want to show last four Sundays temperature for particular city, I need to update the database weekly (on Sundays)
Database Design 1
city_id     temp_pre_sunday1   temp_pre_sunday2   temp_pre_sunday3  temp_pre_sunday4
1                  24.3              35.2           24.4             28.0
2                  4.0                2.0           6.0              7.0

 .
2000

I can update the database each Sunday. Is this good database design?
Database Design 2
 city_id      temp   date
   1          24.3    2017-12-03
   1          35.2    2017-11-26
   1          24.4    2017-11-19
   1          28.0    2017-11-12
   2          4.0     2017-12-03
   2          2.0     2017-11-26
   2          6.0     2017-11-19
   2          7.0     2017-11-12
   .
   .

I need only four Sundays not more than that.
I think first method is better, because  that way for 2000 cities I will have 2000 rows and 5 columns, in the second method I will have 8000 rows and 3 columns,
But in first method I need to update all the four columns,but in the second method I can maybe delete and insert one row.
Which is the better database design?

A: Database design 2 is the best way. You have more control and great flexibility to manipulate the data, to make reports, and extend applications etc...
Says, what if you want to fetch the 5 weeks data, or more, instead of 4 weeks? For database design 2 you only need to modify the query:
SELECT city_id, temp FROM table WHERE date >= _last_n_week_sunday_date_

Another things is, I may think you are creating a weather application, and trying to fetch the monthly average of temperature of each city, simpler query can get the report
SELECT city_id, YEAR(date), MONTH(date), AVG(temp) FROM table GROUP BY city_id, YEAR(date), MONTH(date)

You may also want to store more attributes later of each city, says humidity. You only need to create 1 more column for database design 2. Instead, you may need to do more hard work to work with database design 1.

A: The way to evaluate "best" is complicated. But "number of rows" is almost never a problem in relational databases - they are specifically designed to handle huge numbers of rows.
A much more useful way to think about it is "what are the common things I want to do with the data".
I'm guessing you have a few use cases.
The first is "record new measurements". As you say, that's a little painful in design one.
The second is "find or report on measurements".
In design one, it's easy to answer questions like "what was the temperature in city x on the last Sunday?". But "what was the coldest temperature in the last 3 weeks" is harder. Or "what was the difference between the highest and lowest temperatures for city X?". If the number of weeks is passed in as a parameter, you end up constructing awkward queries. In design two, all of those queries are pretty straightforward.
That alone suggests that design 2 is better.
But as commenters have noted, requirements for databases tend to change. Most people think you have a good design if you can accommodate those changes by adding data, rather than changing your schema. So, if you need to store data for more than 4 Sundays, design 2 requires a schema change; design 1 doesn't. If you have to record data other than temperature, in design 1 you suddenly have multiple columns for each week; in design 2, you can simply add a "measurement_type" column (a much smaller change). So, it's likely that design 2 is more flexible in the face of change.


text:
Q: Website cannot load Microsoft.EntityFrameworkCore I have an API-only site (no pages) that is terminating as soon as it starts.
I found the following errors in Event Viewer.
Application: w3wp.exe
CoreCLR Version: 6.0.21.52210
.NET Version: 6.0.0
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
File name: 'Microsoft.EntityFrameworkCore, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
   at Program.<Main>$(String[] args)

And...
Application '/LM/W3SVC/18/ROOT' with physical root 'C:\inetpub\wwwroot\tt.railtrax.com\' hit unexpected managed exception, exception code = '0xe0434352'. First 30KB characters of captured stdout and stderr logs:
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
File name: 'Microsoft.EntityFrameworkCore, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
   at Program.<Main>$(String[] args)

When I look at Microsoft.EntityFrameworkCore.dll in my deploy folder, it appears to be version 6.0.21.

Package Manager says I have 6.0.1 installed. So I don't know why I have 6.0.21, or if it should work with that version.

Does anyone know if these version discrepancies matter, or what else I could try to resolve this?
The project is running fine on my own computer. I very recently upgraded all the suggested packages in Package Manager. I assume it happened as a result of that.
UPDATE:
Some additional information:

*

*As can be seen from the error message, the project I'm having trouble with is TTRailtrax.

*TTRailtrax has a dependency on RailtraxCore, which has Microsoft.EntityFrameworkCore.dll installed.

*I am deploying to a local folder and then manually copying those files to the server. This has been working until now.

*The only thing I can think that changed is that I updated the recommended NuGet packages.

*The project continues to run fine on my local computer.

*I have confirmed the same version of Microsoft.EntityFrameworkCore.dll exists on my local machine and the server.

*I have cleaned my solution.

*I uninstalled and then re-installed Microsoft.EntityFrameworkCore.dll twice now.

*I have restarted the app on IIS several times.

*I have redeployed to the server several times.

*I have updated Visual Studio to the very latest version.

UPDATE:
Upon further investigation, I see that my bin\Release\net6.0 folder, contains Microsoft.EntityFrameworkCore.dll with product version 6.0.1. But then in my deployment folder, this file has product version 6.0.0.
It seems highly likely that this is related to the issue I'm seeing. Under what circumstances would a different DLL version be placed in my deployment folder than the one in my bin folder?
I tried copying the file from the bin folder but that didn't help.

A: This started as a comment that exceeded the character limit...
Hopefully one of these suggestions/strategies go somewhere. Mostly going off a few potential hunches here from previous issues with .NET assemblies not behaving. (Though, please bare in mind that it's been a year or two since I was working on a large C# code base).
(i) Issues with conflicting Nuget repo sources
This is usually if you have a company-specific Nuget repository. I've seen issues happen if there are conflicting packages, versions, etc. between the public Nuget repo (or if even allowed in some cases) and the company's one.
(ii) Issues with Nuget package requesting conflicting dependency versions
I very distinctly remember at one point that I had to manually check that each of my Solution-Wide dependencies were on the same version. I never trust the per-package view since it's incredibly easy to install the more up-to-date, but wrong and conflicting package. In other words, ensure that any packages referenced by EF Core or any other packages that would bring in EF Core are on the same version between projects.
(iii) Your local Nuget package cache may be corrupted or inconsistent
It would not be the first time where I've had to just delete the Nuget  caches and just redownload packages. Important: If I recall correctly, this likely may require having to reinstall or repair install .NET Core.
The various default locations for the Nuget caches are detailed on Microsoft's docs here. In case the link breaks, here is the tl;dr:

*

*Global Packages
Windows: %userprofile%\.nuget\packages
Mac/Linux: ~/.nuget/packages
(Note: can be overwritten by NUGET_PACKAGES environment variable, or the globalPackagesFolder project config property.

*

*Package Download Cache
Windows: %localappdata%\NuGet\v3-cache
Mac/Linux: ~/.local/share/NuGet/v3-cache
(Note: can be overwritten by NUGET_HTTP_CACHE_PATH environment variable)

*Project packages within the solution folder itself.
(iii) Use the debugger's "Modules" window to see which DLLs are loaded, and see which DLL is throwing the exception
This ideally can pin-point which the library or executable that is the culprit.

*

*Try enabling pausing on all exceptions (i.e. uncheck Just My Code and enable pausing on all unhandled exceptions.

*In debugging mode, open the "Modules" window. When paused, this should allow you to see which DLLs are loaded (including their version and such), and which DLL is currently being executed (or namely throwing an exception).

*Worst case, enable stepping into .NET source code. (This surprisingly has helped numerous times with very strange issues.)

Hopefully one of these tips may be helpful to determine what the root cause is.
Or at least what may be potentially the culprit.

A: I ran exactly in the same issue, since I updated EntityFrameworkCore.Sqlite from 6.0.0 to 6.0.1.
The last days I did more or less the options mentioned above.
Today I found a (hopefully) final solution which worked for me:
In the Nuget Manager was only Microsoft.EntityFrameCore.Sqlite listed under Installed, not Microsoft.EntityFrameworkCore. So the dependcy seems to be included from the Sqlite package. I added the Microsoft.EntityFrameworkCore. package explicit to my web application and since that the publish folder contains the current version 6.0.1 of this and all further  dependencies.

A: Following step guide to help you solve the problem:

*

*Delete all bin and obj hidden folder from your project (do it on every project in your solution).

*Clean the solution.

*Rebuild solution.

*Publish again.

We have two folders bin obj because the compilation process goes through two steps, compiling and linking. See the below diagram.

⬤ In compiling phase, every code file is compiled into individual compiled units. So if you have two code files, two independent compiled codes will be generated.
⬤ In linking phase, all these compiled code files are linked and compiled into a single unit assembly which can be a DLL or EXE.
Ref: Link


text:
Q: Disable app rotation if resolution is small I am currently working on an Android App written in Kotlin with Jetpack Compose. My goal is to get a responsive app that runs on smartphones and tables responsively. To do this I get the user's curent width and then decide on that width how I will display the UI because in some cases I have to show something else.
I get the current width of the user's display by using a BoxWithConstraints:
BoxWithConstraints(modifier = Modifier.fillMaxSize())
{
   val largeScreen = this.maxWidth > 1000.dp
}

This works fine for now but when a user is rotating the screen on his smartphone to landscape I get problems because of the miniscule height of the device. In my app it does not even make sense to use it in landscape. And I do not want users to use landscape in the app on smartphones. It is fine on tablet devices but not on smartphones.
All I could find was to lock portrait mode for the whole app. But what I would love to have would be to enable landscape and portrait on tablet and enable portrait mode solely on smartphone.
Has anyone also had this problem.
Thanks a lot!

A: There's getRequestedOrientation() and a setter for the same. You could use the largeScreen boolean to put conditions on the former, and allow landscape rotation if the screen is large, blocking otherwise with the help of the latter.


text:
Q: Delphi convert csv to utf-8 I have a csv file which might or might not be in utf-8 format.
Is there a way to convert an existing .csv to utf-8 format and then just overwrite the existing one?

A: CSV is a way of organising characters in a file, placing meaning on certain characters in terms of the structure of the file.
UTF8 is a way of encoding the characters stored in the file.
Talking about "converting CSV to UTF8" is like talking about "converting blue to loud".  A file format is not a file encoding any more than a colour is a measure of volume.
It sounds as if your real problem is how to determine whether a file is UTF8 encoded or not (and if not, what encoding is involved).  Which has nothing to do with Delphi (unless and until you come across problems with any specific Delphi implementation attempting to achieve this)


text:
Q: How to return data from an infinite loop without breaking it in python? Purpose: I want to read the content of an infinite loop [class A], collect data, and send it off to another class B/function for further processing.
Problem: content in class A can be displayed. However, calling A's content into class B/function display empty list.
There are 2 files: test3.py and test4.py. The call and execution are done from test4.py
It should work, but it does not: Looking for advice, what is wrong? - Thanks.
# Test4.py
import test3
import time
objectTest = test3.test1()
def interface():
   A = objectTest.collectData() #call collectData from tset3
   B = (objectTest.name)        #call Instance attribute from test3
   print(B)                     #for testing purpose
   print(A)                     #for testing purpose
   while True:
       interface()
       time.sleep(1)

# Test3.py
import random
import time

class test1:
    def __init__(self):
        self.name=[]

    def collectData(self):
        temp=[]
        #temp = list(self.name)  # for testing purpose
        enter code heretemp = self.name.copy()
        print(temp)             # for testing purpose
        return temp

    def engine(self):
        while True:
            self.name.append(random.randrange(1,20))
            self.collectData()
            self.name.clear()
            time.sleep(2)

if __name__ == '__main__':
    object1 = test1()
    object1.engine()


text:
Q: TDCH failing while importing to hive table hadoop jar /usr/lib/tdch/1.4/lib/teradata-connector-1.4.4.jar com.teradata.connector.common.tool.ConnectorImportTool \
-url jdbc:teradata://192.168.2.128/DATABASE=db_1 \
-username dbc \
-password dbc \
-jobtype hive \
-fileformat textfile \
-sourcetable employee \
-nummappers 1 \
-targettable td_employee \
-targettableschema "emp_id int,firstname string,lastname string"
Here is the Log. I have added the hive-serde jar in HADOOP_CLASSPATH.
17/04/20 04:26:56 INFO tool.ConnectorImportTool: ConnectorImportTool starts at 1492687616920
17/04/20 04:26:58 INFO common.ConnectorPlugin: load plugins in jar:file:/usr/lib/tdch/1.4/lib/teradata-connector-1.4.4.jar!/teradata.connector.plugins.xml
17/04/20 04:26:59 INFO metastore.HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
17/04/20 04:26:59 INFO metastore.ObjectStore: ObjectStore, initialize called
17/04/20 04:26:59 INFO DataNucleus.Persistence: Property datanucleus.cache.level2 unknown - will be ignored
17/04/20 04:26:59 INFO DataNucleus.Persistence: Property hive.metastore.integral.jdo.pushdown unknown - will be ignored
17/04/20 04:27:03 INFO metastore.ObjectStore: Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
17/04/20 04:27:03 INFO metastore.MetaStoreDirectSql: MySQL check failed, assuming we are not on mysql: Lexical error at line 1, column 5.  Encountered: "@" (64), after : "".
17/04/20 04:27:05 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
17/04/20 04:27:05 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
17/04/20 04:27:05 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
17/04/20 04:27:05 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
17/04/20 04:27:05 INFO DataNucleus.Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
17/04/20 04:27:05 INFO metastore.ObjectStore: Initialized ObjectStore
17/04/20 04:27:06 INFO metastore.HiveMetaStore: Added admin role in metastore
17/04/20 04:27:06 INFO metastore.HiveMetaStore: Added public role in metastore
17/04/20 04:27:06 INFO metastore.HiveMetaStore: No user is added in admin role, since config is empty
17/04/20 04:27:06 INFO metastore.HiveMetaStore: 0: get_table : db=default tbl=td_employee
17/04/20 04:27:06 INFO HiveMetaStore.audit: ugi=root    ip=unknown-ip-addr  cmd=get_table : db=default tbl=td_employee
17/04/20 04:27:06 INFO processor.TeradataInputProcessor: input preprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor starts at:  1492687626978
17/04/20 04:27:08 INFO utils.TeradataUtils: the input database product is Teradata
17/04/20 04:27:08 INFO utils.TeradataUtils: the input database version is 16.0
17/04/20 04:27:08 INFO utils.TeradataUtils: the jdbc driver version is 15.0
17/04/20 04:27:08 INFO processor.TeradataInputProcessor: the teradata connector for hadoop version is: 1.4.4
17/04/20 04:27:08 INFO processor.TeradataInputProcessor: input jdbc properties are jdbc:teradata://192.168.2.128/DATABASE=db_1
17/04/20 04:27:09 INFO processor.TeradataInputProcessor: the number of mappers are 1
17/04/20 04:27:09 INFO processor.TeradataInputProcessor: input preprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor ends at:  1492687629069
17/04/20 04:27:09 INFO processor.TeradataInputProcessor: the total elapsed time of input preprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor is: 2s
17/04/20 04:27:10 INFO Configuration.deprecation: mapred.output.dir is deprecated. Instead, use mapreduce.output.fileoutputformat.outputdir
17/04/20 04:27:10 INFO metastore.HiveMetaStore: No user is added in admin role, since config is empty
17/04/20 04:27:10 INFO metastore.HiveMetaStore: 0: get_table : db=default tbl=td_employee
17/04/20 04:27:10 INFO HiveMetaStore.audit: ugi=root    ip=unknown-ip-addr  cmd=get_table : db=default tbl=td_employee
17/04/20 04:27:10 INFO metastore.HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
17/04/20 04:27:10 INFO metastore.ObjectStore: ObjectStore, initialize called
17/04/20 04:27:10 INFO metastore.MetaStoreDirectSql: MySQL check failed, assuming we are not on mysql: Lexical error at line 1, column 5.  Encountered: "@" (64), after : "".
17/04/20 04:27:10 INFO DataNucleus.Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
17/04/20 04:27:10 INFO metastore.ObjectStore: Initialized ObjectStore
17/04/20 04:27:10 INFO processor.HiveOutputProcessor: hive table default.td_employee does not exist
17/04/20 04:27:10 INFO metastore.HiveMetaStore: 0: Shutting down the object store...
17/04/20 04:27:10 INFO HiveMetaStore.audit: ugi=root    ip=unknown-ip-addr  cmd=Shutting down the object store...
17/04/20 04:27:10 INFO metastore.HiveMetaStore: 0: Metastore shutdown complete.
17/04/20 04:27:10 INFO HiveMetaStore.audit: ugi=root    ip=unknown-ip-addr  cmd=Metastore shutdown complete.
17/04/20 04:27:11 INFO client.RMProxy: Connecting to ResourceManager at sandbox.hortonworks.com/10.0.2.15:8050
17/04/20 04:27:13 INFO client.RMProxy: Connecting to ResourceManager at sandbox.hortonworks.com/10.0.2.15:8050
17/04/20 04:27:13 WARN mapred.ResourceMgrDelegate: getBlacklistedTrackers - Not implemented yet
17/04/20 04:27:13 INFO mapreduce.JobSubmitter: number of splits:1
17/04/20 04:27:14 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1492661647325_0001
17/04/20 04:27:14 INFO impl.YarnClientImpl: Submitted application application_1492661647325_0001
17/04/20 04:27:14 INFO mapreduce.Job: The url to track the job: http://sandbox.hortonworks.com:8088/proxy/application_1492661647325_0001/
17/04/20 04:27:14 INFO mapreduce.Job: Running job: job_1492661647325_0001
17/04/20 04:27:34 INFO mapreduce.Job: Job job_1492661647325_0001 running in uber mode : false
17/04/20 04:27:34 INFO mapreduce.Job:  map 0% reduce 0%
17/04/20 04:27:49 INFO mapreduce.Job: Task Id : attempt_1492661647325_0001_m_000000_0, Status : FAILED
Error: java.lang.ClassNotFoundException: org.apache.hadoop.hive.serde2.SerDeException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at com.teradata.connector.common.ConnectorOutputFormat$ConnectorFileRecordWriter.<init>(ConnectorOutputFormat.java:91)
    at com.teradata.connector.common.ConnectorOutputFormat.getRecordWriter(ConnectorOutputFormat.java:38)
    at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.<init>(MapTask.java:624)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:744)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:167)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)

17/04/20 04:28:00 INFO mapreduce.Job: Task Id : attempt_1492661647325_0001_m_000000_1, Status : FAILED
Error: org.apache.hadoop.fs.FileAlreadyExistsException: /user/root/temp_042710/part-m-00000 for client 10.0.2.15 already exists
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:2309)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInt(FSNamesystem.java:2237)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFile(FSNamesystem.java:2190)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.create(NameNodeRpcServer.java:520)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.create(ClientNamenodeProtocolServerSideTranslatorPB.java:354)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:585)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:928)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2013)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2009)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2007)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106)
    at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:73)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1604)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1465)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1390)
    at org.apache.hadoop.hdfs.DistributedFileSystem$6.doCall(DistributedFileSystem.java:394)
    at org.apache.hadoop.hdfs.DistributedFileSystem$6.doCall(DistributedFileSystem.java:390)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:390)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:334)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:906)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:887)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:784)
    at org.apache.hadoop.mapreduce.lib.output.TextOutputFormat.getRecordWriter(TextOutputFormat.java:132)
    at com.teradata.connector.hive.HiveTextFileOutputFormat.getRecordWriter(HiveTextFileOutputFormat.java:22)
    at com.teradata.connector.common.ConnectorOutputFormat$ConnectorFileRecordWriter.<init>(ConnectorOutputFormat.java:89)
    at com.teradata.connector.common.ConnectorOutputFormat.getRecordWriter(ConnectorOutputFormat.java:38)
    at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.<init>(MapTask.java:624)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:744)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:167)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.fs.FileAlreadyExistsException): /user/root/temp_042710/part-m-00000 for client 10.0.2.15 already exists
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:2309)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInt(FSNamesystem.java:2237)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFile(FSNamesystem.java:2190)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.create(NameNodeRpcServer.java:520)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.create(ClientNamenodeProtocolServerSideTranslatorPB.java:354)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:585)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:928)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2013)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2009)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2007)

    at org.apache.hadoop.ipc.Client.call(Client.java:1410)
    at org.apache.hadoop.ipc.Client.call(Client.java:1363)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:206)
    at com.sun.proxy.$Proxy15.create(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:190)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:103)
    at com.sun.proxy.$Proxy15.create(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.create(ClientNamenodeProtocolTranslatorPB.java:258)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1600)
    ... 22 more

17/04/20 04:28:05 INFO mapreduce.Job: Task Id : attempt_1492661647325_0001_m_000000_2, Status : FAILED
Error: org.apache.hadoop.fs.FileAlreadyExistsException: /user/root/temp_042710/part-m-00000 for client 10.0.2.15 already exists
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:2309)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInt(FSNamesystem.java:2237)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFile(FSNamesystem.java:2190)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.create(NameNodeRpcServer.java:520)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.create(ClientNamenodeProtocolServerSideTranslatorPB.java:354)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:585)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:928)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2013)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2009)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2007)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106)
    at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:73)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1604)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1465)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1390)
    at org.apache.hadoop.hdfs.DistributedFileSystem$6.doCall(DistributedFileSystem.java:394)
    at org.apache.hadoop.hdfs.DistributedFileSystem$6.doCall(DistributedFileSystem.java:390)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:390)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:334)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:906)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:887)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:784)
    at org.apache.hadoop.mapreduce.lib.output.TextOutputFormat.getRecordWriter(TextOutputFormat.java:132)
    at com.teradata.connector.hive.HiveTextFileOutputFormat.getRecordWriter(HiveTextFileOutputFormat.java:22)
    at com.teradata.connector.common.ConnectorOutputFormat$ConnectorFileRecordWriter.<init>(ConnectorOutputFormat.java:89)
    at com.teradata.connector.common.ConnectorOutputFormat.getRecordWriter(ConnectorOutputFormat.java:38)
    at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.<init>(MapTask.java:624)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:744)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:167)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.fs.FileAlreadyExistsException): /user/root/temp_042710/part-m-00000 for client 10.0.2.15 already exists
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:2309)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInt(FSNamesystem.java:2237)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFile(FSNamesystem.java:2190)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.create(NameNodeRpcServer.java:520)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.create(ClientNamenodeProtocolServerSideTranslatorPB.java:354)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:585)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:928)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2013)
    at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2009)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1557)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2007)

    at org.apache.hadoop.ipc.Client.call(Client.java:1410)
    at org.apache.hadoop.ipc.Client.call(Client.java:1363)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:206)
    at com.sun.proxy.$Proxy15.create(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:190)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:103)
    at com.sun.proxy.$Proxy15.create(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.create(ClientNamenodeProtocolTranslatorPB.java:258)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1600)
    ... 22 more

17/04/20 04:28:13 INFO mapreduce.Job:  map 100% reduce 0%
17/04/20 04:28:14 INFO mapreduce.Job: Job job_1492661647325_0001 failed with state FAILED due to: Task failed task_1492661647325_0001_m_000000
Job failed as tasks failed. failedMaps:1 failedReduces:0

17/04/20 04:28:14 INFO mapreduce.Job: Counters: 12
    Job Counters
        Failed map tasks=4
        Launched map tasks=4
        Other local map tasks=3
        Data-local map tasks=1
        Total time spent by all maps in occupied slots (ms)=30868
        Total time spent by all reduces in occupied slots (ms)=0
        Total time spent by all map tasks (ms)=30868
        Total vcore-seconds taken by all map tasks=30868
        Total megabyte-seconds taken by all map tasks=7717000
    Map-Reduce Framework
        CPU time spent (ms)=0
        Physical memory (bytes) snapshot=0
        Virtual memory (bytes) snapshot=0
17/04/20 04:28:14 WARN tool.ConnectorJobRunner: com.teradata.connector.common.exception.ConnectorException: The output post processor returns 1
17/04/20 04:28:14 INFO processor.TeradataInputProcessor: input postprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor starts at:  1492687694783
17/04/20 04:28:15 INFO processor.TeradataInputProcessor: input postprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor ends at:  1492687694783
17/04/20 04:28:15 INFO processor.TeradataInputProcessor: the total elapsed time of input postprocessor com.teradata.connector.teradata.processor.TeradataSplitByHashProcessor is: 0s
17/04/20 04:28:15 INFO tool.ConnectorImportTool: ConnectorImportTool ends at 1492687695150
17/04/20 04:28:15 INFO tool.ConnectorImportTool: ConnectorImportTool time is 78s
17/04/20 04:28:15 INFO tool.ConnectorImportTool: job completed with exit code 1

A: TDCH import will fail if you are using lower versions of sqoop. Check the version compatibility.


text:
Q: Jmeter - How to execute two scripts together I have two scenarios which need to be executed together:
Scenario 1: Launch ---> Login..........---> Logout. Basically it creates something. There is a unique id received.

Scenario 2: Launch ---> Login..........---> Logout. This updates the unique id received from the previous scenario.

Scenario 1 needs to be run with 70 users and 2 with another 70 users. Totally 140 users for one hour.
Scenario 2 has a dependency on 1. The unique id generated from 1 needs to be passed into 2.
How do I proceed with this execution? Thanks in Advance.
Regards,
Ajith

A: Normally you should be using different Thread Groups for simulating different groups of business users so you need to configure the Thread Groups like:

In order to run both Thread Groups at the same time make sure that Run Thread Groups consecutively is not checked at Test Plan level
For passing the unique ID from the 1st Thread Group to 2nd Thread Group there are 2 approaches:

*

*Use __setProperty() function (maybe in combination with __threadNum() function if each user need to have its own ID) to store the unique ID into a JMeter Property in the 1st Thread Group. The property can be read via __P() function in the 2nd Thread Group

*Use Inter-Thread Communication Plugin


text:
Q: Updating array item by index using Object.assign equivalent in spread syntax I have stumbled upon this gem recently while trying to update an index of an array;
What I tried is:
const a = [1,2,3];
Object.assign([...a], {1: 10}) );
// [1, 10, 3]

This allows me to programmatically update the a specific arrays items value, while not updating the original in one line.
However when I try to convert this to spread syntax:
[...a, ...{1: 10}]

It's not actually working, giving me an error:

Uncaught TypeError: {(intermediate value)} is not iterable

Would I be correct in assuming that the object assign adds an iterable prototype to the object making the first option work, while the spread synatax is more generic and doest not include this feature?
Thanks

A: The spread syntax expects an iterable object

Spread syntax allows an iterable such as an array expression or string
  to be expanded in places where zero or more arguments (for function
  calls) or elements (for array literals) are expected, or an object
  expression to be expanded in places where zero or more key-value pairs
  (for object literals) are expected.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The Object.assign() method expects an Object - it doesn't have to be iterable.

The Object.assign() method is used to copy the values of all
  enumerable own properties from one or more source objects to a target
  object. It will return the target object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Iterables: https://javascript.info/iterable
So it seems it's quite the contrary to what you suggested: the spread syntax is less general than the Object.assign() method, as it requires a stricter type of items to work correctly.

A: You cannot spread objects like that. Refer to this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


text:
Q: Do I need an online database if I am hosting docker webservice on AWS instance? I would like to deploy my web service on AWS EC2 instance. My plan is to install docker on AWS EC2.
My plan is to create an image of my web service and transfer the docker container to my AWS instance which will be able to host the web service since I have docker on my AWS instance.
My question:
If my web service is pulling data from my local DB. Does that mean that I have to create an AWS RDS to store all my data since my web service is running on EC2.
How does it work? Can anyone direct me to any guide that is available?

A: It is possible to pull from local machine you don't need to create a RDS database. Use Virtual Private Gateway to connect the VPC to your on-site systems over a secure VPN. You can also use direct connect in AWS


text:
Q: Can I debug (set breakpoints) in TypeScript files in a VS 2012 Windows Store app? I have a Visual Studio 2012 Windows Store (Win 8) app that I have setup to use TypeScript files to generate the JavaScript.  When I try to set a breakpoint in the TypeScript files, Visual Studio gives me this message:

This breakpoint will not currently be hit.  No symbols have been
  loaded for this document.

Is it possible to set breakpoints in *.ts files in a Windows Store project in VS 2012?
If so, how does the project have to be configured to do so?


text:
Q: I am stuck with my pokemon trading app practice in python i started learning python in the last month and i am stuck with how to continue working on an idea i read about.
this will be only a simple training practice for me and also the first program i will do as OOP.
i entered to reddit app ideas to find some project to try to work on and one of these asked for a pokedex that allows you to check if someone has a pokemon that you need.
i was able to scrape the first gen 151 pokemon, create a player class and give each one 20 random pokemon.
now i want to give every player the option to check if player 2 has a pokemon that player 1 doesn't have and the reverse in order to see if they can do some trading but i am not sure how to do this.
can someone please help me? :)
thanks in advance!
here is my code so far, i would also love to hear tips about ho i can make the current code better! :
import requests
from bs4 import BeautifulSoup
import random

url = 'https://pokemondb.net/pokedex/national#gen-1'
req = requests.get(url)
page = req.text
Soup = BeautifulSoup(page,'html.parser')

gen1_poke_names = [pokemon.get_text() for pokemon in Soup.find_all('',{'class':'ent-name'})[:151]]

class PokeScrape:
    def __init__(self):
        pass

class Player(PokeScrape):
    def __init__(self,name,poke_list):
        self.name = name
        self.poke_list = poke_list

Michael = Player('Michael',random.sample(gen1_poke_names,20))
print(Michael.name)
print(Michael.poke_list)

Daniel = Player('Daniel',random.sample(gen1_poke_names,20))
print(Daniel.name)
print(Daniel.poke_list)

A: This is easier to do using sets than lists, since it is straightforward to "subtract" one set from another. Suppose we have:
Michael.poke_list = ['Bulbasaur', 'Squirtle', 'Pikachu']
Daniel.poke_list = ['Pikachu', 'Charmander']

Then:
>>> michael_set = set(Michael.poke_list)
>>> daniel_set = set(Daniel.poke_list)
>>> michael_set - daniel_set
{'Bulbasaur', 'Squirtle'}
>>> daniel_set - michael_set
{'Charmander'}

So the set differences tell you which Pokémon each player has that the other doesn't.

A: to check and return pokemon he has and you don't: (in Player class ofc)
def checkpoke(self, other_player):
    other_pokelist = other_player.pokelist
    result=[poke for poke in other_player.pokelist if poke not in self.pokelist]
    print("he has: {} but you don't".format(result))


text:
Q: ActiveMQ failover transport - Why so many connections? We have 4 ActiveMQ brokers (each running on a separate server) setup in a network of brokers. There about 60 producers. The producers lookup the ActiveMQ connection factory from Glassfish using JDNI.
The ActiveMQ URI configured in Glassfish is as follows:
failover:(tcp://phxgapm01:61616,tcp://phxgapm02:61616,tcp://phxgapm03:61616,tcp://phxgapm04:61616)?randomize=true&backup=false&maxReconnectAttempts=8

Each producer process does a JNDI lookup of the javax.jms.ConnectionFactory and then creates 1 javax.jms.Connection. As the producer runs it will periodically create a javax.jms.Session and javax.jms.MessageProducer, send some messages to a queue and then close the Session and MessageProducer.
That is all background - now to my question. From some, but not all of the producers, we'll see a stream of log output like the following:
2014-12-30 21:07:06,534 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm03:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,538 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm04:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,544 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm02:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,548 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm04:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,552 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm01:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,556 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm02:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,561 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm02:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,565 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm01:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,568 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm02:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,572 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm04:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,577 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm03:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,581 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm04:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,586 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm01:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,590 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm03:61616 - [ActiveMQ Task-1]
2014-12-30 21:07:06,594 INFO  FailoverTransport    - Successfully connected to tcp://phxgapm04:61616 - [ActiveMQ Task-1]

For some of the producers we'll see this output every 10 minutes - for others it is less frequent. Even more confusing is that all of these producers use identical code for the JMS messaging - so while producers may vary in the how frequently they create sessions and messageproducers, they all use the same code and all create just 1 connection object.
From reading the documentation, my understanding is that the failover transport would open a connection to 1 of the brokers (selecting randomly in our case).  Why do we see this stream of connections (multiple connections to each of the brokers within 60ms)? Using netstat we can see these connections. Is this normal? If not, any suggestions as to what might be causing this?

A: Without having the activeMQ loglevels raised there is some room to speculation, but:

*

*"for others it is less frequent" - Observing different behaviour on different instances in this case is completely natural. If the load is not perfectly distributed between instances, they will behave differently when it comes to messaging. Just imagine one of your nodes picking up 90% of the triggering inputs and doing most of the work alone. That node would be under much higher load and would use its JMS resources totally differently from the rest of the nodes.

*"my understanding is that the failover transport would open a connection to 1 of the brokers" - That is completely true. Failover will come in play only if the the wrapping connectionFactory requests a new physical connection to be opened. In this case there will be exactly one connection created for that request.

*"Why do we see this stream of connections" - I am pretty sure that this is due to having a pooling implementation in your project. You can see that there are those connections established to all of your brokers (randomly distributed), indicating multiple requests for new connections at the same time.

By increasing the loglevel in your application you would be able to see exactly which layer initiates this and for what reason. Possible reasons are: "all connections were expired and the pool restores the minIdleConnection count to the minimum"; "some incoming request in your application requires lots of messages to be sent at once, so your pool creates them".


text:
Q: PayPal Curl Error I have the following Code which on a successful payment gives me error.

<?php
    $name = "pra_api1.mymail.sutd.edu.sg";
    $password = "EJLV5PRE9Q3";
    $signature = "AFcWxVRCpSSRl31NmODmpouHa5SPBWS1";
    $endpoint = 'https://api-3t.sandbox.paypal.com/nvp';
    session_start();

    $amtDonate = $_SESSION['try'];
    $curren = $_SESSION['cure'];
 $params2 = array(
        'METHOD'=> 'DoExpressCheckoutPayment',
            'VERSION'=> '74.0',
            'TOKEN' => $_GET['token'],
            'PAYMENTACTION' => 'Sale',
            'USER'=> $name,
            'SIGNATURE'=> $signature,
            'PWD'=> $password,
            'PAYERID' => $_GET['PayerID'],
            'PAYMENTREQUEST_0_AMT'=> $amtDonate,
            'PAYMENTREQUEST_0_CURRENCYCODE' =>$curren
    );
    $params2 = http_build_query($params2);
    $curl2 = curl_init();
    curl_setopt_array($curl2, array(
        CURLOPT_URL => $endpoint,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $params2,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_VERBOSE => 1));
    $response2 = curl_exec($curl2);
    $responseArray2 = array();
    parse_str($response2,$responseArray2);
    //var_dump($responseArray2);
    curl_close($curl2);

    if (curl_errno($curl2)){
    //  var_dump(curl_error($curl2));
        curl_close($curl2);
        die();
    } else {
        if ($responseArray2['ACK']=="Success"){
        } else {
            var_dump($responseArray2);
            die();

        }
                    curl_close($curl2);

    }

        $params = array(
        'METHOD'=> 'GetExpressCheckoutDetails',
            'VERSION'=> '74.0',
            'TOKEN' => $_GET['token'],
            'USER'=> $name,
            'SIGNATURE'=> $signature,
            'PWD'=> $password);
    $params = http_build_query($params);
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $endpoint,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_VERBOSE => 1));
    $response = curl_exec($curl);
    $responseArray = array();
    parse_str($response,$responseArray);
    //var_dump($responseArray);
    curl_close($curl);

    if (curl_errno($curl)){
    //  var_dump(curl_error($curl));
        curl_close($curl);
        die();
    } else {
        if ($responseArray['CHECKOUTSTATUS']=='PaymentActionCompleted'){
            header( "refresh:3;url=index.php" );

        } else {
            var_dump($responseArray);
            die();

        }
                    curl_close($curl);

    }
?>

<meta charset="UTF-8" />
<title>We Empower Her</title>

 Your transaction has been completed. Thank you for your generous contribution.

A: It looks like your code is a bit over the place. I would suggest to clean up the redundant curl_close calls
Warning#1 = You already closed the $curl2 handle on line 36
Warning#2 = $curl2 Handle already closed
Warning#3 = $curl handle already closed
Warning#4 = Looks like you're too late to set a header at this stage. As line#38 caused an error message, you might be fine as soon as you've fixed the warnings or as soon as you disable PHP warning messages in your php.ini file
Warning#5 = Yet another curl_close() for an already closed handle.


text:
Q: Loop into the results after a preg_match_all in PHP {Hello} {my} {name} {is} {Bob}

How can I loop in all the world in between the { and } ?.
$matches = array();
$t = preg_match_all('/{(.*?)\}/s', '{Hello} {my} {name} {is} {Bob}', $matches);
foreach ($matches as $match) {
    // Should display Hello, my, name, is, Bob
}

A: The captured groups from preg_match_all() appear in an array $matches[1].
To get the result you want you can just implode() that array...
<?php

$matches = array();
$t = preg_match_all('/{(.*?)\}/s', '{Hello} {my} {name} {is} {Bob}', $matches);
echo implode(',',$matches[1]);   //Hello,my,name,is,Bob

See: https://3v4l.org/TINmH
If you want to loop over the results use
    foreach($matches[1] as $match) {
        // do stuff
    }


text:
Q: VBA function issues I'm working on a project where I need to analyse availability of staff based on 15-minute time periods, their language skills and their shifts. I have one sheet that looks like this:
--Time-------English------German-----French

--06:15--------0------------0-----------0
--06:30--------0------------0-----------0
--06:45--------0------------0-----------0

And another one that looks like this:
--Name-----Language-----Info--------Shift--------

--Joe B----English-----BlaBla---05:45 - 12:30---
--Al C-----English-----BlaBla---07:45 - 15:30---
--Jill T---English-----BlaBla---07:45 - 15:30---

So, I need to take the Language they speak, their shift (split into start and end times) and based on the language specified in the heading of that column (in the first sheet given above) add '1' if they speak that language and are available at that time.
Below is the code I have at present which is not doing this for me:
Function CalculateAvailability(The_Time As String, The_Info As Range, Current_Lang As String)

'The_Time is the current 15-minute period
'The_Info is the range of fields in sheet 2 with our information (A3:D5 above)
'Current_Lang is the current language heading

Dim The_Lang As String 'the language of the staff member
Dim The_Shift_Start As String 'obvious
Dim The_Shift_End As String 'also obvious
Dim stGotIt As String 'redundant, not used currently
Dim stCell As String 'for capturing the cell contents
Dim Counter As Integer 'our counter

Counter = 0

For Each r In The_Info.Rows
    For Each c In r.Cells
        stCell = c.Value
        If InStr(1, stCell, ":", vbTextCompare) > 0 Then
            The_Shift_Start = GetShiftStart(stCell) 'this code works
            The_Shift_End = GetShiftEnd(stCell) 'this code works
        End If
        If InStr(1, stCell, Current_Lang, vbTextCompare) > 0 Then
            The_Lang = Current_Lang 'seems redundant but how else to do the check?
            Counter = 17 'test value - doesn't seem to reach here
        End If
    Next c
    If The_Lang = Current_Lang Then
        Counter = 5 'test value - doesn't seem to reach here either
    End If
Next r

CalculateAvailability = "Time:" + The_Time + " - Start:" + The_Shift_Start + " - End:" + The_Shift_End + " - Avail. " + Counter 'for output purposes

End Function

It doesn't seem to be reaching the important parts of my code where I would do the calculation that calls a seperate (tested and working) function that returns '1' or '0' based on the time period and the shift start and end times. (That would be where I specify Counter = 5) Is my logic in the code above incorrect? I realise that the testing of the language seems redundant and is probably incorrect, but as the commenting says, I couldn't rework that more sensibly. One thing I'm curious about is does the For Loop immediately jump from the "Next" back to the related "For Each" or does it carry out the following code and THEN jump back up? (I know this wouldn't make much sense programmatically, but I'm not that familiar with VB so I can't say for sure, despite how ridiculous it seems in light of my C/C#/C++ knowledge)
All help greatly appreciated!

A: Assuming that Current_Lang is not sent in as an empty string and the code never reaches the line Counter = 17, it will never reach the line Counter = 5 either, so I think you can concentrate on why it doesn't reach Counter = 17.
The most likely answer to that would seem to be that stCell does not contain what you expect it to contain and so this is the reason why it can't find Current_Lang in there. Try to output or Watch what's in stCell so you can check why it's not working.


text:
Q: How do I create a download pdf button on an HTML form that fills in automatically? I would like to make a button on the bottom of my summary form that downloads a pdf with all of the inputs and outputs.
The biggest problem is, I'm working in webStorm (which doesn't support php) and I'm somewhat of a noob in web development. Should I download phpStorm and do it there (if so, please give me some suggestions on how to do it), or does anyone have any suggestions just using HTML and JS?
Here is my code currently:

    <title>Calculator</title>
    <link rel="stylesheet" href="styler.css">

Calculator

    <select id="form-selector">
        <option value="_" selected disabled>Pick One</option>
        <option value="Input">Input</option>
        <option value="Output">Output</option>
        <option value="Summary">Summary</option>
    </select>

    <form name = "Input">

Input

    Cost of Candy ($):

            <input type="number" name="costOfCandy" placeholder="5.00" min="0.01" max="20.00">

        <input type="button" value="Calculate" onclick="performCalculations()">

    </form>

    <form name = "Output">

Output

        Baseline Annual Cost of Candy ($):

            <input type="text" name="BCostCandy">

    </form>

    <form name = "Summary">

Summary

        Impact on Annual Candy Cost ($):

            <input type="text" name="NCandyCost">

    </form>

This will ensure that you have some utility in place to get your work done,
the next step is to write out some lines using the jsPDF library.
For example, in your case, if you want the whole body to be a pdf, then,

This piece of code added after the above 2 lines should do the magic.
Consult this article for further information:

A: You can simply use print.js library. You can give any area of your web page. If you don't want to export pdf with your current template, you can create appropriate document template and hide it from users and print that one. You can get this library from here or from their site.
You can understand it very easily by going through their explanation.