text:
Q: Symfony2 - Association refers to the owning side which does not exist I'm trying to do mapping associations in symfony2 but I'm having some problems. Here's my code:
OSC\UserBundle\Resources\doctrine\Child.orm.yml
OSC\UserBundle\Entity\Child:
    type: entity
    table: null
    repositoryClass: OSC\UserBundle\Entity\ChildRepository
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        firstName:
            type: string
            length: 255
        lastName:
            type: string
            length: 255
        dateOfBirth:
            type: datetime
            column: dateOfBirth
        isPlayer:
            type: boolean
            default: false
        isCoach:
            type: boolean
            default: false

    ManyToOne:
        parent:
            targetEntity: User
            inversedBy: children

    lifecycleCallbacks: {  }

OSC\UserBundle\Entity\Child.php
<?php

namespace OSC\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Child
 */
class Child
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $firstName;

    /**
     * @var string
     */
    private $lastName;

    /**
     * @var \DateTime
     */
    private $dateOfBirth;

     protected $isPlayer;

     protected $isCoach;

     protected $player;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return Child
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return Child
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set dateOfBirth
     *
     * @param \DateTime $dateOfBirth
     * @return Child
     */
    public function setDateOfBirth($dateOfBirth)
    {
        $this->dateOfBirth = $dateOfBirth;

        return $this;
    }

    /**
     * Get dateOfBirth
     *
     * @return \DateTime
     */
    public function getDateOfBirth()
    {
        return $this->dateOfBirth;
    }

    /**
     * Set isPlayer
     *
     * @param boolean $isPlayer
     * @return Child
     */
    public function setIsPlayer($isPlayer)
    {
        $this->isPlayer = $isPlayer;

        return $this;
    }

    /**
     * Get isPlayer
     *
     * @return boolean
     */
    public function getIsPlayer()
    {
        return $this->isPlayer;
    }

    /**
     * Set isCoach
     *
     * @param boolean $isCoach
     * @return Child
     */
    public function setIsCoach($isCoach)
    {
        $this->isCoach = $isCoach;

        return $this;
    }

    /**
     * Get isCoach
     *
     * @return boolean
     */
    public function getIsCoach()
    {
        return $this->isCoach;
    }

}

OSC\UserBundle\Entity\User.orm.yml
OSC\UserBundle\Entity\User:
    type: entity
    table: null
    repositoryClass: OSC\UserBundle\Entity\UserRepository
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
        lastName:
            type: string
            length: 255

        firstName:
            type: string
            length: 255

        streetNumber:
            type: string
            length: 255

        street:
            type: string
            length: 255

        province:
            type: string
            length: 255

        country:
            type: string
            length: 255

        homePhone:
            type: string
            length: 255

        mobilePhone:
            type: string
            length: 255
        isPlayer:
            type: boolean
            default: false
        isCoach:
            type: boolean
            default: false

        dateOfBirth:
            type: date
            column: dateOfBirth

    oneToMany:
        children:
            targetEntity: Child
            mappedBy: parent

    lifecycleCallbacks: {  }

/
<?php

namespace OSC\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

class User extends BaseUser
{

    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic

    }

   /**
     *
     * @Assert\NotBlank(message="Please enter your last name.", groups={"Registration", "Profile"})
     * @Assert\MinLength(limit="3", message="The name is too short.", groups={"Registration", "Profile"})
     * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
     */
     protected $lastName;

   /**
     * @Assert\NotBlank(message="Please enter your first name.", groups={"Registration", "Profile"})
     * @Assert\MinLength(limit="3", message="The name is too short.", groups={"Registration", "Profile"})
     * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
     */
     protected $firstName;

     protected $streetNumber;

     protected $street;

     protected $province;

     protected $country;

     protected $postalCode;

     protected $homePhone;

     protected $mobilePhone;

     protected $dateOfBirth;

     protected $children;

     protected $isPlayer;

     protected $isCoach;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set streetNumber
     *
     * @param string $streetNumber
     * @return User
     */
    public function setStreetNumber($streetNumber)
    {
        $this->streetNumber = $streetNumber;

        return $this;
    }

    /**
     * Get streetNumber
     *
     * @return string
     */
    public function getStreetNumber()
    {
        return $this->streetNumber;
    }

    /**
     * Set street
     *
     * @param string $street
     * @return User
     */
    public function setStreet($street)
    {
        $this->street = $street;

        return $this;
    }

    /**
     * Get street
     *
     * @return string
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * Set province
     *
     * @param string $province
     * @return User
     */
    public function setProvince($province)
    {
        $this->province = $province;

        return $this;
    }

    /**
     * Get province
     *
     * @return string
     */
    public function getProvince()
    {
        return $this->province;
    }

    /**
     * Set country
     *
     * @param string $country
     * @return User
     */
    public function setCountry($country)
    {
        $this->country = $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set homePhone
     *
     * @param string $homePhone
     * @return User
     */
    public function setHomePhone($homePhone)
    {
        $this->homePhone = $homePhone;

        return $this;
    }

    /**
     * Get homePhone
     *
     * @return string
     */
    public function getHomePhone()
    {
        return $this->homePhone;
    }

    /**
     * Set mobilePhone
     *
     * @param string $mobilePhone
     * @return User
     */
    public function setMobilePhone($mobilePhone)
    {
        $this->mobilePhone = $mobilePhone;

        return $this;
    }

    /**
     * Get mobilePhone
     *
     * @return string
     */
    public function getMobilePhone()
    {
        return $this->mobilePhone;
    }

    /**
     * Add children
     *
     * @param \OSC\UserBundle\Entity\Children $children
     * @return User
     */
    public function addChild(\OSC\UserBundle\Entity\Children $children)
    {
        $this->children[] = $children;

        return $this;
    }

    /**
     * Remove children
     *
     * @param \OSC\UserBundle\Entity\Children $children
     */
    public function removeChild(\OSC\UserBundle\Entity\Children $children)
    {
        $this->children->removeElement($children);
    }

    /**
     * Get children
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Set isPlayer
     *
     * @param boolean $isPlayer
     * @return User
     */
    public function setIsPlayer($isPlayer)
    {
        $this->isPlayer = $isPlayer;

        return $this;
    }

    /**
     * Get isPlayer
     *
     * @return boolean
     */
    public function getIsPlayer()
    {
        return $this->isPlayer;
    }

    /**
     * Set isCoach
     *
     * @param boolean $isCoach
     * @return User
     */
    public function setIsCoach($isCoach)
    {
        $this->isCoach = $isCoach;

        return $this;
    }

    /**
     * Get isCoach
     *
     * @return boolean
     */
    public function getIsCoach()
    {
        return $this->isCoach;
    }

    /**
     * Set dateOfBirth
     *
     * @param \DateTime $dateOfBirth
     * @return User
     */
    public function setDateOfBirth($dateOfBirth)
    {
        $this->dateOfBirth = $dateOfBirth;

        return $this;
    }

    /**
     * Get dateOfBirth
     *
     * @return \DateTime
     */
    public function getDateOfBirth()
    {
        return $this->dateOfBirth;
    }
}

My question is the following
When I run the command: doctrine:schema:validate
why am I getting the following error:
[Mapping]  FAIL - The entity-class 'OSC\UserBundle\Entity\User' mapping is invalid:
* The association OSC\UserBundle\Entity\User#children refers to the owning side field OSC\UserBundle\Entity\Child#parent which does not exist.
I'm feeling this is linked to parent not being defined in Child. However, when I run doctrine:generate:entities OSC parent is not added....

A: Oh my god, it was so simple, you have to write manyToOne, not ManyToOne...


text:
Q: Use Ansible to copy files to Windows NFS Overview:
I have an Ansible node that has a number of files on it. I would like to copy those files over to a remote Network File Share (NFS). I'm trying to limit the number of Windows computers we WinRM into, and so would prefer (if possible) not to need to WinRM to a Windows machine in order to copy the file. Ideally, I would like to be able to copy the file directly from the RHEL Ansible node to the Windows NFS. I say "Windows NFS" but really it is a NAS protected using Active Directory authentication.
Questions:

*

*Is it possible to use Ansible to copy from a Linux machine to an NFS (i.e. Windows, Nas, etc.)?

*Does it matter that the NFS is protected with Active Directory? Must I use some other credentials, or can I use an AD-based username/password?

A: The best way to tackle this would be to mount the Windows Share to the Ansible node. For our use case, a permanent mount would be best. But, you could also use Ansible to temporarily mount the share.
More details can be found here...
How do you provide domain credentials to ansible's mount module?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looking for something like onlive desktop with Visual Studio for Mac I'm trying to see if there is an online application that would allow me to 'rent' a PC remotely. In much the same way as you could remote connect to a server within Windows (via Remote Connection), I'd like to be able to remote into a PC that is off-site, where the data stays secure, and where I could install new applications.
Yes, this is pretty much asking if there is something that already exists that would be a remote connection to a Windows PC. I'm on a Mac and am a developer, but Bootcamp means I have to keep switching machines, and the VM's/Parallels are just not fast enough. I don't want to be running two machines for the different OS's if I can.
Any advice or pointers in the right direction would be greatly appreciated.
Thanks!

A: I'd use Amazon Web Services EC2. It's a cloud service where you can spin up instances of whatever OS you need. I often use a Windows Server VM on AWS so I can do Windows stuff on my Mac when I'm on the road. I believe micro Windows instances are now available under AWS's free tier (double-check me though) so you could try it out with no risk. Even if you do have to pay, it's like 10 bucks/month to run a Windows server nonstop with moderate bandwidth usage.


text:
Q: subtracting values group wise on a tibble I have a simple tibble and want to calculate the absolute difference of values after grouping them:
tibb <- tibble(id = c("A", "B", "C","A", "B", "C"), value = c(5,4,3,7,8,9))

# A tibble: 6 x 2
  id    value
  <chr> <dbl>
1 A         5
2 B         4
3 C         3
4 A         7
5 B         8
6 C         9

tibb %>% group_by(id) %>% summarize(diff = function(x,y){abs(x-y)})

dplyr return an error stating diff is not supported.
The output should looks like this:
# A tibble: 3 x 2
  id      sum
  <chr> <int>
1 A         2
2 B         4
3 C         6

Error in summarise_impl(.data, dots) :
  Column `diff` is of unsupported type function

Is there any way to calculate this?

A: If there are 2 values in each group then try this:
tibb <- tibble(id = c("A", "B", "C","A", "B", "C"), value = c(5,4,3,7,8,9))
tibb

tibb %>% group_by(id) %>% summarize(diff = abs(diff(value)))
#or
tibb %>% group_by(id) %>% summarize(diff = abs(value[1] - value[2]))


text:
Q: Highlight selected link on the same page I'am searching for highlight selected link on the same page using css or javascript or jquery, found many solutions but they are not working according to my requirement.
follwoing are requirement.
Highlight the selected link or change its color etc.
First
Second
Third

most of the people say to use
a:active{
 background-color:Red;
}
or
a:visited{
 background:color:Red;
}

i know ative link is that which is currently active and visited link is that which you already visited.
but they are not working in my case, i am loading the content of same page on click of these links.
any idea how i can do this
Thanks in advance

A: You can do this with inline Javascript, like this:
Link

You can also trigger a function on the link's click event all with jQuery:
$("a").click(function(){
    $(this).addClass("active");
    // define the styles for the active class for this to work
});

A: This is not valid code:
a:active{
background-color:Red;
}
or
a:visited{
background:color:Red;
}

In addition, they both are trying to set the same color (although the visited link is coded wrong.)
Proper code would be:
a:visited, a:active{
background-color: red;
}

This will change any links which have been clicked to have a red background, as well as apply a red background to any link when it is in the processes of being clicked.


text:
Q: DrawerNavigation dynamic initial route I want to dynamically render initial route based on a a key from Async Storage. There are a lot of ways to do that but in my case I cannot find anything working. Here is my navigator file.
import {
  createDrawerNavigator,
  DrawerNavigatorItems,
} from 'react-navigation-drawer';

const WINDOW_WIDTH = Dimensions.get('window').width;

const getRoute = ()=>{
  return "SignUpScreen";
}

const DrawerNavigator = createDrawerNavigator(
  {
    Home: {
      path: '/home',
      screen: Home,
    },
    SignUpScreen:{
        path: '/signup',
        screen: SignUpScreen
    },
    OtpScreen: {
      path: '/otpscreen',
      screen: OtpScreen
    }
  },
  {
    initialRouteName: `${getRoute()}`,
    contentOptions: {
      activeTintColor: `${THEME_VARIABLES.COLORS.PRIMARY_TEXT}`,
      activeBackgroundColor: 'transparent',
      inactiveTintColor: `${THEME_VARIABLES.COLORS.PRIMARY_TEXT}`,
      inactiveBackgroundColor: 'transparent',
      backgroundColor: `${THEME_VARIABLES.COLORS.PRIMARY_THEME}`,
      labelStyle: {
        fontSize: 15,
        marginLeft: 0,
      },
    },
    drawerWidth: Math.min(WINDOW_WIDTH * 0.6, 300),
    contentComponent: customContentComponent,
  }
);

export default DrawerNavigator;

To use asyncStorage in getRote() I had to do something like
const getRoute = async()=>{
  var initialRouteName = await AsyncStorage.getItem('screen');
  return initialRouteName;
}

But when I use async the function returns an object instead of string like it returns in my first getRoute function(function without async). Its shows following error:


text:
Q: d3.js nodes and trees become seperated during transition I've noticed that all the tree examples I've found on bl.ocks.org have a problem in which the transitions of the nodes and links aren't really linked. In some cases this doesn't matter, but other times (especially when the node count gets higher) it results in an animation in which the nodes and links seperate from each other.
An example can be seen here: http://bl.ocks.org/robschmuecker/7926762
To trigger the behavior you just need to increase the number of rendered nodes by expanding some of them and then click the root node. You should see the links and nodes diverge during the animation and then converge only once both transitions have finished.
Is there a way to prevent this divergence?


text:
Q: How to configure and build Tesseract OCR C++ using Visual Studio 2015 x64 on Windows 10 I am trying to run the VS2015_Tesseract example in Tesseract OCR Library.
I always get the following error when I try to open the file:

Could not find a part of the path

Currently I am working with Visual Studio 2015 on Windows 10 (64 bit).
Please provide the full information on how I can configure the Tesseract OCR C++ library on Visual Studio 2015 Windows 10 (64 bit).
You also can provide any reference tutorial links.

A: *

*You have to download the vs2015_Tesseract or simply run the following git command in working directory:
git clone https://github.com/peirick/VS2015_Tesseract.git

*Run the build_tesseract.bat file.

*Activate tesseract as the startup project.


text:
Q: Full text search on JSON field in MySQL I have some field in my database which are string containing JSON in it.
It looks like this:
2.0.0-p0 :004 > Event.first.title

      Event Load (0.8ms)  SELECT  `events`.* FROM `events`   ORDER BY `events`.`id` ASC LIMIT 1
     => "{'fr' => 'res', 'en' => 'asdg'}"

I wanna do a full text-search on this column, but a simple
Event.where("title LIKE ?", title)

does not result in anything. I have tried by adding the language key, but it doesn't work. I'm not really sure how to perform this request (or if it is even possible).

A: Copying over from comment as answer:
Event.where("title like ?", "%#{title}%")


text:
Q: SMTP Error: The following recipients failed:XXXX So i just received this error when trying to send an mail using PHPmailer from my site.
SMTP Error: The following recipients failed: XXXX
I tried to set $mail->SMTPAuth = true; to false but no result. And i tried to change the password for the mail account and update that in the sendmailfile.php but still the same.
It worked as intended two days ago, now i don't know why this is happening. Since there ain't any error code either i don't really know where to begin and since it did work..
Anyone who might know?
    $mail = new PHPMailer();
    $mail->CharSet = 'UTF-8';
    $mail->ContentType = 'text/html';
    $mail->IsSMTP();
    $mail->Host = "HOST.COM";
    $mail->SMTPAuth = true;
    $mail->Username = "MAIL_TO_SEND_FROM";
    $mail->Password = "PASSWORD";
    $mail->From = "MAIL_TO_SEND_FROM";
    $mail->FromName = "NAME";
    $mail->AddAddress($safeMail);
    $mail->AddReplyTo("no-reply@example.COM", "No-reply");
    $mail->WordWrap = 50;
    $mail->IsHTML(true);
    $sub = "SUBJECT";
    mail->Subject = ($sub);

A: It is a restriction from your SMTP server.
Sending e-mail messages is a vital part of the ever-growing Internet business. Sometimes, a large number of e-mails are required to be sent daily, even hourly. With this comes also the ever-increasing problem with the e-mail spam, and the countless number of junk messages users receive constantly.
The most common restrictions are:
150 e-mails per hour;
1500 e-mails per 24 hours;
50 recipients per message, where each recipient is counted as a separately sent e-mail message (e.g. if you have 50 recipients in a single message, this willcount as 50 sent messages);
One solution is to use a mailing list, then the restriction is 1500 e-mails for 24 hours. There's no restriction for the amount of emails sent per hour, i.e. you can send an email to a mailing list with up to 1500 recipients without a problem.
If you reach the hourly/daily limit you will get this error when trying to send further e-mails:
550 - Stop, you are sending too fast!
You will be able to send e-mails again, once the hour/day has passed.
Things you should know in order to avoid exceeding your limit:
The above e-mail restrictions are valid for the entire hosting account, and not for a single mailbox. This means, that if one of your mailboxes exceeds the allowed limit, you will not be able to send messages from any of your other e-mail accounts.
If, at any point you receive the afore-mentioned error message, it is highly recommended to stop all attempts to send messages from your mailboxes. If you continue trying, your messages will be left in a mail queue, which will have to clear first, before the server timer can reset and allow you to send e-mails again.

A: I've encountered the same problem. Managed too fix it when i commented the next row:
 $mail->isSMTP();

Noticed you already found an answer, however maybe this will fix the problem for other people.
This does prevent using your external SMTP server as RozzA stated in the comments.

A: try inlcuding this
$mail->SMTPDebug  = 1;

A: Just try to set SMTPAuth to false.

A: Maybe your class.phpmailer.php file is corrupt. Download the latest version from :
https://github.com/PHPMailer/PHPMailer
$mail->SMTPDebug  = 1; // enables SMTP debug information (for testing)
                               // 1 = errors and messages
                               // 2 = messages only

A: there is  a  slightly less probable problem.maybe this condition is  caused by  protection placed by your ISP.and you said  it worked well two days ago.maybe that is the problem.try contacting  your ISP.
or maybe its  a  problem with the  recipients/senders email adresses

A: Here is some additional info about SMTP Auth
PLAIN (Uses Base64 encoding.)
LOGIN (Uses Base64 encoding.)
e.t.c - you can watch here http://en.wikipedia.org/wiki/SMTP_Authentication
For me solution was to set SMTPAuth to true for PHPMailer class

A: Please note in your lines i.e....
$mail->Username = "MAIL_TO_SEND_FROM";
   $mail->Password = "PASSWORD";
   $mail->From = "MAIL_TO_SEND_FROM";
Here at Line 1 and 3 you have to use same email address (You can't use different email address), this will work sure, I hope u r using different email address, (Email address must be same as username/password matching).

A: for Skip sending emails to invalid adresses; use try ... catch
$mail=new PHPMailer(true);
try {
$mail->CharSet = 'utf-8';
$mail->isSMTP();
$mail->isHTML(true);
$mail->Host = 'smtp.yourhost.com';
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->Username = 'xxxx';
$mail->Password = 'xxxx';
$mail->SMTPSecure = 'tls';
$mail->SMTPDebug = 0;
$mail->MailerDebug = false;
$mail->setFrom($absender, $name);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $message_other_player;
}

$mail->send();
      // echo 'Message has been sent';
   } catch (Exception $e) {
     //  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
   }

PHPMailer - Skip sending emails to invalid adresses


text:
Q: Getting Out of Memory error when using Image Classification in Sage Maker When using a p2.xlarge or p3.2xlarge with up to 1TB of memory trying to use the predefined SageMaker Image Classification algorithm in a training job I'm getting the following error:
ClientError: Out of Memory. Please use a larger instance and/or reduce the values of other parameters (e.g. batch size, number of layers etc.) if applicable
I'm using 450+ images, I've tried resizing them from their original 2000x3000px size to a 244x244px size down to a 24x24px size and keep getting the same error.
I've tried adjusting my hyper parameters: num_classes, num_layers, num_training_samples, optimizer, image_shape, checkpoint frequency, batch_size and epochs. Also tried using pretrained model. But the same error keeps occurring.

A: Would've added this as a comment but I don't have enough rep yet.
A few clarifying questions so that I can have some more context:
How exactly are you achieving 1TB of RAM?

*

*p2.xlarge servers have 61GB of RAM, and p3.2xlarge servers have 61GB memory + 16GB onboard the Tesla V100 GPU.

How are you storing, resizing, and ingesting the images into the SageMaker algorithm?

*The memory error seems suspect considering it still occurs when downsizing images to 24x24. If you are resizing your original images (450 images at 2000x3000 resolution) as in-memory objects and aren't performing the transformations in-place (ie: not creating new images), you may have a substantial bit of memory pre-allocated, causing the SageMaker training algorithm to throw an OOM error.


text:
Q: facebook - get url of existing comment I am using facebook comments on many pages/servers for one FB application.
Is any options how to find url of added comment (I need to distinguish that each of comment belongs to certain page)?
I haven't find anything like that in management tool for comments.
Thx. Sam.


text:
Q: BeautifulSoup - Python - Find the key from HTML I have been practicing with bs4 and Python and now I have been stucked.
My plan is to do a If - Else state where I wanted to do similar like
If(I find a value inside this html)
   Do This method
Else:
   Do something else

and I have scraped up a html I found randomly which looks like -

and what I have done so far is that:
s = requests.Session()
    Url = 'www.myhtml.com' #Just took a random page which I don't feel to insert
    r = s.get(Url)
    soup = soup(r, "lxml")
    findKey = soup.find(('div', {'class': 'Talkinghand'})['data-key'])
    print(findKey)

but no luck. Gives me error and

TypeError: object of type 'Response' has no len()

Once I find or print out the key. I wanted to do a if else statement where it also says:
If(there is a value inside that data-key)
 ...

A: To display the data-key attribute from inside the
 tag, you can do the following:
from bs4 import BeautifulSoup

html = '

'
soup = BeautifulSoup(html, "html.parser")

print soup.div['data-key']

This would print:
123456

You would need to pass r.content to your soup call.
Your script had an extra ( and ), so the following would also work:
findKey = soup.find('div', {'class': 'Talkinghand'})['data-key']
print findKey


text:
Q: Why I'm not able to connect to HBase running as Docker container? I have my Java Spring app that deals with HBase.
Here is my configuration:
@Configuration
public class HbaseConfiguration {

    @Bean
    public HbaseTemplate hbaseTemplate(@Value("${hadoop.home.dir}") final String hadoopHome,
                                       @Value("${hbase.zookeeper.quorum}") final String quorum,
                                       @Value("${hbase.zookeeper.property.clientPort}") final String port)
            throws IOException, ServiceException {
        System.setProperty("hadoop.home.dir", hadoopHome);
        org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", quorum);
        configuration.set("hbase.zookeeper.property.clientPort", port);
        HBaseAdmin.checkHBaseAvailable(configuration);
        return new HbaseTemplate(configuration);
    }

}

#HBASE
hbase.zookeeper.quorum = localhost
hbase.zookeeper.property.clientPort = 2181
hadoop.home.dir = C:/hadoop

Before asking the question I tried to figure out the problem on my own and found this link https://github.com/sel-fish/hbase.docker
But still, I get an error
org.apache.hadoop.net.ConnectTimeoutException: 10000 millis timeout while waiting for channel to be ready for connect. ch : java.nio.channels.SocketChannel[connection-pending remote=myhbase/192.168.99.100:60000]

Could I ask you to help me and clarify how can I connect my local Java app with HBase running in Docker?


text:
Q: How to docker compose up a jenkins agent node with git installed I docker compose up my Jenkins Agent Node with
  jenkins_barcelona_node:
    image: jenkins/ssh-agent:jdk11
    privileged: true
    user: root
    group_add:
      - "998"
    depends_on:
      - jenkins  <-- Master Node
      - reverse-proxy
    container_name: barcelona
    restart: "always"
    hostname: barcelona
    networks:
      - akogare-net
    expose:
      - 22
    environment:
     - JENKINS_AGENT_SSH_PUBKEY=ssh-rsa......
    volumes:
     - barcelona-data:/var/barcelona_home
     - /usr/bin/docker:/usr/bin/docker
     - /var/run/docker.sock:/var/run/docker.sock

This results in a debian container running a Jenkins Slave Node and works as expected. But there is one thing I want to improve. For my pipeline I need git here. So I connect via SSH to this docker container and install git manually here with apt-get install git-all.
Is there a way to deploy a Jenkins Agent Node with git already installed? So I dont need to manually install it.


text:
Q: ManualResetEvent and Task Issue I've been working on a custom multi-threaded server that uses HTTP to communicate with clients.  To create new threads, I've been using the Task.Factory.StartNew() method. For synchronization, I've been using ManualResetEvent objects.
Here's the essence of the code:
namespace ThreadTest {
    class Program {
        private readonly ManualResetEvent _event = new ManualResetEvent(false);

        public void Start() {
            for (int i = 0; i < 100; i++) {
                int num = i;
                Task.Factory.StartNew(() => {
                    Console.WriteLine("Task {0} Started", num);
                    _event.WaitOne();
                });
            }
        }

        static void Main(string[] args) {
            var test = new Program();
            test.Start();
            Console.ReadLine();
        }
    }
}

In the real code, the _event object would eventually have Set called on it to release the waiting tasks.
The problem I've run into is that this code works fine on my development machine (which is dual-core with 2 threads per core and using the MS .NET 4 runtime) but does not work on my server (which is single core with 1 thread per core and using the Mono 2.8 runtime).  The output on my development machine is:
Task 0 Started
Task 1 Started
Task 3 Started
Task 2 Started
Task 4 Started
Task 5 Started
...

While the server output is
Task 53 Started

My question is: What am I misunderstanding about the ManualResetEvent or Tasks?  Why does the TaskFactory continue to make tasks on the dual-core but not the single-core?
Update:
I just tried it on my dual-core (1 thread per core) mac laptop and I got the output
Task 97 Started
Task 1 Started

And then nothing.  I also tried it with Mono on my development machine (4 threads) and got:
Task 99 Started
Task 2 Started
Task 98 Started
Task 0 Started

So it looks like a bug with Mono.

A: Turns out it was a bug in Mono.  I filed a report and it's now been fixed.

A: Your code as presented will never complete any of the tasks as the event is never signaled.  Ultimately it runs out of threads to allocate and it locks up.  The issue really is "how many threads does the task parallel library spin up under different CPU configurations when none of the threads can proceed" since that's what your code effectively measures.
The Task Parallel Library's default scheduler is based on ThreadPool, which uses a hill-climbing algorithm to adjust to the number of threads to maximize work item completion rate.  The algorithm takes into account how many cores you have.
There are better ways to use the Task Parallel Library to schedule work to happen once a Task has finished, ways that don't tie up threads, e.g ContinueWith.  What are you trying to achieve with the event construct?


text:
Q: Distribution of a general stochastic process composed with an independent random variable throught the index parameter Suppose you have a probability space $(\Omega, \mathcal{F}, \mathbb{P})$, a finite measure space $(S, \mathcal{S},\mu )$ and the associated product space $(S \times \Omega, \mathcal{S} \times \mathcal{F},\mu \times \mathbb{P})$.
Suppose further we have a collection $Y_s:\Omega \rightarrow \mathbb{R}$ of random variables indexed by elements $s\in S$. Let $X:\Omega \rightarrow S$ be a random variable with distribution $\nu$ that is independent of the $Y_s$'s.
I want to investigate under what conditions the following equality holds for all $B$ Borel:
\begin{equation}
\mathbb{P} \left( Y_X \in B \right) = \int_S \mathbb{P} \left(Y_s \in B \right)d\nu(s)
\end{equation}
I've been assuming that the function $f :S \times\Omega \rightarrow \mathbb{R}$ defined by $f(s,\omega)= Y_s(\omega)$ is measurable with respect to the product $\sigma$-algebra. Furthermore, my proof attempts to use the fact that a bounded measurable function $f$ can be approximated in $L^1$ by functions of the form:
\begin{equation}
\sum_{i=1}^{m_n}h_{n,i}(s)g_{n,i}(\omega)
\end{equation}
where the the $h$'s and $g$'s are bounded and measurable and in addition the $g$'s are independent of $X$.
Now I can prove the approximation without the independence clause for a general finite measure space $S$ but can only prove the full approximation by tightening $S$ to be a Polish space. Can this be loosened?
Also, does it help to consider the case where the $Y_s$'s and $X$ are all independent?


text:
Q: Can I shoot through teammates, enemies or civilians? There are instances where a teammate could be blocking an enemy in your line of fire. I was wondering if shot bullets / projectiles can pass through teammates and hit enemies on the other side.
If yes, how does the projectile penetration work? Will the impact on the first enemy hit by the projectile, lessen damage to the second enemy hit or not? Does this differ depending on the weapon or weapon mod?
I also would like to know how projectile penetration for enemies and civilians (to damage other enemies or civilians) work.

A: You cannot shoot through

*

*most of the map objects

*other players

*enemies

*civilians

You can shoot through

*

*glass

*AI companions

Bullets stop at the first thing you cannot shoot through.

A: To add to this answer, here are some info on projectile penetration mechanics from The Long Guide (edited to be in bulleted list format by me):

*

*All guns except shotguns penetrate breakable glass. It usually becomes damaged on the first hit, but the bullet still hits people or objects behind it dealing full damage.

*Enemy weapons do not penetrate.

*Bullets penetrating shields deal only 25% of their damage, provided the weapon is capable of that (sniper rifles, shotgun slug ammunition).

*Penetration of walls and enemies does not reduce the damage.

*When a bullet impacts somewhere and the weapon is capable of penetration against glass/walls/shields/enemies, the game spawns a new projectile 0.0125 seconds later and ignores the old one. The new projectile spawns 40 cm (20 cm against shields) behind the point of impact and is then affected by spread once again (e.g. firing a sniper rifle from the hip causes the new projectile to have higher spread regardless of the trajectory of the original projectile). The new projectile has some data from the old one.

*In particular, a projectile and its subsequent spawns can never penetrate more than one wall.

*The indestructible glass on some cars counts as a wall, so while sniper rifles can penetrate a window causing a new projectile to spawn inside the car, the new projectile will hit another window or the frame on the way out and vanish.

*The type of wall or obstacle is of no consequence, as long as it is thin enough. As a consequence of the projectile spawn delay, firing a loud weapon at a cool enemy behind an obstacle alerts him first before the new projectile hits him.

Source: Weapon Stats - Remarks   - The Long Guide
The armor piercing capability [of the 'Silent Killer' skill] only affects the body armor on Tans (it has no effect on Bulldozers, etc.). Without penetration, the front Tan armor fully blocks any incoming damage, so that not even hit indicators appear. With penetration, the bullet will deal full damage. Sniper rifles [and shotgun slug ammunition] have a 100% chance to penetrate and therefore do not benefit from an extra penetration chance.
Source: Remarks on Ghost skills - The Long Guide


text:
Q: After upgrading AGP version from 4.2.1 to 7.0.0(same with 7.0.1) WorkManger not run jobs after r8 minifying After upgrading AGP version from 4.2.1 to 7.0.0(same with 7.0.1) WorkManger not run jobs after r8 minifying(tested on debug and release builds with minifyEnabled = true).
No crash, but in Background tasks inspector job is just queued, but event didn't tried to start.
But it works correctly when minifyEnabled = false.
Tested on WM library versions: 2.5.0, 2.6.0.
Also tested with adding all proguard-rules from:
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-main/work/
but same issue was reproduced.
On 4.2.1 everything works fine.
Maybe issue is related in some way to upgrading Java from 8 to 11 version.
Link to PR with changes:
https://github.com/game-x50/android_client_app/pull/22/files
Thanks.


text:
Q: How to set two inputs and ungrey a button? I'm looking for a way to automatically fill in a username/password in a webpage using Greasemonkey.
The two tags are inputs, they have no ID but they're the only two inputs in the page, which appear when a 'log in' button is pressed.
I am a beginner in Greasemonkey (and javascript) and I was wondering how I could wait for these two inputs to appear.
Then there's two buttons, an 'ok' and a 'cancel' button. The 'ok' button is greyed, and setting the inputs with element0.value="password" doesn't ungrey the button.
How can I ungrey it using javascript?

A: The question lacks the requested and required HTML, but in general, you would use techniques from "Choosing and activating the right controls on an AJAX-driven site".
Something like:
// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

waitForKeyElements ("input[type='password']", logIn);

function logIn (jNode) {
    var inputs  = $("input");

    //-- DO NOT HARDCODE LOGIN CREDENTIALS IN A SCRIPT!
    $(inputs[0]).val ("username");
    $(inputs[1]).val ("password");

    //-- Might need to trigger a change or mouse event here.

    waitForKeyElements (
        "JQUERY SELECTOR FOR THE OK BUTTON IN THE ACTIVE STATE",
        clickOK_Btn
    );
}

function clickOK_Btn (jNode) {
    triggerMouseEvent (jNode[0], "click");
}

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

But do not hardcode login credentials.  Use a sensitive information framework.


text:
Q: date UTC in datepicker Having problem showing small date. Currently it shows long UTC date with time.
var events = [
    { Title: "Five K for charity", Date: new Date("03/13/2013"), Time: "11:15" },
    { Title: "Dinner", Date: new Date("03/25/2013"), Time: "11:15" },
    { Title: "Meeting with manager", Date: new Date("03/01/2013"), Time: "11:15" }
];

        for(var d=0;d<events.length;d++) {
        $('.myarray').append('
'+events[d].Title + '
' + events[d].Date + '
' + events[d].Time + '

');
        }

A: Your event[] array should be like this:
var events = [{
   Title: "Five K for charity",
   Date: "03/13/2013",
   Time: "11:15"
}, {
   Title: "Dinner",
   Date: "03/25/2013",
   Time: "11:15"
}, {
   Title: "Meeting with manager",
   Date: "03/01/2013",
   Time: "11:15"
}];

Date: new Date("03/25/2013"), This creates a full date and time with standards.


text:
Q: how to keep the system date & time unchanged in VMWare snapshot? I created MacOS Virtual Machine snapshot in VMware Fusion. I want the system date and time to be unchanged in the snapshot. I've unchecked "Synchronize Time" in Virtual Machine Settings. But everywhere I launched the snapshot the system date will be updated to the current system time. Any ideas how to fix this issue? Thanks!!

A: Have you also disabled the Network Adapter so that NTP can't sync?


text:
Q: Django Sphinx Foreign key search I'm trying to create full text search on model, everything goes fine
when
searching TextFields but I have a problem with ForeignKey field.
How can i do that? Can anyone point me to the right direction?
Thanks
Model example:
class Model1(models.Model):
 text_field =models.TextField(max_length=250)
 fk_field = models.ForeignKey('Model2')

class Model2(models.Model):
 text_field = models.TextField(max_length=250)

Thanks
R.

A: I would like to see your sphinx.conf.
Well for this which creating your indexer in sphinx.conf you need to specify what fields you select. After that what fields from your sql you select to be put as attributes (i.e. non searchable fields).
I suppose search with foreign-key fields are just as normal search. What particular difficulty/error are you facing?


text:
Q: SF book series with main character that had a golden suit which was paired with a golden spaceship It has been decades, but some details I remember. Humanity had become immortal either through technology or cloning. Set in our solar system. There was a super soldier who was actually the last soldier. The Golden suit and ship were paired and used to harness our suns power. Maybe?

A: As confirmed in the comments, this is "The Golden Transcendence" by John C. Wright, the final volume of The Golden Age trilogy.
The super soldier of the question is Phaeton; he indeed wears golden armour and pilots a golden ship named the Phoenix Exultant:

A hundred kilometers from prow to stern, sleek and streamlined as a
spear blade, a hull of golden adamantium, an artificially stable
element of unimaginable weight: immeasurably strong, inductile,
refractory.

The series is indeed set in our solar system, ten thousand years in the future. The sun's power has been harnessed, the planets have been relocated, and all minds are about to merge into a single supermind called the Transcendence. Phaeton combats the "Lords of the Silent Oecumene" who are trying to destroy mankind during this time of vulnerability.


text:
Q: Newton's Third Law is just wrong, can you see why? For every action there is an equally opposite reaction is flawed. Can you identify why?
The answer is simple enough and its simplicity makes it very hard to see, can you?

A: I guess you are considering that if there is an equal and opposite force, how is there any movement? The answer is that the equal and opposite forces are acting on two different bodies, and are causing movements on those bodies separately


text:
Q: How to replace Perl-style regex with MatchData object I am using the gsub method with a regular expression:
@text.gsub(/(-\n)(\S+)\s/) { "#{$2}\n" }

Example of input data:
"The wolverine is now es-
sentially absent from
the southern end
of its European range."

should return:
"The wolverine is now essentially
absent from
the southern end
of its European range."

The method works fine, but rubocop reports and offense:

Avoid the use of Perl-style backrefs.

Any ideas how to rewrite it using MatchData object instead of $2?

A: If you want to use Regexp.last_match :
@text.gsub(/(-\n)(\S+)\s/) { Regexp.last_match[2] + "\n" }

or :
@text.gsub(/-\n(\S+)\s/) { Regexp.last_match[1] + "\n" }

Note that the block in gsub should be used when logic is involved. Without logic, a second parameter set to "\\1\n" or '\1' + "\n" would do just fine.

A: You can use backslash without the block:
@text.gsub /(-\n)(\S+)\s/, "\\2\n"

Also, it's a bit cleaner to use only one group, since the first one above isn't needed:
@text.gsub /-\n(\S+)\s/, "\\1\n"

A: This solution accounts for errant spaces before newlines and split words that end a sentence or the string. It uses String#gsub with a block and no capture groups.
Code
R = /
    [[:alpha:]]\- # match a letter followed by a hyphen
    \s*\n         # match a newline possibly preceded by whitespace
    [[:alpha:]]+  # match one or more letters
    [.?!]?        # possibly match a sentence terminator
    \n?           # possibly match a newline
    \s*           # match zero or more whitespaces
    /x            # free-spacing regex definition mode

def remove_hyphens(str)
  str.gsub(R) { |s| s.gsub(/[\n\s-]/, '') << "\n" }
end

Examples
str =<<_
The wolverine is now es-
sentially absent from
the south-
ern end of its
European range.
_

puts remove_hyphens(str)
The wolverine is now essentially
absent from
the southern
end of its
European range.

puts remove_hyphens("now es-  \nsentially\nabsent")
now essentially
absent

puts remove_hyphens("now es-\nsentially.\nabsent")
now essentially.
absent

remove_hyphens("now es-\nsentially?\n")
  #=> "now essentially?\n" (no extra \n at end)


text:
Q: MVC CheckboxFor Im trying to make checkbox for each model element in my view. However my lamda expression does not work when trying call my properties. However it does work when using Html.DisplayNameFor.

I have been trying for several days. Can anyone please point me in the right direction?
BR

A: public class ModtagerOmradeView
{
    [DisplayName("Navan")]
    public bool Navan{ get; set; }
}

public ActionResult IndexUdbetaling()
{
  var modtagerOmradeView= new List<ModtagerOmradeView>()
  return View(modtagerOmradeView);
}

@model IEnumerable<ModtagerOmradeView>

@for( int i = 0; i < Model.ModtagerOmradeView.Count(); i++)
{
      @Html.LabelFor(model => modelModtagerOmradeVie[i].Navan)
      @Html.CheckBoxFor(model => modelModtagerOmradeVie[i].Navan)
}


text:
Q: C# HttpWebResponse GetResponse throwing 404 Error because it needs to be redirected I am currently designing an application that reads ID's from a text file and then adds it to the URL address... so urlhere is actually www.website.com/ID.  The only problem is that the website redirects from www.website.com/ID to www.website.com/username.  Is there a way I can tell the application to wait for the redirecting to happen?  I want to get information from the source of www.website.com/username.  Unfortunately I cannot because my application is currently trying to GetResponse() from the www.website.com/ID and throwing the exception error for 404 not found.  Unfortunately I cannot get the username so I cannot do www.website.com/username. Any suggestions will help.
HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create(urlhere);
            request.UserAgent = "Mozilla/16.02 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
            request.AllowAutoRedirect = true;
            // execute the request

            HttpWebResponse response = (HttpWebResponse)
                    request.GetResponse();


text:
Q: Android: Xmlserializer not respecting indentation Long story short, I'm developing an android app about collecting dynamic data and creating a KML file to show the characteristics of the driving with self-calibration of the sensors. I want to create a KML file using XMLserializer with the data obtained, this is the service that manages the process of creation of the file (it can run several times, that's why it doesn't close the file always):
File file = new File(sp.getString(getResources().getString(R.string.filesdir_key),"error"));
if (file.getPath().equals("error")) {
    file = new File (Environment.getExternalStoragePublicDirectory("/smart-drive").toString()
+ "/SmaDri_" + sp.getString(getResources().getString(R.string.ruta_key),"00000000_0000"));
    file.mkdirs();
}
finalFile = new File (file,"Final.kml");

if(!finalFile.exists()) {
    try {
        finalFile.createNewFile();
        Log.d(TAG, "RefreshKML: creando " + finalFile.getPath());
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "RefreshKML: fallo al crear " + finalFile.getName());
    }
    start = true;
}
try{
    fileos = new FileOutputStream(finalFile,true);
} catch(FileNotFoundException e) {
    e.printStackTrace();
    Log.d(TAG,"RefreshKML: error abriendo "+finalFile.getName());
}

try {
    serializer = Xml.newSerializer();
    serializer.setOutput(fileos, "UTF-8");
    if (start) {
        kH.SerialStart(serializer, fileos, "Ruta "+sp.getString(getResources().getString(R.string.ruta_key),"00000000_0000"));
        start = false;
    }

    int i=sp.getInt("poligonos",1);

    for (s=0 ; s<PolyArray.size() ; s++){
        polygon = PolyArray.get(s);
        kH.SerialPlacePol(serializer, fileos,"Tramo "+i, polygon);
        i++;
    }
    editor.putInt("poligonos",i);
    editor.apply();

    if (end) { //Solo cierra el archivo si se termina la recopilación de datos
        kH.SerialEnd(serializer, fileos);
        Log.d(TAG,"RefreshKML crea el cierre del KML");
        end=false; //En caso de que no se completó esta opción
        copyAllFiles();
        mainDB.close();
        DBHelper.close();
    }

    fileos.close();
} catch(IOException e) {
    e.printStackTrace();
    Log.d(TAG,"RefreshKML: error al escribir en serializer");
}

And these are the methods I use to create the header, body and close of the KML file:
public void SerialStart (XmlSerializer serializer, FileOutputStream fileos, String docName ) {
    try{
        serializer.startDocument(null, Boolean.valueOf(true));
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.startTag(null, "kml");
        serializer.attribute(null, "xmlns", "http://www.opengis.net/kml/2.2");
        serializer.attribute(null,"xmlns:gx", "http://www.google.com/kml/ext/2.2"); //ALE, para intentar que se vea en Earth
        serializer.attribute(null, "xmlns:kml", "http://www.opengis.net/kml/2.2");
        serializer.attribute(null, "xmlns:atom", "http://www.w3.org/2005/Atom");
        serializer.startTag(null, "Document");
        serializer.startTag(null, "name");
        serializer.text(docName);
        serializer.endTag(null, "name");
        serializer.startTag(null, "open");
        serializer.text("1");
        serializer.endTag(null, "open");
    } catch(Exception e){
        Log.d(TAG,"KMLHelper: Exception occured in SerialStart");
        e.printStackTrace();
    }
}
public void SerialPlacePol (XmlSerializer serializer, FileOutputStream fileos, String placeName, PolyKML poly ) {
    try{
        serializer.startTag(null, "Placemark");
        // He añadido el tag fill porque parece que Google Earth la exige

        serializer.startTag(null, "name");
        serializer.text(placeName);
        serializer.endTag(null, "name");

        serializer.startTag(null, "description");   //PARA DESCRIPCION TIEMPOS
        serializer.text(poly.gap);                  //PARA DESCRIPCION TIEMPOS
        serializer.endTag(null, "description");     //PARA DESCRIPCION TIEMPOS

        serializer.startTag(null, "Style");
        serializer.startTag(null, "LineStyle");

        serializer.startTag(null, "color");
        serializer.text(poly.getLineColor());
        serializer.endTag(null,"color");

        serializer.startTag(null, "width");
        serializer.text(poly.getLineWidth());
        serializer.endTag(null,"width");

        serializer.endTag(null,"LineStyle");
        serializer.startTag(null, "PolyStyle");

        serializer.startTag(null, "color");
        serializer.text(poly.getPolyColor());
        serializer.endTag(null,"color");

        //ALE
        serializer.startTag(null,"fill");
        serializer.text("1");
        serializer.endTag(null,"fill");
        //ALE

        serializer.endTag(null,"PolyStyle");
        serializer.endTag(null,"Style");

        serializer.startTag(null, "Polygon");

        serializer.startTag(null, "tessellate");
        if(poly.getTessellate()) serializer.text("1");
        else serializer.text("0");
        serializer.endTag(null,"tessellate");

        serializer.startTag(null, "extrude");
        if(poly.getExtrude()) serializer.text("1");
        else serializer.text("0");
        serializer.endTag(null,"extrude");

        serializer.startTag(null, "altitudeMode");
        serializer.text(poly.getAltitudeMode().toString());
        serializer.endTag(null,"altitudeMode");

        serializer.startTag(null, "outerBoundaryIs");
        serializer.startTag(null, "LinearRing");

        serializer.startTag(null, "coordinates");
        serializer.text(poly.getCoorString());
        serializer.endTag(null, "coordinates");

        serializer.endTag(null, "LinearRing");
        serializer.endTag(null, "outerBoundaryIs");
        serializer.endTag(null, "Polygon");
        serializer.endTag(null,"Placemark");
        serializer.flush(); //ALE
    }catch(Exception e){
        Log.d(TAG,"KMLHelper: Exception occured in SerialPlacePol");
        e.printStackTrace();
    }
}

public void SerialEnd (XmlSerializer serializer, FileOutputStream fileos ) {
    try{
        serializer.endTag(null,"Document");
        serializer.endTag(null,"kml");
        //serializer.endDocument();
        serializer.flush();
        fileos.close();
        Log.d(TAG,"KMLHelper: SerialEnd cierra archivo KML");
    }catch(Exception e){
        Log.d(TAG,"KMLHelper: Exception occured in SerialEnd");
        e.printStackTrace();
    }
}

And the result is fine but the indentation, it is lost after some time, it always happens. An example of the resulting file with the difference in the indentation is the following, there is one placemark with the proper indentation but suddenly the following has no indentation at all:
<Placemark>
  <name>Tramo 1</name>
  <description>1484689867000 - 1484689868000</description>
  <Style>
    <LineStyle>
      <color>55FFFFFF</color>
      <width>1</width>
    </LineStyle>
    <PolyStyle>
      <color>4114B464</color>
      <fill>1</fill>
    </PolyStyle>
  </Style>
  <Polygon>
    <tessellate>1</tessellate>
    <extrude>1</extrude>
    <altitudeMode>relativeToGround</altitudeMode>
    <outerBoundaryIs>
      <LinearRing>
        <coordinates>-4.46107189168431,36.7189079696287,1.0 -4.461074321984691,36.71889869818065,1.0 -4.46104946831569,36.718892230371296,1.0 -4.461047018015309,36.71890140181935,1.0 -4.46107189168431,36.7189079696287,1.0</coordinates>
      </LinearRing>
    </outerBoundaryIs>
  </Polygon>
</Placemark><Placemark><name>Tramo 1</name><description>-15 - -15</description><Style><LineStyle><color>55464646</color><width>1</width></LineStyle><PolyStyle><color>55FFFFFF</color><fill>1</fill></PolyStyle></Style><Polygon><tessellate>1</tessellate><extrude>1</extrude><altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>-4.461042046219597,36.718907918437075,1.0 -4.461048518308548,36.71890698667229,1.0 -4.461047061691453,36.71889709332772,1.0 -4.461040613780402,36.71889802156293,1.0 -4.461042046219597,36.718907918437075,1.0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark><Placemark><name>Tramo 1</name><description>-15 - -15</description><Style><LineStyle><color>55464646</color><width>1</width></LineStyle><PolyStyle><color>55FFFFFF</color><fill>1</fill></PolyStyle></Style><Polygon><tessellate>1</tessellate><extrude>1</extrude><altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>-4.461038813540282,36.718908388824126,1.0 -4.461042046219597,36.718907918437075,1.0 -4.461040613780402,36.71889802156293,1.0 -4.461037386459718,36.71889849117587,1.0 -4.461038813540282,36.718908388824126,1.0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>

Can anyone tell me what is the problem that is causing to lose the indentation? I'll appreciate any ideas that could me help solve this problem

A: Solved, there was more than a XMLserializer writing to the same file so it didn't work fine. Now only 1 thread can access and write to the file at a time and the problem is gone!


text:
Q: Como desabilitar o click(Touch) em uma WebView? A aplicação é simples. Mostrar uma webview de um site externo.
O problema que eu quero desabilitar clicks, não quero que dê para o usuário navegar, quero que apenas olhe a pagina inicial setada.
package br.com.spitzer.webview;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ViewTabelasE extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tabelas_e);
        WebView wv = (WebView) findViewById(R.id.webView1);
        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(false);
        ws.setSupportZoom(false);
        wv.setWebViewClient(new WebViewClient());
        wv.loadUrl("http://www.google.com");

    }

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_menos2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    android:background="@color/colorPrimary"
    tools:context="br.com.spitzer.webview.ViewTabelasE">

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="-390dp"
        android:layout_marginTop="-200dp"
        android:clickable="false">

    </WebView>

</RelativeLayout>

o  android:clickable="false" não funciona.

A: Tente usar:
webView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    return true;
}});

Isso desativa o touch.
Fonte: Pergunta Stack (Inglês)


text:
Q: Assign unique id inside of groups (with duplicated records) I have a DataFrame looks like this:
df = pd.DataFrame({'type': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'B','C','C','C','D','D'],
                   'value': [1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 8],
                  })

I would like to create a unique id based on the type and value columns, the output will look like this:
df = pd.DataFrame({'type': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'B','C','C','C','D','D'],
                   'value': [1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 8],
                   'id': [1, 1, 2, 1, 2, 3, 3, 3, 1, 1, 2, 1, 2],
                  })

A: Use DataFrameGroupBy.rank:
df['id'] = df.groupby('type')['value'].rank('dense').astype(int)
print (df)
   type  value  id
0     A      1   1
1     A      1   1
2     A      2   2
3     B      3   1
4     B      4   2
5     B      5   3
6     B      5   3
7     B      5   3
8     C      6   1
9     C      6   1
10    C      7   2
11    D      7   1
12    D      8   2

Or GroupBy.transform with factorize:
f = lambda x: pd.factorize(x)[0]
df['id'] = df.groupby('type')['value'].transform(f).add(1)

A: Use:
t = df.groupby(['type']).transform(lambda x: x.iloc[0])
df['id'] = df.groupby(['type', 'value'])[['type', 'value']].apply(lambda x: x.name[1]).reset_index().merge(df, on = ['type', 'value'])[0]-t['value']+1

Output:
type    value   id
0   A   1   1
1   A   1   1
2   A   2   2
3   B   3   1
4   B   4   2
5   B   5   3
6   B   5   3
7   B   5   3
8   C   6   1
9   C   6   1
10  C   7   2
11  D   7   1
12  D   8   2


text:
Q: Which volatile ices are hardest below 100 K? In the context of planetary science,
some elements and compounds are informally called volatile instead of refractory,
such as
H2O, HCN, CO2, NH3, HCHO, CH4, CO, N2.
At conditions found near planetary surfaces in the solar system
(often much colder than Earth's),
when these are solid, which ones are hardest by a scale such as Vickers, Rockwell, Brinell, Mohs, Shore or Knoop?
Direct measurements seem rare.  We might need ab initio simulation.


text:
Q: bootstrap 4 Grid, laying 4 elements in a row with a custom horizontal gutter I am trying to lay 4 elements in a row with a custom horizontal gutter, I tried to put each element in a col with the class of col-md-2 for a certain screen size, and modify the margin-right of each element to my need.. but it didn't look very good, when applying the col-md-3 obviously there is no room for adding a margin to each element, surprisingly when I tried applying col-md-2.5 class, it worked on big screens, however, when I want to have the element span to 10 cols in the smaller screens, it does, but when i go back to the bigger screen, it behaves like the small screen again, Here is my HTML code and i will leave a screenshot down below to illustrate the behavior that I want.

[class^="col"]:not(:last-child){
    margin-right: 60px;
  }

1

2

3

4

1

2

3

4


text:
Q: Access by value on nested JSON arrays I'm new to JavaScript and I'm really lost here.  Here is some data produced by PHP json_encode() (and limited to most pertinent keys) :
[
  {
    "product_option_id":"229",
    "product_option_value":
    [
      {
        "product_option_value_id":"21",
        "option_value_id":"51",
        "price":"1,22 €",
        "price_prefix":"+"
      },
      {
        "product_option_value_id":"22",
        "option_value_id":"52",
        "price":false,
        "price_prefix":"+"
      },
      {
        "product_option_value_id":"23",
        "option_value_id":"53",
        "price":"2,42 €",
        "price_prefix":"+"
      }
    ],
    "option_id":"14",
    "type":"radio",
    "value":""
  },
  {
    "product_option_id":"228",
    "product_option_value":
    [
      {
        "product_option_value_id":"19",
        "option_value_id":"49",
        "price":"1,22 €",
        "price_prefix":"+"
      },
      {
        "product_option_value_id":"20",
        "option_value_id":"50",
        "price":"2,42 €",
        "price_prefix":"+"
      }
    ],
    "option_id":"13",
    "type":"select",
    "value":""
  }
]

I need to access price and price_prefix values (in JavaScript) knowing product_option_id and product_option_value_id.
How do I do that ?  Should I go for a loop ?
Update :
Thanks for replies.  Unless I missed something, it appears that in my case arrays (as ugly as they may be…) are much more efficient than all the proposed solutions (I'll try another approach, formatting a JSON object corresponding to my needs with PHP rather than using the "default" one, but it's off topic here).  Though I'm not fond of adding libraries and it's a bit slower than most other solutions, I'll accept Matt's solution because it really seems to make life easier as far as JSON access is concerned.  But it should be noted that Yeldard and Barmar's (almost cloned) solutions are faster than other propositions.

A: you can do like this
    for(var i in jsonData) {
    var item = jsonData[i];
    if(item.product_option_id == 229) {
        for(var j in item.product_option_value){
            var item1 = item.product_option_value[j];
            if(item1.product_option_value_id == 21) {
                //your item here
                break;
            }
        }
       break;
    }

}

A: This should do it:
var productOptionId = 229;
var productOptionValue = 22;

var matchingOuter = yourData.filter(function(i){
    return i.product_option_id === productOptionId;
})[0];

if (matchingOuter) {
    var matchingInner = matchingOuter.product_option_value.filter(function(i){
        return i.product_option_value === productOptionValue;
    })[0];
}

If a matching item exists it will be assigned to matchingInner

A: Use nested loops to search through the main array and the sub-arrays, looking for the matching element.
function find_product(product_option_id, product_option_value_id) {
    for (var i = 0; i < products.length; i++) {
        var product = products[i];
        if (product.product_option_id == product_option_id) {
            for (var j = 0; j < product.product_option_value.length; j++) {
                var value = product.product_option_value[j];
                if (value.product_option_value_id == product_option_value_id) {
                    return { price: value.price, price_prefix: value.price_prefix }
                }
            }
        }
    }
}

A: Use filter on the main array to grab the right object, filter again on the option_value_id, then map on the returned array to get a single price/prefix object. map and filter both return arrays which is why you see the code picking up the first element ([0]) in a couple of places.
function getData(data, options) {
    return data.filter(function (product) {
      return product.product_option_id === options.id;
    })[0].product_option_value.filter(function (details) {
       return details.product_option_value_id === options.optionId;
    }).map(function(el) {
      return { price: el.price, prefix: el.price_prefix }
    })[0];
}

getData(data, { id: '229', optionId: '23' }); // { price: "2,42 €", prefix: "+" }

DEMO

A: Following would do:
function getProductValues(products, product_option_id, product_option_value_id) {
    if (!product_option_id || !product_option_value_id) {
        return;
    }

    return products.filter(function(product) {
        return +product.product_option_id === product_option_id;
    }).map(function (product) {
        var option_values = product.product_option_value;
        return option_values.filter(function (option) {
            return +option.option_value_id === product_option_value_id;
        })[0] || [];
    })[0] || [];
}

Usage:
getProductValues(data, 229, 51)

Result:
{product_option_value_id: "21", option_value_id: "51", price: "1,22 €", price_prefix: "+"}

A: lodash would make this easier and neater. It provides _.find or _.filter depending on if your id's are unique or not.
var record = _.find( data_structure, {
  "product_option_id": "229"
})
if ( !record ) throw new Error("Record not found");

var value = _.find( record.product_option_value, {
  "product_option_value_id":"22"
})
if ( !value ) throw new Error("Value not found");

console.log( "price[%s] prefix[%s]", value.price, value.price_prefix )

Demo
For more complex data selection, you might want to look at sift.js. It's based on mongodb's query system.
var records = sift({
    "product_option_id": "229",
    "product_option_value": {
      $elemMatch: {
        "product_option_value_id": "22"
      }
    }
  },
  data_structure
)

A: Yes, you need to enumerate through the array and find your items:
Here is the working code which outputs price_prefix and price of product with product_option_id = 228 and product_option_value_id = 19. You can replace these values with your own.
for (var i = 0; i < obj.length; i++) // Enumerate through array
{
    var item = obj[i];
    if (item.product_option_id === "228") // Filtering items by product_option_id
    {
        // When necessary product_option_id found
        for (var j = 0; j < item.product_option_value.length; j++) // Enumerate through its products
        {
            var productItem = item.product_option_value[j];
            if (productItem.product_option_value_id === "19") // Filtering by product_option_value_id
            {
                // here it is. productItem is found! do whatever you want with it
                alert(productItem.price_prefix + " " + productItem.price);
            }
        }
    }
}

Working JSFiddle demo.


text:
Q: python google search API - not giving correct results ^
|
| this question DOES NOT HAVE an answer yet!

I am trying to do google search from python script.
xing = "site:xing.com inurl:profile intext:Systemadministrator AND UNIX AND Hamburg"
query = urllib.urlencode ( { 'q' : xing } )
response = urllib.urlopen ( 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&' + query ).read()
import json as m_json
json = m_json.loads ( response )
results = json [ 'responseData' ] [ 'results' ]
print len(results)

the problem is, it is giving  me only 4 results. If i paste the search string in google, it is finding more than 100 results. what am i doing wrong here?
EDIT
i changed the code to this:
import urllib
import django.utils import simplejson
num_queries = 50*4
xing = "site:xing.com inurl:profile intext:Systemadministrator AND UNIX AND Hamburg"
query = urllib.urlencode({'q' : xing})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query

for start in range(0, num_queries, 4):
    request_url = '{0}&start={1}'.format(url, start)
    search_results = urllib.urlopen(request_url)
    json = simplejson.loads(search_results.read())
    results = json['responseData']['results']
return HttpResponse(search_results)

i am receiving no data. search_results is empty. why is this?


text:
Q: PHP/JS software copy protection First of all I know nothing I can do that 100% prevents illegal copying of my software. I'd like to just make it reasonably hard for a competent person to do, and almost impossible for an unknowledgeable person to do.
I have a contract job coming up to develop a web app using the WAMP stack, commissioned by a company's IT manager. During our meeting and conversations, he kept being generic about the software requirements, seemingly refusing to develop requirements specific to his company. So I got the impression as if he was intending to resell the software to other companies for his profit.
And for people who say "people who pirate software aren't in your target market anyway", obviously that doesn't apply in this case because if he resells my software to other companies, those companies ARE in my target market.
The functionality in my software will be divided both in the server-side (PHP) and client-side (JS) using a good JS framework, if possible I want to protect both, (but I think for JS the only thing I can do is obfuscate the code).
I can't just refuse the contract because I need the money.
Is there anything at all I can do?
Edit: I'm also open to using external applications (i.e. written in C, Java, etc. or compiled into dll) to handle the copy-protection. Just need to know the general mechanism of it, if possible.

A: You are solving the wrong problem.
You can't hide your code when using php and javascript. You can obfuscate but it will not deter anyone trying to steal your code.
What you need is a contract where it is clearly written what your code does, what the customer is allowed to do with your code and penalties for breaking the contract by distributing your code without your consent.
For that you'll need a lawyer.

A: First don't forget to use a licence!
https://stackoverflow.com/questions/4766834/how-do-i-protect-javascript-files :

a very interesting article written by Patrick Weid on how to hide your
  js code, and he reveals a different approach: you can encode your
  source code into an image! Sure, that's not bullet proof either, but
  it's another fence that you could build around your code. The idea
  behind this approach is that most browsers can use the canvas element
  to do pixel manipulation on images. And since the canvas pixel is
  represented by 4 values (rgba), each pixel can have a value in the
  range of 0-255. That means that you can store a character (actual it's
  ascii code) in every pixel. The rest of the encoding/decoding is
  trivial. Thanks, Patrick!

The article : https://www.patrick-wied.at/blog/a-technique-for-hiding-your-javascript-code
It is impossible to project your code via JavaScript, because the code is executed on the client. That being said, you can make it difficult to obtain for less advanced developers, who are likely the kind of scum that would steal code and claim they wrote it. Real developers have way too much pride to steal code, and would more than likely write their own. That being said, here is how.

*

*Create a Server side file that requires an active authenticated session in your controller and embed your javascript into this file. Use Ajax to retrieve the file when the page that you want to reference loads it and add the script to the DOM. In other words, dynamically embed your javascript at run time so that it's not visible when view source is selected.

*If you really want to make things complicated, split the logic between server side and client side. Have some of the work done server side via ajax post/get methods and some done client side. Be sure that active session params are used so that no one can simply reference your logic and steal it all. This way if they steal part of the code, they still have to be intelligent enough to write the rest, which probably won't be the case if they're attempting to steal.

*You can also throw your own encryption into the mix, though this will slow things down. You can use a two way hash that uses something as simple as a session id, and decrypt and execute as you go.

*Lastly, you can embed an erroneous javascript file ripe with errors and malicious code to totally jack up unsuspecting losers system called gotcha.js! Ok, that might be a bit overboard, but misdirection is the key here.

A: You can't in this situation, obfuscation is not copy protection and just gets in the way. In any case - you have to trust the people you work with. If you don't trust them don't work with them.


text:
Q: Can I reproduce Scala's behavior for ==? In Programming in Scala, I can read that the == operator behaves as if it was defined like this:
final def == (that: Any): Boolean = if (null eq this) {null eq that} else {this equals that}

But there must actually be compiler magic to avoid null pointer exceptions, right? Is there any way for me to replicate this behavior with pure Scala; i.e., have an operator/method return one thing if the receiver is null and another one if it isn't? What I mean is an actual implementation of null eq this.
I suppose I can write a "pimp" and then define the method on the wrapper class, but is there a more direct way to do this?

A: I don't think so. As far as I know there is no magic for nulls. (see Update)
I think the best you can do, is to wrap any object to option, so that you can use bunch of useful stuff from it:
implicit def toOption[T](target: T) = Option(target)

val q: String = null
val q1: String = "string"

println(q getOrElse "null") // prints: null
println(q1  getOrElse "null") // prints: string

Update
I found this document:
http://www.scala-lang.org/api/2.7.7/scala/Null.html
According to it:

Class Null is - together with class Nothing - at the bottom of the Scala type hierarchy.

So even null has methods inherited from AnyRef like eq, ==, etc... And you also can use them:
val q: String = null
val q1: String = "string"

println(null eq q) // prints: true
println(null eq q1) // prints: false

A: "null" is the only instance of a trait called Null - so it's just a normal object, no magic to invoke ==
You should definitely check out Option and do everything you can to keep nulls out of your code :)

A: There's no magic for nulls, but scala does have some magic for making equality symmetric for numbers.
The trick is to extend the ScalaNumber trait...
http://www.scala-lang.org/node/6387
update
Just to clarify that a bit... This means that if you write a == b and b derives from ScalaNumber or (I believe) is an AnyVal, then the compiler will test instead for b == a.
Not only does this resolve the null situation, but it also makes things a lot easier if you want to compare a primitive to some other type that can be viewed as a number, but for which an implicit conversion would be recklessly unsafe.  This is the approach used with e.g. BigInteger.

A: There doesn't appear to be any way to do this without special casing the null case. Java won't allow a method to be called if the object is null. This compared to a language like python where None is a proper object. I think the best thing to do is try and ignore the fact that null exists.
Useing an implicit to simulate ==
class Equals2(v:AnyRef){
  def ===(that:AnyRef) =  if(v eq null) {that eq null }else {v equals that}
}
implicit def equals2(v:AnyRef) = new Equals2(v)

Unfortunately the following doesn't work as null is not a subclass of AnyRef
null === "Something"

A: null is the only instance of Null and is therefore -- in Scala -- a full object.
If you define your function in the spirit as you posted above in class A, all you have to do is to provide an implicit conversion from Null to A that maps null to some dummy instance.

A: You can use Option.
scala> Option("a")
res0: Option[java.lang.String] = Some(a)

scala> Option(null)
res1: Option[Null] = None


text:
Q: 16.10 broke my MythTV I just upgraded from 16.04.1 to 16.10, and now MythTV 0.28 is broken. It worked fine in 16.04.1.
Specifically it's the mythtv-frontend that's broken. It won't start, and this throws this error:
*** stack smashing detected ***: /usr/bin/mythfrontend.real terminated

The mythtv-backend seems to be running fine... which probably means that the MySQL database is working fine too.
There's not much additional information that I can provide. Can anybody help?!?

A: The crash on mythfrontend startup has been fixed with release 0.28.0+fixes.20161106.1434df8-0ubuntu0mythbuntu2.
Mythfrontend now starts and runs, but crashes on exit with seg fault.


text:
Q: Django redirect to an swf I'm trying to redirect to a swf file because I need to embedd that in a fb:swf which wants its absolute path. When I handle the swf in url's somehow it doesn't work.
In url.py
(r'^flash/','lastproject.yofacebook.flashtest.flash'),

In flahstest.flash
def flash(request):
return render_to_response('as3.swf')

I want to open the swf on this url
http://testapp.varheroes.com/flash/

the fb:swf
<fb:swf
    swfbgcolor="ffffff"
    swfsrc='http://testapp.varheroes.com/flash/'
    width='620' height='530' />

The error I get
'utf8' codec can't decode bytes in position 5-6: invalid data

A: render_to_response is used to render a template and send it as a response. I don't think your swf file is a template, so you should just return it directly:
return HttpResponse(open('as3.swf'))

But really you shouldn't be sending that file through Django at all, it should be served by whatever is serving the rest of your static files (CSS, JS etc).

A: I would keep your swf file in the static directory and add a url pattern to redirect to your file eg:
from django.views.generic.simple import redirect_to

urlpatterns = patterns('',

    ...
    (r'^flash/', redirect_to, {'url': settings.STATIC_URL + 'as3.swf'}),
    ...
)

This redirects for example, /flash/ to STATIC_URL + as3.swf (eg: /static/as3.swf)
as3.swf shall be in your static directory.


text:
Q: Javascript object traversal I need Help regarding the traversal of each and every elements in the following JSON and get both key and value and print it like an unordered list.
var dataSource = ({
                "Items": ({
                    "Deserts": ({}),
                    "Veg": ({
                        "VegPulao": "Veg Pulao",
                        "PalakPaneer": "Palak Paneer",
                        "PaneerButterMasala": "Paneer Butter Masala"
                    }),

                    "Chicken": ({
                        "Tandoori": "Tandoori special"
                    }),
                    "Hot drinks": ({
                        "Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
                        "Tea": ({"Red": "Red Tea", "Black": "Black Tea"}),
                        "BadamMilk": "Hot Badam Milk",
                        "Bornvita": "Hot Bornvita",
                        "Milk": "Hot Milk"
                    }),
                    "Juice": ({
                        "Mango": "Mango",
                        "Berry": "Berry",
                        "Grapes": "Grapes",
                        "Wine": ({
                            "Rose": "Rose",
                            "Red wine": "Red",
                            "Apple": "Apple",
                            "Hard drinks": ({
                                "Royal challenge": "Royal challenge",
                                "Blender's Pride": "Blender's Pride"
                            })
                        })
                    })

                })
            });

A: It is not clear exactly what form of output you want, but here's a method of traversing your data structure and generating some indented output.  Also, parentheses are not necessary in your data definition (I have removed them to make the data easier to read).
function output(str, level) {
    var obj = document.getElementById("output");
    var div = document.createElement("div");
    var node = document.createTextNode(str);
    div.style.marginLeft = (level * 20) + "px";
    div.appendChild(node);
    obj.appendChild(div);
}

function traverseObject(obj, level) {
    for (var prop in obj) {
        if (typeof obj[prop] === "object") {
            output(prop, level);
            traverseObject(obj[prop], level + 1);
        } else {
            output(prop + ": " + obj[prop], level);
        }
    }
}

traverseObject(dataSource, 0);

Working demo: http://jsfiddle.net/jfriend00/6kAn3/


text:
Q: how to restore default gui user interface on linux mint 21 hi trying to install a program I changed the user interface of my linux mint 21.
right now I have mate. but I dont know How I can back to have the default cinnamon of linux min 21
I am desperate


text:
Q: Access double to SQL decimal using SQL Bulk Copy I have an Access database that I am converting to an SQL database using sqlbulkcopy in vb.net.  We have currency values (up to 2 decimal places) stored in Access as Double.  When I convert these Access fields to SQL fields with type [decimal] (19, 2), a number like 81.6 stored in the Access field sometimes appears as 81.59 in the SQL field when converted.
If I change the type in SQL to [decimal] (19,4) then it shows as 81.5999.  The number in Access is definitely calculated and stored to no more than two decimal places.  Can someone explain to me why SQL is doing this?  It doesn't happen all the time... only in some records.
I've reviewed just about any article I could find that explains decimal types and I understand what decimal is (I think), but I don't understand why numbers sometimes get converted like this.  Thanks for your help.
EDIT:
Here is the code that I mentioned below that I used to loop through all of the tables and columns to rename the aliased columns ending in "1Z" to their original names:
        Dim dtTbls As DataTable = cnnSQL.GetSchema("Tables")
    For Each drTbls As DataRow In dtTbls.Rows
        Dim sTableName As String = drTbls(2)
        Dim query As String = String.Concat("select * from [", sTableName, "] Where 0=1")
        Dim myCmd As SqlDataAdapter = New SqlDataAdapter(query, cnnSQL)
        Dim myData As New DataSet()
        myCmd.Fill(myData)
        For Each colu As DataColumn In myData.Tables(0).Columns
            If colu.ColumnName.EndsWith("1Z") = True Then
                Dim sNewColName As String = colu.ColumnName.Remove(colu.ColumnName.Length - 2, 2)
                dbSQL.ExecuteNonQuery(String.Concat("EXEC sp_rename '", sTableName, ".", colu.ColumnName, "', '", sNewColName, "', 'COLUMN'"))
            End If
        Next colu
    Next drTbls

A: Your problem is that floating-point types like Double often cannot store numbers exactly, even values which seem to be quite "simple" numbers to us humans. This can be demonstrated by typing the following  into the Immediate Window of the VBA editor in Access:
?(CDbl(81.60) * CDbl(100)) - CDbl(8160)

The result returned is
-5.6843418860808E-13

Your experience suggests that a direct transfer of Access Double to SQL Server decimal will truncate the number instead of rounding it. Therefore, what you need to do is copy the values from Access into a separate SQL Server column of type float, and then use an UPDATE query in SQL Server to populate the decimal(19,2) column, e.g.,
UPDATE TableName SET DecimalColumn = ROUND(FloatColumn, 2)

Edit
In case it makes things easier, it should also be possible to do the rounding and conversion on the Access side. You could create a Select query for each table that rounds the monetary values and converts them to Currency, like this...
SELECT ProductID, ProductName, CCur(Round([UnitPrice],2)) AS CurrUnitPrice
FROM Products;

...and then SqlBulkCopy the query instead of the table.
Edit
As you may have discovered, trying to convert a column while retaining the original column name with a query like...
SELECT ProductID, ProductName, CCur(Round([UnitPrice],2)) AS UnitPrice
FROM Products

...results in the error

Circular reference cause by alias 'UnitPrice' in query definition's SELECT list

A workaround for that issue would be to use a query like this:
SELECT ProductID, ProductName, CurrUnitPrice AS UnitPrice
FROM
(
    SELECT ProductID, ProductName, CCur(Round([UnitPrice],2)) AS CurrUnitPrice
    FROM Products
)


text:
Q: Python 3 - Example of Multithreading request using requests, asyncio and concurrent So, I wrote the following code based on an example of a multi request using asyncio and concurrent libs, that I found here.
Basically, for a given list of names, I make some parallel requests to get the user's ID. (That's just an example of usage)
The values returned from getUserId function are stored in the 'futures' list, and you can get these values using the result() method that can be accessed from each element in the list.
This is currently a good approach?
import requests, asyncio, concurrent

async def makeMultiRequests(names):

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor,
                getUserId,
                name
            )
            for name in names
        ]

    return futures

def getUserId(username):
    # requests.get() user Id
    return userId;

names = ['Name 1', ..., 'Name N']

loop = asyncio.get_event_loop()
resultList = loop.run_until_complete(makeMultiRequests(names))
loop.close()

for result in resultList:
    print(result.result()) # Users Id printed

Best regards.


text:
Q: Using free() on a pointer within a struct frees memory for the entire struct I have two structs within my program. The first one, huffchar is below, and just shows the general structure (mostly irrelevant to the question), but the second one, huffcoder is the one that I'm having an issue with:
struct huffchar {
    int freq;
    int is_compound;
    int seqno;
    union {
        struct {
        struct huffchar * left;
        struct huffchar * right;
        } compound;
        unsigned char c;
    } u;
};

struct huffcoder {
    int freqs[NUM_CHARS];
    int code_lengths[NUM_CHARS];
    unsigned long long codes[NUM_CHARS];
    struct huffchar * tree;
    int sizeOfTree;
};

When I initialize a huffcoder in my program, I malloc ourHuffCoder the size of a huffcoder, and then malloc memory for X many elements to the struct huffchar * tree:
struct huffcoder * ourHuffChar = malloc(sizeof(struct huffcoder));
ourHuffChar -> tree = malloc(sizeof(struct huffchar)*NUM_CHARS);
However, I will need to make this tree larger at a later point, and do not know how many elements will be on this tree at the end. In other words, every time I add an element, I will create a new tree with realloc() that is one element larger, then set the pointer for tree within the huffcoder to this new updatedTree.
The follow lines of code are intended to achieve this:
    struct huffchar * updatedTree = realloc(ourHuffCoder -> tree, (ourHuffCoder->sizeOfTree+1)*sizeof(struct huffchar));
    free(ourHuffCoder -> tree);
    ourHuffCoder -> tree = updatedTree;

Note that I use the line free(ourHuffCoder -> tree) to free the memory that has been previously allocated to the tree, before updating the tree pointer to updatedTree. However, when I reach the free(ourHuffCoder -> tree) line, memory allocated to the entirety of the HuffCoder pointer ourHuffCoder is freed instead of just the memory allocated to the tree.
Here is my variables window before running the free(ourHuffCoder->tree) line:

And here is after running the free(ourHuffCoder->tree) line:

I have also tried creating an entirely new pointer huffchar * ourTree = ourHuffCoder -> tree and use this variable for the free() method instead, but I get the same result.
Just to test my code, I modified the above code to remove the free() line,
    struct huffchar * updatedTree = realloc(ourHuffCoder -> tree, (ourHuffCoder->sizeOfTree+1)*sizeof(struct huffchar));
    ourHuffCoder -> tree = updatedTree;

This is obviously not what I should be doing because I will run out of memory quickly, but I wanted to see if the pointer to tree within huffcoder would be updated to point to updatedTree, which is has:
Before ourHuffCoder -> tree = updatedTree;

After ourHuffCoder -> tree = updatedTree;

My question is, why is the memory allocated to the entirety of the huffcoder struct being freed, instead of just the memory to the tree? How do I solve this? Is there a better way of increasing the memory allocated to the tree?

A: The mistake I see is that realloc is already a combination of malloc and free. The free call here is unnecessary and wrong:
struct huffchar * updatedTree = realloc(ourHuffCoder -> tree, (ourHuffCoder->sizeOfTree+1)*sizeof(struct huffchar));
free(ourHuffCoder -> tree);
ourHuffCoder -> tree = updatedTree;

That is to say, when we call realloc(ptr), ptr is deallocated and a new pointer is returned. The allocator can sometimes optimize the process by resizing the old object in place.
There is no need to free ptr, and we must not do so, in fact.
If we didn't care about the optimization, we could almost write realloc like this:
#include <string.h>
#include <stdlib.h>
#define min(a, b) ((a) < (b) : (a) : (b))

void *our_realloc(void *oldptr, size_t newsize)
{
   if (newsize == 0) {
      free(oldptr);
      return 0;
   } else {
      void *newptr = malloc(newsize);
      if (oldptr) {
         size_t oldsize = __obtain_old_size_in_nonportable_way(oldptr);
         memcpy(newptr, oldptr, min(oldsize, newsize));
         free(oldptr); // !!!!
      }
      return newptr;
   }
}

Even in cases when realloc returns the "same" pointer, the program cannot easily tell. The old pointer has become invalid, so any use of it is undefined behavior:
newptr = realloc(oldptr, size);

if (newptr == oldptr) {  // did it really move?

The use of oldptr here is technically undefined behavior.  We never hold the two pointers simultaneously; we have traded one for the other and the transaction took place inside the realloc blackbox.
We can capture a printed image:
char oldptr_txt[64], newptr_txt[64];
snprintf(oldptr_txt, sizeof oldptr_txt, "%p", (void *) oldptr);
newptr = realloc(oldptr, size);
snprintf(newptr_txt, sizeof newptr_txt, "%p", (void *) newptr);

if (strcmp(oldptr_txt, newptr_txt) == 0) {
  // almost certainly stayed in place
} else {
  // almost certainly moved
}


text:
Q: How to calculate 2 months from today using php date I have the following code:
$date = date("Y-m-d");

This results in 2013-10-26.
What I need is to obtain the date for two months back. So, for this example, it would be 2013-08-26.
How do I accomplish this?

A: date function only formats given timestamp (second parameter which is current time by default).
You should use strtotime function to get date 2 months back adn then pass to date as second parameter.
Try this:
$date = date("Ymd",strtotime("-2 months"));

As you can see, strtotime function's parameter is very flexible. You can read more about valid values for strtotime in PHP's doc. Take a look here.

A: DateTime example:
echo date_create()->modify('-2 month')->format('Y-m-d');

Demo.

A: $date = date("Y-m-d",strtotime(" -2 months"));


text:
Q: ado connection pooling connected vs disconnected Before jumping the gun and marking duplicate, I've searched an have not had luck with a clear answer.
Background:
A co-worker and I had a discussion on datareader vs dataset with me on the datareader side.
What it boils down to is that I like the datareader because its lightweight, and my co-worker likes the dataset because its disconnected.
His reasoning is that since the dataset is disconnected, .net will fill the dataset and release the connection back into the pool (our server gets millions of hits a day).
He also stated that even if I wrap the sqlconnection and datareader in a using statement, the connection doesn't get released right away because the using statement is just doing a try catch finally and calling the connection.close and dispose anyway, which is bad because we have to wait for the garbage collector to run, and who knows how long that will take. In the meantime, the connection doesn't get returned to the pool.
My question:
Is he right? And will using the datareader cause the connections in the pool to shrink until garbage collection runs?

A: What he is saying actually makes sense, because i have experienced it with a project which is currently running in my company, in it although the developers have written the code to close the connection but still connections are open and many a times we get connection pool errors that's why we have started using disconnected architecture in all the new projects.


text:
Q: how to save an image of tif format by converting into jpg during fileupload? This is the code I have used to upload a file and save it in a folder, but the problem is with .tif images, as browsers does not support them.
Because of this, I want to convert the image to .jpg before saving to folder.
This is my current code:
 Try
        Dim j As Integer = 0
        Dim hfc As HttpFileCollection = Request.Files
        Dim PathName As String
        For i As Integer = 0 To hfc.Count - 1
            Dim hpf As HttpPostedFile = hfc(i)

            If hpf.ContentLength > 0 Then

                  PathName = System.IO.Path.GetFileName(hpf.FileName)
                Dim QuoteNumber As String = objQuoteParent.QuoteTabImage.ToList().Item(i).QuoteNumber
                Dim FName As String = QuoteNumber + "_QOT_" + (i.ToString()) + PathName
                Dim FileName As String = "~/UploadedImages/" + FName

               'what should i use before saving to convert a tif file to jpg then save?

                hpf.SaveAs(Server.MapPath("~/UploadedImages\") & FName)

            End If
        Next
    Catch generatedExceptionName As Exception

        Throw
    End Try

before saving the file into folder I want to check if any .tif is uploaded if yes then first convert it to jpg then save it into the folder.

A: Found This Function on Google TIFF image <--> JPEG image converter
Public Shared Function ConvertTiffToJpeg(fileName As String) As String()
    Using imageFile As Image = Image.FromFile(fileName)
        Dim frameDimensions As New FrameDimension(imageFile.FrameDimensionsList(0))

        ' Gets the number of pages from the tiff image (if multi-page)
        Dim frameNum As Integer = imageFile.GetFrameCount(frameDimensions)
        Dim jpegPaths As String() = New String(frameNum) {}

        Dim frame As Integer = 0
        While frame < frameNum
            ' Selects one frame at a time and save as jpeg.
            imageFile.SelectActiveFrame(frameDimensions, frame)
            Using bmp As New Bitmap(imageFile)
                jpegPaths(frame) = [String].Format("{0}\{1}{2}.jpeg",
                                   Path.GetDirectoryName(fileName),
                                   Path.GetFileNameWithoutExtension(fileName), frame)
                bmp.Save(jpegPaths(frame), ImageFormat.Jpeg)
            End Using
            System.Math.Max(System.Threading.Interlocked.Increment(frame), frame - 1)
        End While

        Return jpegPaths
    End Using
End Function

A: I got the solution.
I used the below code:
   My.Computer.FileSystem.RenameFile(filepath, Name + ".jpg")

This code is able to convert .tif to jpg but after converting i am unable to display the image file.


text:
Q: User and Session info from within JAVA UDF Oracle 11g I wish to get user info just like provided by
SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') FROM DUAL;

and
SELECT SYS_CONTEXT ('USERENV', 'OS_USER') FROM DUAL;

inside a JAVA UDF for Oracle 11g without making a JDBC connection and running these queries to query from DUAL.
I tried System.getProperty("user.name") to read the current OS_user through jvm but I think we are not allowed to fetch information outside the database environment.
More generically, problem statement is to fetch information about the user who has logged into database and using that java UDF (where we need to determine these information) ?

A: I have found solution to above problem by using the "jdbc:default:connection" which is an internal connection maintained by database itself which is always available. Notice I did not do conn.close(); in the end because this is a shared stream which once closed is closed for all database clients.
public static String doSQL() throws SQLException {
    String result = new String();
    String q1 = "SELECT SYS_CONTEXT('USERENV','SESSION_USER') FROM DUAL";
    Connection conn =
            DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement ps = conn.prepareStatement(
            q1
    );
    ResultSet rs = ps.executeQuery();
    while (rs.next())
        result = rs.getString(1);
    return "my udf says"+result;
}