Q: Writing a P2P chat application in Python Is it possible to write a peer-to-peer chat application in Python?
I am thinking of this from a hobbyist project point-of-view. Can two  machines connect to each other directly without involving a server? I have always wondered this, but never actually seen it implemented anywhere so I am thinking there must be a catch somewhere.
PS: I intend to learn Twisted, so if that is involved, it would be an added advantage!

A: Yes. You can do this pretty easily with Twisted. Just have one of the peers act like a server and the other one act like a client. In fact, the twisted tutorial will get you most of the way there.
The only problem you're likely to run into is firewalls. Most people run their home machines behind SNAT routers, which make it tougher to connect directly to them from outside. You can get around it with port forwarding though.

A: Yes, each computer (as long as their on the same network) can establish a server instance with inbound and outbound POST/GET.

A: I think i am way too late in putting my two bits here, i accidentally stumbled upon here as i was also searching on similar lines. I think you can do this fairly easily using just sockets only, however as mentioned above one of the machines would have to act like a server, to whome the other will connect.
I am not familiar with twisted, but i did achieved this using just sockets. But yes even i am curious to know how would you achieve peer2peer chat communication if there are multiple clients connected to a server. Creating a chat room kind of app is easy but i am having hard time in thinking how to handle peer to peer connections.


Q: symfony2 doctrine multiple update / transaction I'm working on a Symfony2 project with doctrine and have some problems with a SQL update. I have a database table where all entries have a position attribute, since the order is important and changeable by the customer. Finally, I decided to save the position as simple integer values, without any implemented logic, and update any affected rows.
So, I wrote this function
public function swapCookingStepAction($recipeId, $posBefore, $posAfter) {
    $em = $this->getDoctrine()->getManager();
    $swappedEntry = $em->getRepository('BarraFrontBundle:CookingStep')->findOneBy(array('recipe'=>$recipeId, 'position'=>$posBefore));
    $swappedEntry->setPosition($posAfter);

    if ($posBefore < $posAfter)
        $steps = $em->getRepository('BarraFrontBundle:CookingStep')->decreaseBetweenPos($recipeId, $posBefore+1, $posAfter);
    else
        $steps = $em->getRepository('BarraFrontBundle:CookingStep')->increaseBetweenPos($recipeId, $posAfter, $posBefore-1);

    $em->flush();
    return new Response("ok?");
}

and this repository with doctrine
class CookingStepRepository extends EntityRepository {
public function increaseBetweenPos($recipeId, $posBefore, $posAfter)
{
    $query = $this->createQueryBuilder('c')
        ->update()
        ->set('c.position', 'c.position +1')
        ->where('c.recipe = :recipeId')
        ->andWhere('c.position BETWEEN :posBefore AND :posAfter')
        ->setParameter('posBefore', $posBefore)
        ->setParameter('posAfter', $posAfter)
        ->setParameter('recipeId', $recipeId)
        ->getQuery();

    return $query->getResult();
}

public function decreaseBetweenPos($recipeId, $posBefore, $posAfter)
{
    $query = $this->createQueryBuilder('c')
        ->update()
        ->set('c.position', 'c.position -1')
        ->where('c.recipe = :recipeId')
        ->andWhere('c.position BETWEEN :posBefore AND :posAfter')
        ->setParameter('posBefore', $posBefore)
        ->setParameter('posAfter', $posAfter)
        ->setParameter('recipeId', $recipeId)
        ->getQuery();

    return $query->getResult();
}}

The queries are build as wished but unfortunately I get this primary key error
An exception occurred while executing 'UPDATE CookingStep SET position = position - 1 WHERE recipe = ? AND (position BETWEEN ? AND ?)' with params ["6", 2, "2"]:

Integrity constraint violation: 1062 Duplicate entry '1-6' for key 'PRIMARY'

for params (6, 1, 2). I tried to work with a transaction but this didn't change anything.
Could you help me, guys?
UPDATE
Just added a 4th parameter at the repository function and could remove the 2nd function.
If I change the primary key for tests, the code & update works very well.


Q: How to show first page of the route without page number on Next JS I've been trying to create a blog page which contains pagination with numbers.
My pages folder is like below :
src
-pages
--blog
---[id].tsx

I am able to render all static pages with getStaticPaths  function Next provides.
The issue is I would like to show first page as /blog instead of  /blog/1.
How can I push the route /blog when there is /blog/1 content?

A: There could be (1) client side routing and (2) server side routing
create new page blog/index.tsx
src
-pages
--blog
---[id].tsx
---index.tsx

and redirect to /blog/1 in index.tsx(client side routing)
import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function Blog() {

  useEffect(() => {
    router.push('/blog/1')
  }, [])

  return
Redirecting...

}

server side route
import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function Blog() {

  useEffect(() => {
    router.push('/blog/1')
  }, [])

  return
Redirecting...

}

export const getServerSideProps = ({ req, res }) => {
    res.writeHead(302, { Location: "/blog/1" });
    res.end();
    return {
        props: {}
    }
}


Q: Prevent text keyboard input on Android/chrome mobile [web] I have a textarea with keyDown listener
<textarea onKeyDown={handleKeyDown}></textarea>

And the handleKeyDown function:
const handleKeyDown = event => event.preventDefault()

When I typing from windows PC, Chrome Version 90.0.4430.212 (Official Build) (64-bit) everything works perfect: text is not appearing in textarea.
When I typing from mac, chrome 90 everything works perfect too.
But when I grab my Android Phone (Samsung, Android 11), open Mobile Chrome (90.0.4430.210) and start typing, text IS appearing in textarea. And the worst thing is that the only mention about this bug I found is this question, which will be referenced by bots when marking my question as duplicate. There is no answer: maxlength attribute not working anymore.
This is the list of things I tried to prevent mobile chrome from input:

*

*Maxlength = 0 (no effect at all)

*readOnly (=disabled, I need focus and selection)

*blocking onKeyUp, onKeyPress, onPaste, onCut, onInput

I also tried to manually set value of textarea to '' but if I set a listener which does this, my textarea become completely broken: each time I press key on keyboard, it duplicates all previous content.
My question is how to prevent input, maybe there is a hack or trick? Please don't send me to android report forums where this bug may be discussed or another questions...

A: I would first check to see if the events are working when adding eventlisteners. There must be a way to handle key events on Android:
<textarea id="mytextarea"></textarea>

let mytextarea = document.getElementById('mytextarea');

mytextarea.addEventListener('keydown', (event) => {
  console.log(event.code);
});

If this is not working; you asked for a hack or trick: try the focus and blur events, then you could run a function on interval that clears the textarea. Note that this blocking trick is something that goes against good user experience conventions, so should be considered a hack/trick for sure ;-)
<textarea id="mytextarea"></textarea>

let int1;

let mytextarea = document.getElementById('mytextarea');

mytextarea.addEventListener('focus', () => {
  clearInterval(int1);
  int1 = setInterval(() => {
    mytextarea.value = '';
  }, 10)
});

mytextarea.addEventListener('blur', () => {
  clearInterval(int1);
});

A: Instead of using event.key or event.code properties of keypress (keyup, keydown) event, I have used event.inputType, event.data of update event and added few restricting attributes to the input tag to overcome 'smartness' of mobile keyboard app. It is an ugly hack but worked for my purpose.
HTML:
<textarea id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" ></textarea>
</div>

JS:
var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);

function do_on_input(e) {

  if( e.inputType == "insertText"){
    console.log( e.data );
  }

  if( e.inputType == "deleteContentBackward"){
    console.log('Backspace');
  }

  if( e.inputType == "insertCompositionText"){
    // without restrictive attribbutes you will need to deal with this type events
  }

}


Q: mysql query using the wrong indexes I have some optimization problems with some of my queries in a mysql database. After I build my application I am trying to optimize using mysqltuner and explain, to find non indexed queries. This is a query that is running often and reports that is not using the index :
SELECT  count(*) AS rangedandselling
    FROM
      ( SELECT  DISTINCT `store_formats`.`Store Name`
            FROM  (`eds_sales`
                    JOIN  `store_formats`
                      ON (`eds_sales`.`Store Nbr` = `store_formats`.`Store Nbr`)
                  )
            WHERE  `eds_sales`.`Prime Item Nbr` = '4'
              AND  `eds_sales`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME)
                                          AND CAST('2016-07-21' AS DATETIME)
              AND  `store_formats`.`Format Name` IN ('format1','format2')
              AND  `store_formats`.`Store Name` IN (
                SELECT  DISTINCT `store_formats`.`Store Name`
                    FROM  (`eds_stock`
                            JOIN  `store_formats`
                              ON (`eds_stock`.`Store Nbr` = `store_formats`.`Store Nbr`)
                          )
                    WHERE  `eds_stock`.`Prime Item Nbr` = '4'
                      AND  `eds_stock`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME)
                                                  AND CAST('2016-07-21' AS DATETIME)
                      AND  `store_formats`.`Format Name` IN ('format1','format2')
                      AND  `eds_stock`.`Curr Traited Store/Item Comb.` = '1' )
      ) t

This is the explain output : https://tools.mariadb.org/ea/pyb3h
Although I have indexed the columns involved in the joins and lookups, it looks like it is picking another index. this other index is called uniqness, and is composed of 6 different columns in the source columns that I use for inserts (the combination of those columns is the only thing that makes a row unique, hence the name I gave.). I then made sure I have indexes for the other columns and I can see them in the explain. I am not sure why this happens, can someone help?
Any ideas on optimizing this query?
Here is the explain for those that the link above does not work :
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+---+---+---+---+---+---+---+---+---+---+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 167048 |  |
| 2 | DERIVED | eds_sales | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 4 | const | 23864 | Using where; Using index; Using temporary |
| 2 | DERIVED | store_formats | ref | Store Nbr,Store Name,Format Name | Store Nbr | 5 | equidata.eds_sales.Store Nbr | 1 | Using where |
| 2 | DERIVED | <subquery3> | eq_ref | distinct_key | distinct_key | 84 | func | 1 | Distinct |
| 3 | MATERIALIZED | store_formats | ALL | Store Nbr,Store Name,Format Name | NULL | NULL | NULL | 634 | Using where; Distinct |
| 3 | MATERIALIZED | eds_stock | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 8 | const,equidata.store_formats.Store Nbr | 7 | Using where; Distinct |
+---+---+---+---+---+---+---+---+---+---+

I am also posting the related tables structure :
--
-- Table structure for table `eds_sales`
--
CREATE TABLE `eds_sales` (
  `id` int(12) NOT NULL,
  `Prime Item Nbr` int(12) NOT NULL,
  `Prime Item Desc` varchar(255) NOT NULL,
  `Prime Size Desc` varchar(255) NOT NULL,
  `Variety` varchar(255) NOT NULL,
  `WHPK Qty` int(5) NOT NULL,
  `SUPPK Qty` int(5) NOT NULL,
  `Depot Nbr` int(5) NOT NULL,
  `Depot Name` varchar(255) NOT NULL,
  `Store Nbr` int(5) NOT NULL,
  `Store Name` varchar(255) NOT NULL,
  `EPOS Quantity` int(5) NOT NULL,
  `EPOS Sales` float(4,2) NOT NULL,
  `Date` date NOT NULL,
  `Client` varchar(255) NOT NULL,
  `Retailer` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `eds_sales`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Prime Item Desc`,`Prime Size Desc`,`Variety`,`WHPK Qty`,`SUPPK Qty`,`Depot Nbr`,`Depot Name`,`Store Nbr`,`Store Name`,`Date`,`Client`) USING BTREE,
  ADD KEY `Prime Item Nbr` (`Prime Item Nbr`),
  ADD KEY `Store Nbr` (`Store Nbr`);

Table structure for table eds_stock
CREATE TABLE `eds_stock` (
  `Prime Item Nbr` int(12) NOT NULL,
  `Prime Item Desc` varchar(255) NOT NULL,
  `Prime Size Desc` varchar(255) NOT NULL,
  `Variety` varchar(255) NOT NULL,
  `Curr Valid Store/Item Comb.` int(12) NOT NULL,
  `Curr Traited Store/Item Comb.` int(12) NOT NULL,
  `Store Nbr` int(12) NOT NULL,
  `Store Name` varchar(255) NOT NULL,
  `Curr Str On Hand Qty` int(12) NOT NULL,
  `Curr Str In Transit Qty` int(12) NOT NULL,
  `Curr Str On Order Qty` int(12) NOT NULL,
  `Curr Str In Depot Qty` int(12) NOT NULL,
  `Curr Instock %` int(12) NOT NULL,
  `Max Shelf Qty` int(12) NOT NULL,
  `On Hand Qty` int(12) NOT NULL,
  `Date` date NOT NULL,
  `Client` varchar(255) NOT NULL,
  `Retailer` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `eds_stock`
  ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Store Nbr`,`Date`,`Client`,`Retailer`),
  ADD KEY `Prime Item Nbr` (`Prime Item Nbr`),
  ADD KEY `Store Nbr` (`Store Nbr`),
  ADD KEY `Curr Valid Store/Item Comb.` (`Curr Valid Store/Item Comb.`);

Table structure for table store_formats
CREATE TABLE `store_formats` (
  `id` int(12) NOT NULL,
  `Store Nbr` int(4) DEFAULT NULL,
  `Store Name` varchar(27) DEFAULT NULL,
  `City` varchar(19) DEFAULT NULL,
  `Post Code` varchar(9) DEFAULT NULL,
  `Region #` int(2) DEFAULT NULL,
  `Region Name` varchar(10) DEFAULT NULL,
  `Distr #` int(3) DEFAULT NULL,
  `Dist Name` varchar(26) DEFAULT NULL,
  `Square Footage` varchar(7) DEFAULT NULL,
  `Format` int(1) DEFAULT NULL,
  `Format Name` varchar(23) DEFAULT NULL,
  `Store Type` varchar(20) DEFAULT NULL,
  `TV Region` varchar(12) DEFAULT NULL,
  `Pharmacy` varchar(3) DEFAULT NULL,
  `Optician` varchar(3) DEFAULT NULL,
  `Home Shopping` varchar(3) DEFAULT NULL,
  `Retailer` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `store_formats`
  ADD PRIMARY KEY (`id`),
  ADD KEY `Store Nbr` (`Store Nbr`),
  ADD KEY `Store Name` (`Store Name`),
  ADD KEY `Format Name` (`Format Name`);

A: CAST('2016-07-14' AS DATETIME) -- the CAST is not needed; '2016-07-14' works fine.  (Especially since you are comparing against a DATE.)
IN ( SELECT ... ) is inefficient.  Change to a JOIN.
On eds_stock, instead of
INDEX(`Prime Item Nbr`)

have these two:
INDEX(`Prime Item Nbr`, `Date`)
INDEX(`Prime Item Nbr`, `Curr Traited Store/Item Comb.`, `Date`)

INT is always a 4-byte number, even if you say int(2).  Consider switching to TINYINT UNSIGNED (and other sizes of INT).
float(4,2) -- Do not use (m,n); it causes an extra rounding and my cause undesired truncation.  Either use DECIMAL(4,2) (for money), or plain FLOAT.
Bug??  Did you really want 8 days, not just a week in
AND `Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME)

I like this pattern:
AND `Date` >= '2016-07-14'
AND `Date`  < '2016-07-14' + INTERVAL 1 WEEK

Instead of two selects
SELECT  count(*) AS rangedandselling
    FROM ( SELECT  DISTINCT `store_formats`.`Store Name` ...

One select will probably work (and be faster):
SELECT COUNT(DISTINCT `store_formats`.`Store Name`) AS rangedandselling ...

Once you have cleaned up most of that, we can get back to your question about 'wrong index', if there is still an issue.  (Please start a new Question if you need further help.)


Q: Django: Form submission in ajax style without csrf token I am new to django. Suppose I have a form and I would like to submit a file to the server in ajax.
I notice that the server has HTTP 403 error when I don't specify the csrf token in the post statement (correct behaviour), but somehow the file can still be able to upload to the server...
Here is my sample code:
models.py (include model and form):
from django.db import models
from django.forms import ModelForm

# Create your models here.
class Dummy(models.Model):
    myfile = models.FileField(upload_to='temp')

class DummyForm(ModelForm):
    class Meta:
        model = Dummy
        fields = ['myfile',]

views.py:
# Create your views here.
class TestFormView(View):
def get(self, request):
    form = DummyForm()

    context = { 'form' : form }
    print form
    return render(request, 'testform.html', context)

def post(self, request):
    print request.FILES
    form = DummyForm(request.POST, request.FILES)
    print form.is_valid()
    print form.errors
    print form.is_bound
    if form.is_valid():
        form.save()

    print Dummy.objects.all().count()
    return render(request, 'testform.html')

testform.html:
<form id="myForm" action="testform/" method="post" enctype="multipart/form-data">
{% csrf_token %}
 <input id="id_myfile" type="file" size="60" name="myfile">
 <input type="submit" value="Ajax File Upload">
</form>

0%

Of course if I put the csrf token in the $post function, I get HTTP 200.
My concern is that will this create security hole because it looks like anyone can upload files to the server?
Thanks!


Q: Cannot Start Weblogic Managed Server, We are running Weblogic 7sp6. We have a working single node cluster with an Admin and two Managed servers. We are re-creating a 2nd standalone cluster on a 2nd server. We reinstalled Weblogic and have copied over all the configuration files to make thing. Its the same on both clusters. We changed all the references to IP and hostnames. We have used this method before without problems.
In the current case I can startup the Admin which listens on port 7001,7002. But when I try and startup either of the Managed servers it tells me that myserver1/2 is already up. (Managed Servers). I confirmed that myserver is configured to use port 7012,7013 and I cannot find any port conflicts especially because these exact ports worked on the first cluster. Any ideas of what else to look at? I have logged in the admin console and can see the ports are all unique. Thanks

A: The startmanagedweblogic.cmd file had the wrong IP for the Admin IP.


Q: Making Mac shortcuts (e.g. Cmd-C) work on linux Is there a way to map Cmd+C to Copy in linux? (instead of Ctrl+C)
Would be nice if I could also have the emacs style ones, like Ctrl+B to move left by one character.

A:
Is there a way, on Linux/X, to map certain key combos to other key combos?

In the tradition of all open source projects, there's not a way, there are several.  At the lowest level you've got kernel keybindings, which is probably not what you want.  At the X server level you've got xkb with its myriad utilities.  And then it seems that every window manager - gnome, kde, xfce or other - also has a keymapping utility.   xkb seems to have lots of utils and such around it, and is likely more complete than any random window manager's keymapping utils, so I'd look at that first.

A: KDE 3 is probably the most flexible here; there's a pre-defined keyboard shortcut scheme named "Mac Scheme".  You can set it through KControl Control Center > Regional & Accessibility > Keyboard Shortcuts or kcmshell keys and it will have effect on almost all KDE applications immediately.  You might miss some of those Emacs-like "Ctrl-*" shortcuts that OS X has, but that aside, it works well (as long as your X modifiers are mapped correctly).  And if it's not to your liking, it's easily customizable.
You can also set Control Center > Desktop > Behavior to enable a Mac OS-like menubar; all KDE applications will then share a menubar at the top of the screen instead of being individually attached to each window.

A: Update 02/03/2020
Kinto has now been rewritten in C for Ubuntu/Debian systems using x11. It also uses json config files, making it easier to manage and extend to other applications than just terminals. The app no longer maps to Super in the Terminal apps, it will now properly map to Ctrl+Shift to create the exact same feel as having a Cmd key.
Please checkout the latest release.
https://github.com/rbreaves/kinto
The main change to allow for the Super = Ctrl+Shift change is in this symbols file.
default partial xkb_symbols "mac_levelssym" {
    key <LWIN> {
      repeat= no,
      type= "ONE_LEVEL",
      symbols[Group1]= [ Hyper_L ],
      actions[group1]=[ SetMods(modifiers=Shift+Control) ]
    };
    key <RWIN> {
      repeat= no,
      type= "ONE_LEVEL",
      symbols[Group1]= [ Hyper_R ],
      actions[group1]=[ SetMods(modifiers=Shift+Control) ]
    };
};

Pjz's answer is correct in saying that an xkb solution would be ideal, sadly few have taken that route, most likely due to the difficulty of learning xkb and it seems many have gone the route of using Xmodmap files which is being deprecated while we are on our way to Wayland.
This answer may be several years too late, but here it is any ways.
Kinto is a tool I recently created that will address this problem and does so by using xkb and by listening to what app you are currently using, as it also changes the keymap while using terminals so the mac like experience can be consistent.
https://github.com/rbreaves/kinto
https://medium.com/@benreaves/kinto-a-mac-inspired-keyboard-mapping-for-linux-58f731817c0
Here's a Gist as well, if you just want to see what is at the heart of it all, it will not alternate your keymap when needed though. The Gist also does not include custom xkb keymap files that setup macOS style cursors/word-wise manipulations that use Cmd and the arrow keys.
https://gist.github.com/rbreaves/f4cf8a991eaeea893999964f5e83eebb
Edit: Posting the contents of the gist as well. I cannot realistically post the contents of Kinto.
# permanent apple keyboard keyswap
echo "options hid_apple swap_opt_cmd=1" | sudo tee -a /etc/modprobe.d/hid_apple.conf
update-initramfs -u -k all

# Temporary & instant apple keyboard keyswap
echo '1' | sudo tee -a /sys/module/hid_apple/parameters/swap_opt_cmd

# Windows and Mac keyboards - GUI (Physical Alt is Ctrl, Physical Super is Alt, Physical Ctrl is Super)
setxkbmap -option;setxkbmap -option altwin:ctrl_alt_win

# Windows and Mac keyboards - Terminal Apps (Physical Alt is Super, Physical Super is Alt, Physical Ctrl is Ctrl)
setxkbmap -option;setxkbmap -option altwin:swap_alt_win

#
# If you want a systemd service and bash script to help toggle between
# GUI and Terminal applications then look at project Kinto.
# https://github.com/rbreaves/kinto
#
# Note: The above may not work for Chromebooks running Linux, please look
# at project Kinto for that.
#
# If anyone would like to contribute to the project then please do!
#

A: You'll get almost all of the way there if you switch Cmd and Ctrl

A: xmodmap -e "keycode 63 = Control_L"
That way Cmd will be Control. No other keys will be swapped
Edited: I forgot the "-e"


Q: TBB error when compiling I have the following piece of code that i am trying to execute
#include <iostream>
#include <cstring>
#include "tbb/tbb.h"

using namespace std;
using namespace tbb;

class Accumulate{
    float& arr;
    float* src;

    public:
    Accumulate(float& _arr, float* _src)
    :arr(_arr), src(_src){}
    void operator() (int i) const{
        arr += src[i];
    }

};

int main(int argc, const char * argv[]) {
    float arr[4] = {1,3,9,27};
    float sum = 0;
    parallel_for(0, 4, Accumulate(sum, arr));
    cout<< sum << endl;
}

I am trying to make use of parllel_for to calculate the sum and this requires the tbb library. I downloaded the source tbb directory and pasted it in my xcode project directory.
When i try to compile the above code, i seem to get the following error
'tbb/internal/_flow_graph_types_impl.h' file not found
I am not sure what i am missing, please advise

A: I can see this file in TBB repo: https://github.com/01org/tbb/blob/tbb_2017/include/tbb/internal/_flow_graph_types_impl.h
Please make sure that your installation of TBB is not damaged.
Off-topic advice, there is a data-race in your program on sum and you can use lambda instead of explicit functor:
int main(int argc, const char * argv[]) {
    float arr[4] = {1,3,9,27};
    atomic<float> sum = 0; // fixing data-race. Still, it's not recommended way
    parallel_for(0, 4, [&](int i){
        sum += arr[i];
    });
    cout<< sum << endl;
}

See also tbb::parallel_reduce in order to make this code correct, clean, and efficient.


Q: UIViewControllers not receiving orientation notifications I've spent the last hour or so trying to work out why not all my UIViewControllers are receiving orientation change notifications.
I've got a subclassed UIViewController attached to the window, that internally creates a few other UIViewControllers to manage smaller portions of the screen which are re-used elsewhere in the application I'm building.
The problem is, only the UIViewController attached to the window is receiving the orientation change notifications.
The other UIViewControllers aren't firing their - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration methods.
I'm assuming it's expected behaviour, and I can't seem to find anything mentioning it in the docs.
Is there a way to make sure all active UIViewControllers are getting orientation changes? Or does the parent view controller have to tell it's children when changes are occurring?
Cheers.

A: Are all your view controllers returning YES to shouldAutorotateToInterfaceOrientation: ? If so, I suggest to pass the interface orientation messages from the parent to the children viewControllers, as you suggested.
I have been doing so before and had no problems with that approach so far.


Q: applying a class to a div I have a css which has some attribute as follows:
.ts{
    background-image: url("images/xyz/pb.gif");
    background-repeat: no-repeat;
    padding:0,0,0,20px;
    display:none;
}

.ts.visible{
    display: inline;
}

Now i want to apply the this style to a div in my html page.How cna i do it.I dont know css

A: Yep, what they said. Also, if you want to assign more than one class, use a space to separate them, like so:
.
Edit:
Also, use spaces to separate the "padding" values, like this: padding: 0 0 0 20px;, or just use padding-left: 20px;.

A: You can use it like this:
...

But I strongly recommend you take a look at css here, it's not that hard.

A: Just give that
 a class attribute, like this:

If you want it to have both classes, use a space between like this:

A: You'd simply do:

Contents of div

That said, I very much suspect that's not the answer you're looking for. :-)


Q: Storing similar objects in a database I am developing an a house renting/selling application, it will allow users to post rental and houses on sale. My concern is the two objects have some similar and different attributes,for example here is a house on rent can have the following attributes `
public class RentalHouse extends Property{

private int numOfBedrooms;
private int payMonthsInAdvance;
private double securityDeposit;
private double rentals;
private String dayOfVacancy;

}

Whilst a house on sale can have the following attributes
public class SaleHouse extends Property{

private int numOfBedrooms;
private double price;

}

public class Property {

private long id;
private String title;
private String description;
private ArrayList<String> images;
private String province;
private String area;

}

Now here is my question; is it good design to have 2 tables for one for rental houses the other for houses on sale? and what would you advice?


Q: What partition key to choose in cosmos db with little data and one customer per database? We’re developing a personnel management system based on blazor and Cosmos DB serverless. There will be one customer per database and around 30 “docTypes”. The biggest categories by number and data volume are "users" and "employees". When we query we get all data of users and employee at once. So it can be several thousand. The other doctypes are much smaller an less frequently queried.
The volume of data per customer will not exceed 5 GByte. The most frequent queries are to 3 docTypes.
Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key?
thanks

A: Based on the information you supplied it sound like docType is a good property to use as partition key, since it can be used to avoid cross partition queries. Especially since you state this will be often be used in your queries. With the max size you stated it will also be unlikely to cause you issues as a single partition can contain up to 20GB of data.
One thing to watch out for is Hot Partitioning. You state that your users partition might be a lot bigger than others. That can result into one partition doing all of the lifting while the others sit mostly idle which results and causing inefficiëncy of your total throughput.
On the other side it won't really matter for your use case. Since none of the databases will exceed that 5GB you'll always stay within a single partition, but it's always good though to think about it beforehand; As situations may change and you end up with a database that does split into partitions.
Lastly I would never use a single partition for all data. It has no benefits. If you have no properties that could serve as partition key then id is the better choice (so a logical partition per document). It won't hit storage limitations and evenly distributes throughput between partitions.

A: I would highly recommend you first take a look at this segment of the Data Modelling & Partitioning presentation by Thomas Weiss, Cosmos DB program manager. In my view it's one of the best resources to understand how to think about partitioning.
Do agree with David Makogon that you didn't provide enough data. For instance, we know there are 30 doc types per single database - given cosmosdb database uses containers, I actually expect each docType to have its own container - contrary to what you wrote:

Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key?

Which suggests you want to use a single container for all your data. I wouldn't keep users and employees as documents in the same container. They are separate domains and deserve their own container.
See Azure docs page on Partition Strategy and subsequent paragraph about access patterns. The recommendation is to:

Choose a partition key that enables access patterns to be evenly spread across logical partitions.

In the access patterns section, the good practice mentioned is to separate data into hot, medium and cold data and place it into their own containers. One caveat is, that according to this page the max number of containers per database with shared throughput is 25.
If that is not possible, and all data has to end up in a single container, then docType seems to be the right partition key, because your queries will get data by docType if I understood correctly.
As 404 wrote, you want to avoid Hot Partitioning i.e. jamming most of documents in a container into a single or a few logical partitions. Therefore you want to choose a partition key based on most frequent operations.


Q: MethodNotAllowedHttpException laravel 4.2 error here is my ContactController.php:
public function destroy($id){
    $contact = Contact::find($id);
    $contact->delete();
    return Redirect::to('http://localhost:8000/contactsview');
}

Here is my rountes.php
Route::delete('/contactsview/destroy/{id}', array('uses'=>'ContactController@destroy'));

Here is my index.blade.php:
{{ Form::open(array('url'=>'/contactsview/delete/'.$contact->id, 'method'=>'DELETE', 'style'=>'display:inline;')) }}
<!-- {{ Form::hidden('id', $contact->id) }} -->
{{ Form::submit('Delete') }}
{{ Form::close() }}

What did I do wrong?

A: Try the form with this instead, passing in the $contact->id as a param rather than directly in the URL:
{{ Form::open(array('method' => 'DELETE', 'action' => array('ContactController@destroy', $contact->id )) }}


Q: Software License which discriminates on 'ethical' grounds I've spent some time reading the common copyleft and permissive software licenses. Is there a license which allows the creator of an application or algorithm to broadly specify who may use/distribute the product based on their own personal prejudices?
I understand that people use dual licenses to force commercial entities to pay for the permissive license or be forced to distribute sourse code for their projects, but I was thinking something more along the lines of, for example, "This code can be freely used, modified, and distributed by any entity not involved in Industry x [which I have deemed unworthy of the use of my free software]".
I have been unable to find any such licenses or license templates, and I would have thought that at least some programmers would be concerned about the ethical implications of their products. Is it possible to create an AI pathfinding algorithm and ensure it would not end up guiding an armed drone, or an Arctic ice floe model and ensure it would not end up being used for offshore oil drilling, while still using a permissive-style license?

A: I work for a company with a mandate to develop software products for progressive charities. We created some libraries that we wanted to open source and, like the OP, we weren’t satisfied with the licenses that we could find.
We created the Just World License so that, at the very least, our code wouldn’t be used by those that are working against the goals of the charities we support. (Here’s an article explaining our reasons behind it)
Below I’ll address some of the objections to ethical licenses raised in comments and answers. In doing so I’m going to draw comparison to the GPL because it is also an example of a license that's drawn from a strong ideological viewpoint and so is instructive in how a license is more than just a legal document, and the aspects of it we’ve come to accept.
Why (not) ethical?
Many of the objections I've read are related to the enforceability of such a license, but I would argue that the purpose of an ethical license is not to enforce it in a court. In fact, most legal documents you really don't want to be testing in court - it's expensive and painful. Yes, you should make them clear and unambiguous, but most people don't draft legal documents with the primary goal being to take the other party to court.
As people have (rightly) pointed out, if a big company wants to use your software despite restrictions, they likely have the resources to bury you in legal paperwork.
But, this is no different from the GPL, and the GPL, too, wasn’t written so that FOSS developers could haul big companies to court for misusing open source code. Yes, it’s legally specific and possible to enforce, but that wasn’t the primary purpose the authors had in mind for it. They created the GPL to spread an idea - the idea that software and it’s source should be freely shared.
Likewise, in creating an ethical license, we want to spread an idea - that our software should be used for the betterment of the world, and that we as developers can take responsibility for how our software is used.
Enforceability
That being said, I would also argue that an ethical license can be enforced. Even with the extremely vague licensing terms of JSLint, IBM was sufficiently concerned about enforcement as to ask the author for express permission to use JSLint for evil.
Yes, big tobacco could use our code and keep quiet about it, but the fear of being discovered or whistle-blown and the possibility of enforcement is enough for most companies, even the ones doing bad things, to decide it’s not worth the risk and go and find some other code.
Restricting usage for illegal things is pointless
Agreed.
In writing an ethical license we decided not to exclude illegal acts for this reason, and also because some countries have really bad laws that restrict people’s freedoms in awful ways. If the activists working against those things want to use our software, they’ve got enough to worry about without worrying that we might show up and add a cease and desist to their troubles.
If it’s bad, there are laws to stop it
<insert obligatory video of lawmakers asking Mark Zuckerberg about sending an email over WhatsApp>
Our lawmakers are, unfortunately, among the slowest to move when it comes to responding to changing social norms, let alone technology. For starters, it’s 2018 and there are still products on shelves that are made by actual slaves.
Ethical cannot be defined
The world is not as grey as it’s often made out to be.
Our license would prevent people from using our software for (among other things) taking action that is known to ruin the state of the planet for future generations, exploiting slave labour, promoting racism, or hacking behavioural psychology to make people waste loads of their life clicking ads.
These aren’t exactly the trolley problem.
Ethics is subjective
Yes, but this isn't a bad thing.
Some of our most essential decisions are subjective. If you're interested, there's some really interesting stories of people who've had their emotional centres damaged in an accident and are no longer able to function even though their reason and objectivity is completely intact.
Less philosophically. The notion that it’s wrong to take FOSS software and improve it without releasing the changes is also a subjective position. This is a subjective viewpoint that forms a key part of the GPL and not everyone in the software development world can agree that it's a good thing, but this difference of opinion hasn't brought down the FOSS community yet ;-)
It would be inconvenient
Well, that’s kind of the point. If a company is writing software for ethically dubious acts, then an ethical license is meant to be an inconvenience.
The same could be said of some FOSS licenses. Some companies today are using tools like license checker because they don’t want GPL code in their products.
If every author threw in their own definition of ethics and we had loads of non-standard ethical licenses then this does become very arduous and inconvenient, but if, like we do now for general open source, we could agree on a handful of standard licenses there’s no reason it would be any less convenient.
Bad Companies will just write their own
Good. Let them waste their resources if they want to profit from harming people and our future.
I’m not going to kid myself that placing the small libraries I've released off limits is going to materially inhibit big evil corporations, but what if bigger projects did?
For example, Apache’s Hadoop is being used by oil and gas companies to help them operate more profitably at a time when they should be shutting their doors so we can avert a climate disaster.
If the Apache Foundation determined that such uses did not fall within the  public benefit that their mission envisions for their resources and decided to codify that in their license, the companies would have to turn to something else, maybe an expensive proprietary solution. This drag on the bottom line of a company that harms our future would be a good thing.
It's a new idea
All this said, the Just World License is a new idea. We think it's got legs, and we’d welcome feedback or pull requests to make it better.

A: There exist software projects that use a license like this. However, these would not be considered free licenses by the OSI definition.
More importantly, the enforceability of these licenses has been strongly questioned every time I've seen them mentioned, and they have never, to the best of my knowledge, been tested in court. Using such a license is unlikely to have more than symbolic value.
Part of the problem here is that such terms are incredibly vague, as Ixrec points out in his comment. Let's say you develop an algorithm that guides self-driving cars. Ethical? Probably. Then this algorithm is used to build trucks that drive on their own. Still ethical. And now these trucks are used to resupply military camps, or transport drugs; will you then say that this isn't allowed because your code is used in there? Maybe they're even used in human trafficking, which is definitely unethical, but how would you control for that? Require the truck manufacturers to also put a license on their trucks?
Finally, your average military or oil company has enough money to just take your idea and reimplement it, so if it's your algorithm you don't want used, you're out of luck anyway. And since military code (such a rocket or drone guidance software) is usually classified anyway, how would you know that your code was used?

A: There are some licenses that specifically prohibit military usage.
http://mindprod.com/contact/nonmil.html
"Open-source" licenses that explicitly prohibit military applications
The problem with those kinds of things, is they become incompatible with other licenses such as the GPL. So on the surface they might seam 'reasonable' but they can cripple the usage.
The CryEngine's license only allows for development of 'Games' and specifically forbids the following:

*

*military projects

*gambling;

*simulation (technical, scientific, other);

*science;

*architecture;

*pornography;

*Serious Games.

Serious games:

1.10. “Serious Games”, i.e. ‘games’ which are not developed for the sole purpose of entertainment but for purposes training, simulation, science, architecture etc.

Of course that is likely for business reasons rather than for ethical ones since they could get more money out of a military contractor for example and they would just need to get a different license. Also kind of crappy that educational games aren't allowed.

A: When you look at the current market, there are already licenses that have stipulations about what the software might be used for.

*

*Apple has a stipulation in their iTunes license which says you're not allowed to use it to develop nuclear weapons.

*the game Far Cry 2 has a stipulation in the license that you're not allowed to use it contrary to morality or laws in force.

*WordWeb has a license which states you're not allowed to use the free version if you've taken more than 4 flights in the past 12 months OR own/regularly drive an SUV, although that last stipulation has an exemption for educational institutions and the registered disabled that require an SUV for transport..

*Amazon AWS Lumberyard (a video game engine) has a license that restricts use of the software in various automation and military purposes, but with a stipulation that this restriction does not apply in the event of a zombie apocalypse. Here's how the license words it:

[...] The occurrence (certified by the United States Centers for Disease Control or successor body) of a widespread viral infection transmitted via bites or contact with bodily fluids that causes human corpses to reanimate and seek to consume living human flesh, blood, brain or nerve tissue and is likely to result in the fall of organized civilization.

There are probably a number of other licenses that have similarly weird clauses. So a license that discriminates based on ethical grounds would not be the first time a license has a weird stipulation..

A: Any license which restricts use of the software to certain purposes is by definition not a Free Software license. It is a violation of the very first of what GNU considers the four essential freedoms:

*

*The freedom to run the program as you wish, for any purpose (freedom 0).

You can find several in GNU's list of non-free software licenses, but frankly the world is chock full of non-free software licensees. A good example is the JSON license, which includes this:

The Software shall be used for Good, not Evil.

Note that any such license is incompatible with GPL and the LGPL. That means if anyone tries to use software using that license with GPL or LPGL software, the resulting work may not be legally distributed to anyone.
In general, I really, really hate having to pore through someone's homebrew software license to see if I can use their software. I have better things to do with my time. I've found there are 3 licenses that can be used for any purpose I would ever publicly release software:

*

*GPL - For software I don't ever want some company putting in their own closed-source product. I'm donating it for the public good, if you build on it then you should too (or keep it to yourself). You can still make money, you just can't close the sources.

*GPL with linking and inclusion exceptions - For libraries and APIs that I want to keep open, but allow people to use in closed-source programs. This means anyone can use the API even in proprietary projects. Many people think the LGPL allows this, but it doesn't quite.

*CC0 - I'm giving this away. Do whatever you want with it. This is the closest an American can legally get to Public Domain.

If you use something else, I'm already a little annoyed with you. If its obscure enough that it isn't on GNU's license list, so I have to analyze it myself, I'm triple annoyed. Usually its easier just to find some other software with a better license.
Note that anyone who is going to use your software for "evil" most likely won't care much about usage restrictions in your license either.

A: This question comes up fairly regularly in the free software community and this is understandable. People writing free software (often in their spare time) and donating it to the public normally do this because they want to make a difference for the better, not for the worse. So trying to ensure that your craft is not used in a way that you consider unethical is a natural thing to think about.
The Free Software Foundation clearly opposes attempts to use the software license to limit the ways people may use software, however. Richard Stallman wrote an article “Why programs must not limit the freedom to run them” where he explains why he is convinced that using software licenses to restrict usage of a piece of software to ethical applications is doomed to fail and would only hurt interoperability and limit the usefulness for legitimate users. I find his article very convincing and recommend of course that you read the original but I'm paraphrasing (with comments of mine) what I think are his main arguments here.

*

*Disallowing the software to be used for illegal activities is pointless at best. Those activities are always illegal, no matter what the license says. A license can only grant the users of the software rights that the copyright holder has. It is not written explicitly in his article but I conclude and agree that it would make more sense to campaign politically that immoral activities be made illegal instead.

*Disallowing the software to be used by states for immoral activities (RMS mentions torture as an example) is likely not going to be effective because most states have special legislation that allows them to do pretty much whatever they like as long as it is in the interest of national security. While I believe that this is somewhat exaggerated, it is certainly true that such legal exemptions for military usage exist in many states or could be passed should the legislative powers consider them desirable. What is probably more relevant is that you would have a hard time proving that your work is used at all without access to classified information and while copyright law is stretched by many players to justify outrageous things, I'm not aware that “getting access to classified information so you can sue the state” is something copyright law grants you in any state of the world. You certainly won't succeed suing an autocratic foreign state that might use your software for the most horrible things.

*It is not clear whether such restrictions would even be enforceable via copyright and if they would, whether that would be beneficial. I can only speak of Germany but I'm pretty confident that any such licensing terms would be void in German court proceedings. I think that this is a Good Thing. Copyright law is already too powerful in what other people can force onto you. The last thing we need is even more restrictions.

*If software licenses would restrict the usage of the software to “ethical purposes”, a terrible mess would result and software would not be compatible. While this certainly might happen, I don't see why there couldn't emerge a de-facto standard “ethical public license” published by a credible organization and used by many projects as it is the case with the GPL today. What I do see is that in order for such a general license to be widely accepted and used, it would very likely have to boil down to define as unethical what has already been agreed upon as unethical and therefore prohibited by public legislation in democracies, so it would not provide much. More important, since no such license exists today, you'd have to roll your own which is always a bad idea.

A: You can write any license you like, and sue anyone who uses your code contrary to the terms of the license for copyright infringement.
Your terms "not to be used by industry X" makes the license incompatible with the GPL license, for example. I cannot include your software in GPL code that I want to distribute (or that may be distributed accidentally, which happens). I couldn't include your code in my company's closed source code, because the legal department would kill me (it means if someone offered us millions for our source code we might not be able to sell it due to your restrictions). At the very least our legal department would say "it will cost us $5,000 to check the license. How much does it cost you to write the code yourself?"

A: If you're concerned about the ethics of industry X, rather than creating a license that discriminates against industry X, you could approach it differently; you could go the dual license approach, and create a free and commercial version. Then make donations to some anti industry X organization - either in the form of a full commercial version or some cut of the profits from the commercial version.
This is completely legal, and it's supporting an ideal you believe in. Also it's much better "good will marketing". Even people in the pro industry X crowd will respect you because at least you're supporting something you believe in. It's always better to be seen supporting an ideal rather than attacking its counter ideal.


Q: Pascals Identity Question, $n-1 \choose k-1$ The idea behind pascals identity is $\displaystyle \binom n k = \binom {n-1}k + \binom{n-1}{k-1}$.
I understand that we're splitting up the number of $k$ element sets into the number of $k$ element sets which include $n$ and the number of $k$ element sets which don't include $n$.
$n-1 \choose k$ makes sense to me, however $n-1 \choose k-1$ doesn't make sense, how this would determine the number of $k$ element subsets which include $n$, any explanations would be greatly appreciated.

A: Let us imagine a kingdom of $n$ people, and one person is the king. Let us now try to choose $k$ people from the kingdom. We may do it in one of two ways: either the king is chosen or he is not. If we do not choose the king, we, therefore, choose $k$ people from $n-1$ people, as the king remains unchosen. However, if the king is chosen, we need yet to choose $k-1$ people from the remaining $n-1$ people. As the two cases were separate, we achieve that we can choose $k$ people from $n$ people as the sum:
$$\binom{n}{k}=\binom{n-1}{k}+\binom{n-1}{k-1}$$


Q: java Opencv unsatisfiedLinkError, native Library is loaded I am trying to run some program on opencv, but I am getting this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError:
org.opencv.objdetect.CascadeClassifier.CascadeClassifier_0(Ljava/lang/String;)J

I have already loaded the library, libopencv_java310.so by using this code:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

I have also added the path to the native library.
I have searched a lot on the internet, but the only reason this error comes, is due to native library is not loaded. What could be the other reason of getting this error.
Can anyone help....!  Any help will be appreciated.

A: you might move your System.loadLibrary(Core.NATIVE_LIBRARY_NAME); to a static block so the dll gets loaded before any instruction of opencv .


Q: xmlns required for bean component of spring-servlet.xml for spring security application How to determine what xmlns are required for beans component of my spring-servlet.xml(spring configuration file) for spring security application?
Is this is the correct code?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

...

</beans>

A: I got my answer in the spring framework reference and that is mention below:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
...
</beans>

In general it should be like this. for reference Spring Security 3.0 Reference


Q: Embed a Mobile Emulator on a Website? I'm basically wondering if it was possible to create a functionality similar to this site: http://www.howtogomo.com/en/#gomo-meter
I want to add some kind of feature on my website that will allow visitors to check to see how their websites looked on a mobile device like an iPhone or Android phone.

A: You could fire up the android emulator from the android sdk , then using android debugging bridge fire up the following command
adb shell
am start -a android.intent.action.VIEW -d http://stackoverflow.com
then follow the following blog
http://android.amberfog.com/?p=168 , to take screen shot .

A: No. It looks like this site renders the website on the server side, and then sends down an image of this to your browser.
If you are interested only in Android and iPhone (and similar smartphones with browsers based on webkit) then you could try a similar approach to http://iphonetester.com. This uses a frame embedded to simulate the size (in pixels) of an iPhone. Note, that even though these browsers may be based on webkit, it doesn't mean their implementation is the same - see http://www.quirksmode.org/webkit.html for variance across different webkit based browsers.
This won't work if you want to stray to other non webkit based browsers.


Q: Creating artificial data out of data that only contains sentences I am trying to create artificial data. However my current data only contains sentences.
Two example rows that I have are the following:

Your order is on its way with tracking {imaginary tracking code}. Visit {imaginary random link} for more information.

The package has been shipped out with tracking {imaginary tracking code}. Visit {imaginary random link} for more information.

Now what I want to do is basically take these sentences and create thousands of them but with randomized tracking codes. I thought about splitting the sentences at two at the tracking code but couldn't figure out a way to split them at the specific tracking code. Like most tracking codes they contains numbers but also sometimes letters(usually at the front).
My current method which is bad would be to split the sentence into words. then check each word if it contains numbers. If it does contain a number that is the tracking code and now I have my way of creating artificial version of that sentence by taking everything before the tracking code inserting my artificial tracking code and everything after the tracking code. Repeating this for every row in the dataset and then randomizing the dataset.
So my question is, is there a more optimal way?

A: I suggest that you use regex to identify the codes to replace with random codes.
This example is deliberately simplified, I have used static codes and not randomly generated one and the regex pattern needs to be defined and refined.
import re
sentences = ('Your order is on its way with tracking 1234567890. Visit 98765432 for more information.',
'The package has been shipped out with tracking 1245789865. Visit 65659865 for more information.')

code1='9999999999'
code2='11111111'

for x in sentences:
  y = re.findall(r'(\D*)\d+(\D*)\d+(\D*)' ,x)
  if y[0][2]:
    z = y[0][0] + code1 + y[0][1] + code2 + y[0][2]
    print(z)

output
Your order is on its way with tracking 9999999999. Visit 11111111 for more information.
The package has been shipped out with tracking 9999999999. Visit 11111111 for more information.


Q: Java Firestore query snapshot returning string rather than boolean I am trying to map my query results from firestore back to a class in my java application.
I have saved this as a Boolean on the web console, see the image:

And then on the app I use the following function to map this to my class:
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        List<uk.wefix.FirestoreModels.Job> mJobsList = new ArrayList<>();
        if(task.isSuccessful()){
            for(QueryDocumentSnapshot document : task.getResult()) {
                uk.wefix.FirestoreModels.Job job = document.toObject(uk.wefix.FirestoreModels.Job.class);
                mJobsList.add(job);
            }
            mjobsAdaptor.clear();
            mjobsAdaptor.addAll(mJobsList);
        } else {
            Log.d("JobsFragment", "Error getting documents: ", task.getException());
        }
    }
});

And the class it maps to:
public class Job {

    public String first_name;
    public String second_name;
    public String phone_number;
    public Boolean complete;

    public Job() {}

    public Job(String first_name, String second_name, String phone_number, Boolean complete) {
        this.first_name = first_name;
        this.second_name = second_name;
        this.phone_number = phone_number;
        this.complete = complete;
    }

    /**
     * @return String
     */
    public String getFirst_name(){
        return first_name;
    }

    /**
     * @return String
     */
    public String getSecond_name(){
        return second_name;
    }

    /**
     * @return String
     */
    public String getPhone_number(){
        return phone_number;
    }

    /**
     * @return Boolean
     */
    public Boolean getComplete(){
        return complete;
    }
}

It seems like Firestore is returning a String instead of a Boolean which means I get the following error out:
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.String to boolean (found in field 'complete')

Obviously I could just do something like this in the Job class, but that seems a bit hacky and I am not sure if this is just a bug or if I am doing something wrong.
Potential 'hacky' solution
/**
 * @return Boolean
 */
public Boolean getComplete(){
    if(complete.equals("true")){
        return true;
    }else{
        return false;
    }
}

Query:
CollectionReference jobs = db.collection("jobs");
Query query = jobs.whereEqualTo("technician_id", 10).whereEqualTo("date", "2018-12-12");


Q: Program or script to see hex triplets in their actual color I've got a theme file that looks like following:
PRIMARY1_COLOR=#7CACDF
PRIMARY2_COLOR=#A5C6E9
PRIMARY3_COLOR=#E2EDF8
SECONDARY1_COLOR=#7CACDF
SECONDARY2_COLOR=#A5C6E9
SECONDARY3_COLOR=#B9D3EE

Is there any tool which allows editing such file while displaying actual colors?

A: You can use Geany. It has "Color chooser" button - select your hex code and click on it and you will see the color and will be able to change it.

A: You can create an HTML file with your favorite text editor and simply load it up your browser. Try this:

PRIMARY1

PRIMARY2

...

You can even automatically generate this with some clever find & replace or Excel formulas.


Q: Duplicate code but make the copied slower I build the shooting game by C# and Unity.
I use GameController and GameStatus to show the score and time.
At first scene, I have no problem. It can run smoothly.
But the second scene, I copy scene from first and make new GameController for second scene.
It's work but running game slower.
I try to make new project by using same code, but it's slow even it's my first scene.
I don't know cause of this happen.
Below is my code, it's work.
using UnityEngine;
using System.Collections;

public class MyGameController2 : MonoBehaviour

    private Gun gun;

    public GUISkin mySkin2;

    private GameStatus gameStatus;

    public float countDownTime2;
    private float scoreTime2;
    private float menuTime2;
    // Use this for initialization
    void Start () {
        countDownTime2 = 60.0f;
        scoreTime2 = countDownTime2+3;
        menuTime2 = countDownTime2+5;
        gameStatus = (GameStatus)GetComponent(typeof(GameStatus));
    }
        // Update is called once per frame
    void Update () {
        countDownTime2 -= Time.deltaTime;
        if(gameStatus.score >= 300){Application.LoadLevel("MainScene2");}
        if(countDownTime2 <= 0.0f)
        {gameStatus.isGameOver = true;
        countDownTime2 = 0.0f;
        gameStatus.score +=0;
        }
        scoreTime2 -= Time.deltaTime;
        menuTime2 -= Time.deltaTime;

    }

    void OnGUI()
    {
        float sw = Screen.width;
        float sh = Screen.height;
        GUI.skin = mySkin2;
        int mScore = gameStatus.score;
        if(countDownTime2 > 0.0f){
        GUI.Label (new Rect(50,0,sw/2,sh/2), "Score : " + mScore.ToString(),"scoreStyle");
        GUI.Label (new Rect(400,0,0,0), "Time : " + countDownTime2.ToString("000") ,"timeStyle");
        }
        if(gameStatus.isGameOver)
        {GUI.Label (new Rect(120,100,sw/2,sh/4),"Game Over","messageStyle");}

        if (scoreTime2 <= 0.0f)
        {
        GUI.Label (new Rect(130,50,0,0), "Your Score is " + mScore.ToString(),"scoreStyle2");
        }

        if(menuTime2 <= 0.0f){
        // Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
        if(GUI.Button(new Rect(100,220,80,20), "Retry")) {
            Application.LoadLevel("MainScene");}

        if(GUI.Button(new Rect(300,220,80,20), "Menu")) {
            Application.LoadLevel("TitleScene");}
        }
    }
}


Q: What's the 60's b&w movie where aliens have needles grow out of fingers and victims disappear in a funnel of sand? White thin-skinned aliens with large heads have needles grow out of their fingers just before stabbing their victims, then retract. Drops of 'venom' fall from the tips.  They (victims) and/or aliens (can't remember) disappear when the dirt/sand opens up bigger and bigger; reminds me of the funnel shape made in an hour glass.

A: I think you might be thinking of two different films.  The large-headed aliens with the retractable needles on the fingertips are from Invasion of the Saucer Men, (1957), and the "venom" turns out to be alcohol.

A teenage couple making out in the woods accidentally runs over an
  alien creature with their car. The creature's hand falls off, but it
  comes alive, and, with an eye growing out of it, begins to stalk the
  teens. Meanwhile, Joe the town drunk wants to store the body in his
  refrigerator, but some of the alien's buddies inject alcohol into his
  system, and Joe dies of an overdose.

The movie is available on Youtube.  The aliens don't have much screen time, so check out their highlight reel here.
The aliens capturing humans in sand pits are from the original Invaders From Mars, (1953).

One night, young David McLean sees a spaceship crash into a nearby
  sandpit. His father goes to investigate, but comes back changed. Where
  once he was cheerful and affectionate, he's now sullen and snarlingly
  rude. Others fall into the sandpit and begin acting like him: cold,
  ill-tempered and conspiratorial.

The movie is available on Youtube, and one of the scenes in question is here.


Q: Roots of unity inside ring class fields of an imaginary quadratic field $K$ always contained in $K(\mu_{12})$? I read online (in https://mathoverflow.net/questions/184347/intersection-of-a-ring-class-field-of-a-quadratic-field-k-with-the-cyclotomic-ex) that an (apparently not so trivial) exercise in class field theory shows that the roots of unity contained in ring class fields (of any conductor) on an imaginary quadratic field $K$ are always contained in $K(\mu_{12})$, where $\mu_{12}$ is the group of 12-th roots of unity.
Unfortunately, I can't find any proof or reference of this fact: can someone help me?

A: Not an expert of those things so please check that I'm not confused with something, and I can only show that the roots of unity of $K_O$ are contained in $\langle\zeta_{24}\rangle$.
We have an order $O=\Bbb{Z}+dO_K$.
The Artin map of the ring class field $K_O/K$ is $$(I,K_O/K)= [I\cap O]\ \in Cl(O)$$
For $a\in \Bbb{Z},\gcd(a,d)=1$ then $aO_K\cap O=aO$.

Proof: take $b\in \Bbb{Z},ab=1\bmod n$,
if $av=c+dw\in aO_K\cap O$ with $c\in \Bbb{Z},v,w\in O_K$ then $v=abv=bc\in (O_K/dO_K)^\times$ and hence $v\in O$.

Fix $n\in \Bbb{Z},n\nmid 24$. The Artin map of $K(\zeta_n)/K$ is $$(I,K(\zeta_n)/K)=N(I)\in \Bbb{Z}/n\Bbb{Z}^\times$$
For some $a\in \Bbb{Z},\gcd(a,dn)=1$ we have $a^2 \ne 1\bmod n$
so that $$(aO_K,K(\zeta_n)/K)=N(aO_K)=a^2\ne 1\in \Bbb{Z}/n\Bbb{Z}^\times$$ whereas
$$(aO_K,K_O/K)=[aO_K\cap O]=[aO]=1\in Cl(O)$$
whence $\zeta_n\not \in K_O$.


Q: EF5 Code First Many to Many with Migrations I have done this before, but for some reason cannot get it to work in EF5.
Usually it just automatically picks up when I have many to many relationships like this one...
public class Beer
{
    public int Id { get; set; }
    public virtual ICollection<Restaurant> Restaurants { get; set; }
}

public class Restaurant
{
    public int Id { get; set; }
    public virtual ICollection<Beer> Beers { get; set; }
}

I am wanting a RestaurantsBeers table or whatever with just RestaurantId and BeerId.
When I create it using the normal Code First way by just running the application it works.

Using migrations though, it won't create that table.

I ran Enable-Migrations then Add-Migration FirstDb and finally Update-Database... No dice...
Also tried this...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Beer>()
            .HasMany(b => b.Restaurants)
            .WithMany(a => a.Beers)
            .Map(m => m.MapLeftKey("BeerId")
                          .MapRightKey("RestaurantId")
                          .ToTable("BeersRestaurants"));
    }

A: Migrations to create a new M2M relationship are not supported yet in EF5.0RC per my experience trying to track down the same issue.  Thus why it will work on standard DB creation but doesn't work with Migration features.  You can export the create SQL from the standard code first database initialization and run it manually on the migration for now.
This should be resolved when EF5.0 goes RTM but for now we have to wait it out.


Q: Select multiple checkboxes using angularjs but unable to get selected one I am trying to get the list of selected checkboxes using angularjs. But unable to get selected.
HTML code Here

        <input type="checkbox" id="product_{{x.id}}"  class="form-control" ng-model="x.Selected">

        {{ x.category_name }}

script code:
.controller('categorieCtrl', function($scope, $http) {
   $scope.result = [{
            id: 1,
            category_name: 'Apple',
            Selected: false
        }, {
            id: 2,
            category_name: 'Mango',
            Selected: false
        }, {
            id: 3,
            category_name: 'Orange',
            Selected: false
        }];

 $scope.myFunc = function () {
     debugger;
     var message = "";
            for (var i = 0; i < 3; i++) {
                if ($scope.result[i].Selected) {
                    var id = $scope.result[i].id;
                    var categoryName =  $scope.result[i].category_name;
                    message += "Value: " + id + " Text: " + categoryName + "\n";
                }
            }
        alert(message);
    };
});

In the above code i am not getting selected items. Please let me know how can i get selected items using angularjs.

A:
  I've created a plunkr with your code here and it is working fine. I suppose you are not calling myFunc() correctly.
And also instead of using
for (var i = 0; i < 3; i++) {
  if ($scope.result[i].Selected) {
      ...
  }
}

You can make use of angular.forEach which will give you the object directly
angular.forEach(($scope.result, function(result, index){
  if (result.selected){
     ...
 });


Q: Flash light not detected I am trying to write an app which turns on flash light when a button is pressed. The problem is the app is not detecting flash light on my phone. I have searched alot on internet. Sure others have faced the problem, I have also applied those solutions but they don't seem to work. I don't know what is causing this problem. Posting the code here:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting_point);

    if(! getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) // checking if flash light is available inn android phone
    {
        Toast.makeText(StartingPoint.this, "Sorry this app can't work without flash light", Toast.LENGTH_LONG).show();
        finish();
    }

    cam = Camera.open();

    param = cam.getParameters();

}

@Override
public void onClick (View v)
{
      if(!flashOn)
        {
            i=0;

            flashOn=true;

            param.setFlashMode(Parameters.FLASH_MODE_TORCH);
            cam.setParameters(param);
            cam.startPreview();
        }
        else{
                i=0;

                flashOn=false;

                param.setFlashMode(Parameters.FLASH_MODE_OFF);
                cam.setParameters(param);
                cam.stopPreview();
            }

}
I have added these permissions in Android Manifest as well.
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />

Regards

A: I have an app that checks the flashlight feature and it works fine. Here is the code I used for checking if the user has the light:
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
    new AlertDialog.Builder(this)
    .setTitle("Sorry")
    .setMessage("It appears that your device is incompatible with this app. Sorry for the inconvenience.")
    .setNeutralButton("Close", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            finish();
        }
    }).show();
    return;
}

Now to actually make the light work, I made a toggle button and wrote the following code:
private boolean isLightOn = false;
private Camera camera;
private ToggleButton button;
public Vibrator v;

if (camera == null) {
    camera = Camera.open();
}

final Parameters p = camera.getParameters();

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        if (isLightOn) {

        Toast.makeText(context, "Light off!", Toast.LENGTH_SHORT).show();
        v.vibrate(40);
        p.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(p);
        camera.stopPreview();
        isLightOn = false;

        } else {

            Toast.makeText(context, "Light on!", Toast.LENGTH_SHORT).show();
        v.vibrate(40);
        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(p);
        camera.startPreview();
        isLightOn = true;

        }

    }
});

And finally, here are the only permissions I used:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

Note: All of the above code is in the onCreate method of my activity.
Hope this helps solve your problem!

A: I think you aren't setting your params again:
I used this to check if there is a flashlight:
public static Boolean hasFlashLight(Context context){
    return context.getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

and to turn it off and on:
Parameters params = mCamera.getParameters();
if (!isFlashlightOn) {
    params.setFlashMode(Parameters.FLASH_MODE_OFF);
} else {
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
mCamera.setParameters(params);

Let me know if it works for you too.

A: I had the same problem. Use this
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
  //Flash ok
  Parameters params = mCamera.getParameters();
  params.setFlashMode(Parameters.FLASH_MODE_TORCH);
} else {
  //Flash not supported
}

to determinate if your device has flash.

A: Some cameras need surface holder, otherwise they block the flash.
SurfaceView preview = (SurfaceView) findViewById(...);
SurfaceHolder holder = preview.getHolder();
holder.addCallback(this);
Camera camera = Camera.open();
camera.setPreviewDisplay(holder);


Q: Kafka 0.10.1.0 Test Server: Request METADATA failed I'm getting basic errors after setting up a super simple single-instance Kafka VM. This is for tiny volume development testing.
This is using the latest Confluent Platform 3.1.1 which includes the almost latest Kafka 0.10.1.0.
FYI, a slightly newer bug patch Kafka 0.10.1.1 is out, but the next post 3.1.1 Confluent Platform binary that includes that isn't available quite yet.
I configure /etc/kafka/server.properties with (I'm using a static local IP for dev testing simplicity):
listeners=PLAINTEXT://192.168.50.20:9092
advertised.listeners=PLAINTEXT://192.168.50.20:9092

(is that right?)
Simple console admin commands are generating errors. This leads me to believe that there is something wrong with the basic setup/configuration.
~$ /usr/bin/kafka-consumer-groups --new-consumer --bootstrap-server localhost:9092 --list
Error while executing consumer group command Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null))
java.lang.RuntimeException: Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null))
    at kafka.admin.AdminClient.sendAnyNode(AdminClient.scala:67)
    at kafka.admin.AdminClient.findAllBrokers(AdminClient.scala:87)
    at kafka.admin.AdminClient.listAllGroups(AdminClient.scala:96)
    at kafka.admin.AdminClient.listAllGroupsFlattened(AdminClient.scala:117)
    at kafka.admin.AdminClient.listAllConsumerGroupsFlattened(AdminClient.scala:121)
    at kafka.admin.ConsumerGroupCommand$KafkaConsumerGroupService.list(ConsumerGroupCommand.scala:304)
    at kafka.admin.ConsumerGroupCommand$.main(ConsumerGroupCommand.scala:66)
    at kafka.admin.ConsumerGroupCommand.main(ConsumerGroupCommand.scala)

EDIT: The problem, thanks to Gondola_Ride, was that I specified the IP in listeners in server.properties. I could connect via that IP, but not via localhost. The solution was to use host 0.0.0.0 which is Kafka's convention for binding to all local TCP interfaces:
listeners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://192.168.50.20:9092

A: Try adding an entry in the /etc/hosts on the host where you are running this command for this host 192.168.50.20 and see if it works
Something like
127.0.0.1       localhost.localdomain localhost
OR
192.168.50.20  hostname hostname-alias
Then try using it in the command
OR
Try using ip address directly in the command instead of localhost


Q: Google maps api and geolocation, Javascript and Html Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
     var map;
  var infowindow;

  function initialize() {

    if (navigator.geolocation)
   {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
    function showPosition(position)
    {

    var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );

    map = new google.maps.Map(document.getElementById('map'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlon,
      zoom: 15,
      disableDefaultUI: true
    });

    var request = {
      location: latlon,
      radius: 555,
      types: ['bar']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
     }
    }
   }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      alert(place.name);
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);

Working code
 var map;
  var infowindow;

  function initialize() {
    var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);

    map = new google.maps.Map(document.getElementById('map'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlon,
      zoom: 15,
      disableDefaultUI: true
    });

    var request = {
      location: latlon,
      radius: 555,
      types: ['bar']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      alert(place.name);
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);

Any help if appreciated :)

A: Replace your line:
var latlon = new google.maps.LatLng
      (position.coords.latitude + "," + position.coords.longitude);

with
var latlon = new google.maps.LatLng
      (position.coords.latitude, position.coords.longitude);

The problem is in concatenating two values into one where constructor expects two parameters.


Q: Try/Catch with while loop can't work Problem

*

*Method asks user for an integer value.

*Pass the value into a loop to ensure it is a positive number.

*Add a in.nextline to ensure the value don't overrun into next line of code. -

*Return integer value.
private static int getIntFromUser(String aa) {

int aaa = 0;
 while (true && aaa <= 0) {
     try {
         System.out.println(aa + ": ");
         aaa = in.nextInt();
             if (aaa <= 0) {
                 System.out.println("Please enter a positive number.");
             }
         } catch (Exception e) {
         System.out.println("Please enter an integer: ");

 in.next();
         }
 }
 in.next();
 return aaa;
}

Question
Try/Catch with while loop can't work ?

A: Tested it myself, it returns aaa properly (after removing in.next() at the bottom of the method and replacing it with in.nextLine()). When you do a return call, you need to send it somewhere. Such as System.out or to a variable like int x = getUserFromInput("test: ");
public class Tester {

    private static Scanner in = new Scanner(System.in);

    private static int getIntFromUser(String aa) {

        int aaa = 0;
        while (true && aaa <= 0) {
            try {
                System.out.println(aa + ": ");
                aaa = in.nextInt();
                if (aaa <= 0) {
                    System.out.println("Please enter a positive number.");
                }
            } catch (Exception e) {
                System.out.println("Please enter an integer: ");
                in.next();
            }
        }
        in.nextLine();
        return aaa;
    }

    public static void main(String[] a) {
        System.out.println(getIntFromUser("test123"));
    }
}

Output


Q: ActiveRecord STI delete doesn't work correctly I want to store two models using active record, but delete doesn't work as expected.

*

*Evaluation has id, name and description

*and SqlEvaluation has additional two columns of query_string and database.

I want to use those two tables, and eval_typ_id is used to distinguish which subclass should be used: 1 for SqlEvaluation.
create table eval (
eval_id int,
eval_name varchar,
eval_desc varchar,
eval_typ_id int
);

create table sql_eval (
eval_id int
query_str varchar
database varchar
);

After some research, I used the following code, it works well except "delete", which didn't delete the row in sql_eval. I cannot figure out where is wrong?
require 'rubygems'
require 'active_record'
require 'logger'

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(:adapter => "ibm_db",
                                        :username => "edwdq",
                                        :password => "edw%2dqr",
                                        :database => "EDWV2",
                                        :schema => "EDWDQ" )

class Eval < ActiveRecord::Base
  set_table_name "eval"
  set_primary_key :eval_id

  TYPE_MAP = { 1 => 'SqlEval' }

  class << self
    def find_sti_class(type)
      puts "#{type}"
      super(TYPE_MAP[type.to_i])
    end

    def sti_name
      TYPE_MAP.invert[self.name]
    end
  end

  set_inheritance_column :eval_typ_id
end

class SqlEval < Eval
  has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id, :foreign_key=>:eval_id, :include=>true, :dependent=>:delete
  default_scope :conditions => { :eval_typ_id => 1 }
end

class SqlEvalDetails < ActiveRecord::Base
  belongs_to :sql_eval, :class_name=>'SqlEval',
    :conditions => { :eval_type_id => 1 }
  set_table_name "sql_eval"
  set_primary_key :eval_id
end

se = SqlEval.find(:last)

require 'pp'

pp se
pp se.details

# Eval.delete(se.eval_id)
se.delete

A: Sorry for messing the code. It is first time to post for me. Here is the code.
require 'rubygems'
require 'active_record'
require 'logger'

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(:adapter => "ibm_db",
                                    :username => "edwdq",
                                    :password => "edw%2dqr",
                                    :database => "EDWV2",
                                    :schema => "EDWDQ" )

class Eval < ActiveRecord::Base
  set_table_name "eval"
  set_primary_key :eval_id

  TYPE_MAP = { 1 => 'SqlEval' }

  class << self
    def find_sti_class(type)
      puts "#{type}"
      super(TYPE_MAP[type.to_i])
    end

    def sti_name
      TYPE_MAP.invert[self.name]
    end
  end

  set_inheritance_column :eval_typ_id
end

class SqlEval < Eval
  has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id,     :foreign_key=>:eval_id, :include=>true, :dependent=>:delete
  default_scope :conditions => { :eval_typ_id => 1 }
end

class SqlEvalDetails < ActiveRecord::Base
  belongs_to :sql_eval, :class_name=>'SqlEval',
    :conditions => { :eval_type_id => 1 }
  set_table_name "sql_eval"
  set_primary_key :eval_id
end

se = SqlEval.find(:last)
e = Eval.where(:eval_id => 26)

require 'pp'

pp se
pp e
pp se.details

# Eval.delete(se.eval_id)
se.delete


Q: Passar array para Modal Tenho o seguinte array $detalhes:
 Array ( [0] => Array ( [dt_detalhes] => 2016-03-09 [desc_detalhes] => Viabilidade [tp_processo] => Viabilidade [vl_protocolo] => 1234 )
         [1] => Array ( [dt_detalhes] => 2016-03-12 [desc_detalhes] => Sincronizado [tp_processo] => Sincronizado [vl_protocolo] => 12345 )
         [2] => Array ( [dt_detalhes] => 2016-03-11 [desc_detalhes] => Integrador [tp_processo] => Integrador [vl_protocolo] => 123456 ) )

Gostaria de passar ele para dentro de uma modal, dessa forma:
<button type="button" data-toggle="modal" data-target="#detalhes"
data-id="<?=$linha['id_processo']?>" data-detalhes="<?=$details?>">

Como posso fazer isso? Da forma tentada acima da o seguinte erro:

Array to String Conversion

OBS: preciso passar o array inteiro.

A: O echo serve para imprimir valores escaleres(int, string float etc) exceto arrays e objetos.
Você pode pegar o array e transforma em uma string json com o php e pelo javascript converter para um objeto.
<button id="button" type="button" data-toggle="modal" data-target="#detalhes"
data-id="<?=$linha['id_processo']?>" data-detalhes="<?=json_encode($detalhes);?>">

No javascript:
var data = document.getElementById('button');
var json = JSON.parse(data.getAttribute('data-detalhes'));
console.log(json);

A: Se você quer imprimir dados específicos do array, precisa imprimir assim:
echo $details[0]['dt_detalhes'];

Ele irá imprimir o campo dt_detalhes do primeiro item do array 0
Se quiser imprimir todos os campos e todos os arrays, deve percorrelos utilizando alguma função de laço, exemplo:
for($i=0; $i < count($details); $i++) {
    echo $details[$i]['dt_detalhes']; // campo desejado, exemplo 'vl_protocolo'
}

Para entender melhor como um array funciona leia a documentação, caso tenho dúvidas, poste aqui.


Q: ASP.NET RSS feed error in link tag in item node? Issue with Razor in Umbraco RSS Feed Having an issue with creating an rss feed against a blog in umbraco using razor.  The code below works but as soon as I try and add any value into the link tag under the item node I get an xml error, below is the code.
<rss version="2.0">
    <channel>
        <title>@landing.uBlogsyRssTitle</title>
        <description>@landing.uBlogsyRssDescription</description>
        <copyright>@landing.uBlogsyRssCopyright</copyright>
        @*<image>@landing.uBlogsyRssImage</image>*@
        <link>@Request.Url.Host@landing.Url</link>
        <lastBuildDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</lastBuildDate>
        <pubDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate>
        @foreach (var p in posts)
        {
        <item>
            <title>@p.GetProperty("uBlogsyContentTitle").Value</title>
            <link></link>
            <author>@p.GetProperty("uBlogsyPostAuthor").Value</author>
            <description>@p.GetProperty("uBlogsyContentBody").Value.StripHtml().Trim()</description>
            <guid>@p.Url</guid>
            <pubDate>@p.GetProperty("uBlogsyPostDate").Value.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate>
        </item>
        }
</channel>
</rss>

A: This is my answer to another post with the same problem solved:
Since MVC4 Razor verifies that what you are trying to write is valid HTML. If you fail to do so, Razor fails.
Your code tried to write incorrect HTML:
If you look at the documentation of link tag in w3schools you can read the same thing expressed in different ways:

*

*"The  element is an empty element, it contains attributes only."

*"In HTML the  tag has no end tag."

What this mean is that link is a singleton tag, so you must write this tag as a self-closing tag, like this:
<link atrib1='value1' attrib2='value2' />
So you can't do what you was trying to do: use an opening and a closing tag with contents inside.
That's why Razor fails to generate this your <xml> doc.
But there is one way you can deceive Razor: don't let it know that you're writing a tag, like so:
@Html.Raw("<link>")--your link's content--@Html.Raw("</link>")
Remember that Razor is for writing HTML so writing XML with it can become somewhat tricky.


Q: Multiple framebuffers and textures not working on intel drivers I'm writing an application using PyOpengl and PySide. My main machine is installed with ubuntu and an nvidia card (proprietary drivers), the premise is just to tell that the application is working properly in this setting.
I'm testing this application on a machine with an intel hd 3000 and Ubuntu 12.10, the drivers are the default intel drivers. Everything is working so far except for the application of multiple post-processing filters.
The process works like that:
render the scene and output a color texture (texture0) using a framebuffer object (called fb0).
render the first postprocessing effect by binding the textures produced in the previous step. The processed color output is saved in another texture (extratexture1) by using another framebuffer (fb1).
render another postprocessing effect by using the new color texture (extratexture2 and fb2).
render the result on the screen.
What I obtain is a white screen (my background color perhaps).
If I remove the last step and render the extratexture1, I obtain the correct result. If I remove the second step only and render the extratexture2 I obtain the correct result. Therefore the problem should not be in the texture initialization code.
It's like that this driver doesn't support more than 2 framebuffers (+ default one) at a time. Or probably failing to reset some important state.
Was anybody able to code a similar thing on an intel video card? I'm running out of ideas of what the problem can be.
I add some example code to troubleshoot any error:
Initialization of framebuffers and textures, at initialization time. The texture are regenerated at each resize.
   self.fb0, self.fb2, self.fb1 = glGenFramebuffers(3)
   # Creation of texture0

   glDrawBuffers(1, np.array([GL_COLOR_ATTACHMENT0], dtype='uint32'))

   # Creation of extratexture1
   # Creation of extratexture2

Creation of each texture:
def create_color_texture(fb, width, height):
    # Simple wrapper for glGenTexture and glTexImage2D
    texture = Texture(GL_TEXTURE_2D, width, height, GL_RGB, GL_RGB,
                      GL_UNSIGNED_BYTE)

    # Set some parameters
    texture.set_parameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    texture.set_parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    glBindFramebuffer(GL_FRAMEBUFFER, fb)
    glViewport(0, 0, width, height)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           texture.id, 0)
    return texture

Code that draws the texture to screen:
def render(self, fb, textures):
    # We need to render to a quad
    glBindFramebuffer(GL_FRAMEBUFFER, fb)
    glViewport(0, 0, self.widget.width(), self.widget.height())
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glUseProgram(self.quad_program)

    qd_id = glGetUniformLocation(self.quad_program, "rendered_texture")
    # Setting up the texture
    glActiveTexture(GL_TEXTURE0)
    textures['color'].bind()
    # Set our "rendered_texture" sampler to user Texture Unit 0
    glUniform1i(qd_id, 0)

    # Set resolution
    glUniform2f(glGetUniformLocation(self.quad_program, 'resolution'), self.widget.width(), self.widget.height())
    # Set gamma value
    glUniform1f(glGetUniformLocation(self.quad_program, 'gamma'), self.gamma)

    # Let's render a quad
    quad_data = np.array([-1.0, -1.0, 0.0,
                          1.0, -1.0, 0.0,
                          -1.0,  1.0, 0.0,
                          -1.0,  1.0, 0.0,
                          1.0, -1.0, 0.0,
                          1.0,  1.0, 0.0],
                         dtype='float32')

    vboquad = vbo.VBO(quad_data)
    vboquad.bind()

    glVertexPointer(3, GL_FLOAT, 0, None)
    glEnableClientState(GL_VERTEX_ARRAY)

    # draw "count" points from the VBO
    glDrawArrays(GL_TRIANGLES, 0, 6)

    vboquad.unbind()
    glDisableClientState(GL_VERTEX_ARRAY)


Q: Ruby TCPSocket Server - Can I tell to what host a client was connecting? I have a ruby server based on TCPSocket (non-HTTP).
I have 2 different domains, both pointing with an A-Record to my servers IP Address (the same one). So, there are clients connecting to one of those domains.
Is it possible to tell which domain a client was connecting to?
I saw that this is possible in other protocols, but I'm not sure if this is based on manually added headers or really extracted from the basic tcp/ip connection. E.g. in PHP there is $_SERVER["HTTP_HOST"] which shows to which domain a client was connecting.

A: At the TCP socket level, the only things that are known are the source and destination IP addresses (and ports) of the connection.  How the IP address was resolved via DNS is not possible to know at this layer.  Even though HTTP works on top of TCP, HTTP servers have to look at the HTTP headers from the client to know which domain they are making a request to. (That's how the HTTP_HOST value gets filled in.)
One possible solution is to configure your server to have an additional IP address. This can be by assigning an additional IP address to the NIC or adding an additional NIC.  Then have each domain use a different IP address.  Otherwise, this is not possible and you may want to consider your application protocol on top of TCP to convey this information.


Q: Можно ли определить браузер, ОС, IP и прочую информацию о пользователе используя Flask Можно ли как нибудь определить IP-адрес пользователя, ОС, браузер, и.т.д используя Flask?


Q: NumPy linear equations I was wondering to check for an algorithm that would solve set of three linear equations in two variables which change in every equation adjacently for example

*

*a + b = 0

*a + c = 0

*b + c = 1

I am open to all suggestions

A: Use the np.linalg.solve library:
https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
import numpy as np
a = np.array([[1,1,0], [1,0,1], [0,1,1]])
b = np.array([0,0,1])
x = np.linalg.solve(a, b)

A: alternative to the answer
import numpy as np
A = np.array([[1, 1, 0], [1, 0, 1], [0, 1, 1]])
B = np.array([0, 0, 1])
X = np.linalg.inv(A).dot(B)

print(X)


Q: Extract elements of lists in an RDD What I want to achieve
I'm working with Spark and Scala. I have two Pair RDDs.
rdd1 : RDD[(String, List[String])]
rdd2 : RDD[(String, List[String])]

Both RDDs are joined on their first value.
val joinedRdd = rdd1.join(rdd2)

So the resulting RDD is of type RDD[(String, (List[String], List[String]))]. I want to map this RDD and extract the elements of both lists, so that the resulting RDD contains just these elements of the two lists.

Example
rdd1 (id, List(a, b))
rdd2 (id, List(d, e, f))
wantedResult (a, b, d, e, f)

Naive approach
My naive approach would be to adress each element directly with (i), like below:
val rdd = rdd1.join(rdd2)
    .map({ case (id, lists) =>
        (lists._1(0), lists._1(1), lists._2(0), lists._2(2), lists._2(3)) })

/* results in RDD[(String, String, String, String, String)] */

Is there a way to get the elements of each list, without adressing each individually? Something like "lists._1.extractAll". Is there a way to use flatMap to achieve what I'm trying to achieve?

A: You can simply concatenate the two lists with the ++ operator:
val res: RDD[List[String]] = rdd1.join(rdd2)
  .map { case (_, (list1, list2)) => list1 ++ list2 }

Probably a better approach that would avoid to carry List[String] around that may be very big would be to explode the RDD into smaller (key value) pairs, concatenate them and then do a groupByKey:
val flatten1: RDD[(String, String)] = rdd1.flatMapValues(identity)
val flatten2: RDD[(String, String)] = rdd2.flatMapValues(identity)
val res: RDD[Iterable[String]] = (flatten1 ++ flatten2).groupByKey.values