text:
Q: How to enable detailed database connection logging? Our DBA is trying to migrate a Django application's database to a new backend host running Oracle 12.  When I put that host's info in the Django settings.py file, I get this error:
DatabaseError: ORA-28547: connection to server failed, probable Oracle Net admin error

The DBA has asked for my help in solving this problem.  Is there a way to turn on detailed logging in Django while establishing a database connection?  I've seen directions for enabling logging of database queries, but we're not getting that far -- our error is happening sometime during the connection.

A: Basically you can use a Wireshark or any sniffing tool to check what is the connection string passed to the DB.
But this oracle error will occur when there is an error after the initial handshake to the Oracle DB and further establishing a connection.
Check you oracle_cx for python and the oracle instant client whether the insta client is of the correct version to the DB. Try a connection form instantclient directly to the DB using sqlplus.
Reference:
django docs
DBA forum
django community


text:
Q: How to check if PFQuery result is true in Swift In my application, users can select three different account types at sign up: Parent User, Family Account, and Child Account. I added a column in the users database in Parse called "isParent" and set it as a boolean. Now, in the AppDelegate, I want to check if "isParent" is true, so I can display a certain ViewController. I have the following code:
In AppDelegate.swift within didFinishLaunchingWithOptions:
    if PFUser.currentUser() == nil {
      // code to show sign up/login goes here

        }

    } else {

        let query = PFUser.query()
        query?.whereKey("username", equalTo: (PFUser.currentUser()?.username)!)

        if query["isParent"] == true{   // error here. see below.
           // parent view controller
              print("this user is a parent")

            }
        } else{
            // non parent view controller
            print("this user is not parent")

        }
    }

As you read above, the error is within:
if query["isParent"] == true{

I get the following error message:

Type "PFQuery?" has no subscript members

So, I want to be able to check if "isParent" is true so I can open a view controller.
How can I fix this?
Thanks.

A: First you need to fire the query to get data and after that you can check your condition.
You can user PFQuery class's method to get data.
findObjectsInBackgroundWithBlock
findObjectsInBackgroundWithTarget:selector:
getFirstObject
getFirstObjectInBackground ....etc.

You can choose your method...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing .so file made with Cython results in ImportError: ... undefined symbol I have cythonised a chunk of code, which I know works on my usual machine.
However, when I transfer it and run it on another machine it is not working. My machine is running Ubuntu and the other machine is running Ubuntu within Docker.
The error is:
    from myFile import myFunction
ImportError: /myFile.so: undefined symbol: PyFPE_jbuf

The Docker environment is set up with the exact same dependencies as on my local machine, so I can't understand why this is happening!

A: This error is referenced with several scientific Python projects https://github.com/scikit-learn/scikit-learn/issues/7542 https://github.com/automl/auto-sklearn/issues/101 and is apparently related to multiple installations of NumPy, Cython or different C++ compilers.
Now, you should make sure that the environment is clean on both sides: no packages in ~/.local, no setting for PYTHONPATH environment variable and only the system Python and system compiler, for instance. Then, also provide the full backtrace instead of the one error.


text:
Q: 14.04: kernel version vs. release version I started fresh installation from the ISO file of 14.04.1 via USB flash drive. Soon after that, I did the updating via Software Updater (over 270 MB required). Then I've checked the terminal and this is what is happening now:
:~$ uname -r

3.13.0-93-generic

:~$ lsb_release -a

No LSB modules are available.

Distributor ID: Ubuntu

Description:    Ubuntu 14.04.5 LTS

Release:    14.04

Codename:   trusty

As far as I'm concerned, the point release 14.04.5 is along with 4.4 kernel. How could it happen to be as what is shown in the command line? Would there be any problems that might appear caused by it? Should I upgrade the kernel?


text:
Q: Django join ManyToManyField with Intersection Table - Soft Delete There are three models - Role,Permission, and their intersection as RolePermission
Every models have a active_status flag to denote soft delete. Now when we are trying to fetch all roles joined with their respective active positions through RolePosition model, the Inactive ones are still there.

class Role(models.Model):
    name = models.CharField(_('Role Name'),null=False,max_length=255,unique=True,blank=False)
    organization = models.ForeignKey('organization.Organization',blank=False, null=True,on_delete=models.SET_NULL)
    active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE')
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(null=True)
    permissions = models.ManyToManyField(Permission, through='RolePermission')

    #------------------plan details ---------------------

    class Meta:
        verbose_name = "role"
        db_table = 'ontym_roles'

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        timestamp = timezone.now()
        if not self.id:
            self.created_at = timestamp
        self.updated_at = timestamp
        return super(Role, self).save(*args, **kwargs)

#----------------------- manp many to many role permissions -------------------
class RolePermission(models.Model):
    role = models.ForeignKey(Role,null=False,blank=False,on_delete=models.CASCADE)
    permission = models.ForeignKey(Permission,null=False,blank=False,on_delete=models.CASCADE)
    active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE')
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(null=True)

    class Meta:
        verbose_name = "role_permission"
        db_table = 'ontym_role_permission'

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        timestamp = timezone.now()
        if not self.id:
            self.created_at = timestamp
        self.updated_at = timestamp
        return super(RolePermission, self).save(*args, **kwargs)

        roles = Role.objects.filter(rolepermission__permission__active_status__exact='ACTIVE')

And getting a response ->
{
    "status": true,
    "code": 200,
    "message": "All Roles fetched sucessfully for current organization",
    "data": [
        {
            "id": 1,
            "name": "ROLE_MANAGER",
            "active_status": "ACTIVE",

            "permissions": [
                {
                    "id": 1,
                    "name": "ROLE_CREATE",
                    "active_status": "ACTIVE",

                },
                {
                    "id": 2,
                    "name": "ROLE_VIEW",
                    "active_status": "ACTIVE",

                }
            ]
        },
        {
            "id": 4,
            "name": "MANAGE_",
            "active_status": "ACTIVE",

            "permissions": [
                {
                    "id": 1,
                    "name": "ROLE_CREATE",
                    "active_status": "ACTIVE",

                },
                {
                    "id": 2,
                    "name": "ROLE_VIEW",
                    "active_status": "ACTIVE",

                }
            ]
        },
        {
            "id": 5,
            "name": "ROLE_MANAGER_NEW",
            "active_status": "ACTIVE",

            "permissions": [
                {
                    "id": 1,
                    "name": "ROLE_CREATE",
                    "active_status": "ACTIVE",

                },
                {
                    "id": 2,
                    "name": "ROLE_VIEW",
                    "active_status": "ACTIVE",

                }
            ]
        }
    ]
}

Snapshot of DB ->
https://drive.google.com/drive/folders/1b_KSyZE7vEwXuoLDEpkWo4YmmaaAQH0n?usp=sharing


text:
Q: How to check whether a CGPoint is inside a UIImageView? In touchesBegan:
CGPoint touch_point = [[touches anyObject] locationInView:self.view];

There are tens of UIImageView around, stored in a NSMutableArray images. I'd like to know is there a built-in function to check if a CGPoint (touch_point) is inside one of the images, e.g.:
for (UIImageView *image in images) {
   // how to test if touch_point is tapped on a image?
}

Thanks
Follow up:
For unknown reason, pointInside never returns true. Here is the full code.
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
      UITouch *touch = [touches anyObject];
        touch_point = [touch locationInView:self.view];
        for (UIImageView *image in piece_images) {
            if ([image pointInside:touch_point withEvent:event]) {
                image.hidden = YES;
            } else {
                image.hidden = NO;
            }
            NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, touch_point.x, touch_point.y);
        }
    }

although I can see the two points are sometimes identical in the NSLog output.
I also tried:
  if ([image pointInside:touch_point withEvent:nil])

the result is the same. never returns a true.
To eliminate the chance of anything goes with with the images. I tried the following:
  if (YES or [image pointInside:touch_point withEvent:event])

all images are hidden after the first click on screen.
EDIT 2:
Really weird. Even I hard coded this:
        point.x = image.center.x;
        point.y = image.center.y;

the code becomes:
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [touches anyObject];
        CGPoint point; // = [touch locationInView:self.view];
        for (UIImageView *image in piece_images) {
            point.x = image.center.x;
            point.y = image.center.y;
            if ([image pointInside:point withEvent:event]) {
                image.hidden = YES;
                NSLog(@"YES");
            } else {
                image.hidden = NO;
                NSLog(@"NO");
            }
            NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, point.x, point.y);
        }
    }

pointInside always returns false ...

A: Sounds to me like the problem is you need to convert coordinates from your view's coordinates to the UIImageView's coordinates. You can use UIView's convertPoint method.
Try replacing
if ([image pointInside:touch_point withEvent:event]) {

with
if ([image pointInside: [self.view convertPoint:touch_point toView: image] withEvent:event]) {

(Note that you are allowed to pass nil instead of event.)
I guess this is a bit late for the questioner, but I hope it is of use to someone.

A: if ([image pointInside:touch_point withEvent:event]) {
    // Point inside
}else {
    // Point isn't inside
}

In this case event is taken from :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    for (UIImageView *piece in piece_images) {
        CGFloat x_min = piece.center.x - (piece.bounds.size.width / 2);
        CGFloat x_max = x_min + piece.bounds.size.width;
        CGFloat y_min = piece.center.y - (piece.bounds.size.height / 2);
        CGFloat y_max = y_min + piece.bounds.size.height;
        if (point.x > x_min && point.x < x_max && point.y > y_min && point.y < y_max ) {
            piece.hidden = YES;
        } else {
            piece.hidden = NO;
        }
    }

}

too bad, I have do it myself...
it's OS 3.2, XCode 3.2.2, tried both on simulator and iPad


text:
Q: how to scroll down inside div with selenium I have a div element that I want to scroll down inside it with selenium.
I want to scroll specific pixels.
What is the easiest way to do it?
I searched on web but didn't find fine explanation.

A: You can use this method:
public void scrollOnElement(String cssSelector){
    JavascriptExecutor js = (JavascriptExecutor)driver;
    String script = String.format("document.querySelector('%s').scrollTop= 450",cssSelector);
    js.executeScript(script);
}

The css parameter here is the css selector locating the div element you want to scroll inside.
I use 450 pixels scrolling here however you can use any parameter instead.


text:
Q: PHP - Storing Session in a Database I am setting up a EC2 cluster with a load balancer. I have seperate DB server which has mysql running on it. I have 3 webservers running, mostly for high availability, and of course its round-robin load balancing it seems, so every page you go to you get a different server which looses your session.
I am trying to setup PHP to store it in the DB. I have setup a table, and setup all the functions (open,close,etc). and I have set:
session_set_save_handler('_open',
                         '_close',
                         '_read',
                         '_write',
                         '_destroy',
                         '_clean');

But when I login or anything on the site I check the table and nothing has been written. I am not sure If i need to change something in the php.ini file. If so what is the value to change?
Thanks!!
EDIT: functions:
function _open(){
    global $con;
    connect();
}

function _close(){
    global $con;
    //mysql_close();
}

function _read($id){
    global $con;
    $id = mysql_real_escape_string($id);
    $sql = "SELECT data FROM sessions WHERE id = '$id'";
    if ($result = mysql_query($sql, $con)) {
        if (mysql_num_rows($result)) {
            $record = mysql_fetch_assoc($result);
            return $record['data'];
        }
    }
    return '';
}

function _write($id, $data)
{
    global $con;

    $access = time();

    $id = mysql_real_escape_string($id);
    $access = mysql_real_escape_string($access);
    $data = mysql_real_escape_string($data);

    $sql = "REPLACE
            INTO    sessions
            VALUES  ('$id', '$access', '$data')";

    return mysql_query($sql, $con);
}

function _destroy($id)
{
   global $con;
    $id = mysql_real_escape_string($id);
    $sql = "DELETE
            FROM   sessions
            WHERE  id = '$id'";
    return mysql_query($sql, $con);
}

function _clean($max)
{
    global $con;

    $old = time() - $max;
    $old = mysql_real_escape_string($old);

    $sql = "DELETE
            FROM   sessions
            WHERE  access < '$old'";

    return mysql_query($sql, $con);
}

session_set_save_handler('_open',
                         '_close',
                         '_read',
                         '_write',
                         '_destroy',
                         '_clean');

A: The function you're using will interrupt the normal session function and insert your code in to act, then carry on with other internal functions.
In the functions where you aren't really doing anything session-wise (things like '_open' and '_close'), you need return something to carry on the command or it will just die right there.
Example:
function _open($save_path, $session_name){
    global $con;
    connect();

    return true; //Do nothing but carry on
}

function _close(){
    global $con;
    //mysql_close();

    return true; //Do nothing but carry on
}

A: Really this is not the answer to your question, but if you need really high availability I can suggest that storing sessions in mysql is not a good method.
A better practice: Put your sessions in memcache. Memcache server it's easy to install. Memcache client is easy to install and php support storing session in memcache without programming!!! Memcache store data in memory, not in disk and it's faster.
Here you can view a good post about this: http://kevin.vanzonneveld.net/techblog/article/enhance_php_session_management/
Luck!!

A: How come you can't use cookies? and just have the script check if the cookies is present then read the value's from there. Unless security is an issue .. I suggest cookies over sessions for cheap scalability ..Writing session's in the database won't be good and will probably result in expensive queries being ran for no reason.

A: The best database for sessions is going to be something like Redis or MonogDB and not MySQL and not memcached. You could use memcached depending on how much traffic you get, but Redis or MongoDB is a much more scalable database. Also, since you're on EC2, you may want to look at Amazon SimpleDB. It's a key/value store so it should lend itself well to sessions.
I'd personally run with MongoDB because not only can you store your sessions there, but you can take what you do have from MySQL and cache it there too as well as store other data in Mongo...Or just think about converting your site's database altogether because you'll probably fall in love with MongoDB =)
You can also look into the settings of HAProxy under Application Cookies. That may help you too.


text:
Q: Very Strange Repeated TCP/IP/DNS Warnings Every 75 minutes a warning is posted in my system event log.  With very few exceptions, this continues 24/7 and has occurred for months.  The warning is from source DNS Client Events, event ID 1014, description:

"Name resolution for the name tunnel.cfw.trustedsource.org timed out
  after none of the configured DNS servers responded."

There are one or two other URLs that sometimes appear in place of tunnel.cfw.trustedsource.org.
For 10 minutes after the posting of this warning, no new internet connections succeed.  I.E., if the IE browser is launched, the circulating arrow appears with the "Waiting for ..." message and this will continue for 10 minutes.  After that time, the home page will appear and for the next 65 minutes all is OK.
I removed power from my Cisco DPC3825 residential gateway for a few minutes to see if the times of the warnings would shift (possibly indicating that the problem is in the gateway itself), but the times did not shift.  Subsequent warnings continued to be posted on the same, original schedule.
Does anyone have any suggestions, either as to the cause, or for anything I can do to obtain more diagnostic information?  It might be helpful if there were a way to monitor ALL TCP/IP/DNS activity immediately preceding the posting of the DNS warning.  Because the timing of the warnings is so uniform, I can predict within seconds when the next one will occur.
I am running under Windows 7 on a Dell T1700.
(Sorry if this duplicates a question I submitted yesterday as a guest, but I was unable to relocate that question or any answers to it.)


text:
Q: Setting up React app using Typescript with Auth0 I'm attempting to work through the Auth0 sample application using a project created using create-react-app with the Typescript template.
I found one example that got me through react-auth0-spa.tsx (https://github.com/auth0/auth0-spa-js/issues/39).  However, when I try to create NavBar.tsx, it seems not to be understanding the type returned by the useAuth0() call.  I am a comparative lightweight with Typescript, but this seems like it may be because the type is declared as nullable, though that's a guess.
Here's the export from react-auth0-spa.tsx:

And here's the error VSCode is showing me:

But isAuthenticated is very definitely on the interface, which leads me to think the nullable declaration is part of my problem:

If I change the type declaration to 'any' it works, but that's clearly the wrong answer.  The whole point of using Typescript is for static typing.
I also found https://github.com/tommedema/startup-boilerplate/blob/master/packages/react-app/src/components/LoginView.tsx, which seems to imply that this should work.  I've reviewed tsconfig.json and some other files to see if maybe I have different compiler options, but haven't found a smoking gun.
What am I missing here?
Thanks in advance.

A: It looks like my suspicion was right.  I was missing a trailing non-null assertion operator on the call to create the useAuth0 lambda.
What was this:
export const useAuth0 = () => useContext(Auth0Context);

Needed to be this:
export const useAuth0 = () => useContext(Auth0Context)!;


text:
Q: enabling SSL - IIS proxying weblogic server I've enabled SSL on IIS server (running on Windows 2003) using steps mentioned here:
http://www.techpaste.com/2012/01/steps-configure-ssl-iis-windows-2003-server/
It looks like SSL is enabled properly because when I hit:
http://hostname.myhost

I get following in browser:

The page must be viewed over a secure channel The page you are trying
  to access is secured with Secure Sockets Layer (SSL).
Please try the following:
Type https:// at the beginning of the address you are attempting to reach and press ENTER.

I was using this IIS as proxy to my weblogic server. All my configuration was working on HTTP (http://hostname.myhost/myapp/test.jsp).
However when I tried (HTTPS):
https://myhost/myapp/test.jsp

It doesn't work. I get following in browser:
The connection was interrupted

After googling, I found that I'll need to enable HTTPS on weblogic and I'll have to establish trust between IIS plugin and weblogic.
URL - http://docs.oracle.com/cd/E13222_01/wls/docs81/plugins/isapi.html#100382
Section: Using SSL with the Microsoft Internet Information Server Plug-In

I enabled HTTPS on weblogic by checking 'SSL Listen Port Enabled'.
Using keytool and java command, I got pem file as well for corresponding der file for corresponding certificate in DemoTrust.jks.
I added following two keys to iisproxy.ini file:
SecureProxy=ON
TrustedCAFile=c:/mycert.pem

However when I access https://hostname.myhost/myapp/test.jsp, I still get same error in browser.
In iisforward.log I see following:
Fri Aug 02 14:52:29 2013 load properties from: C:\Inetpub\WLS_IIS_Plugin\iisproxy.ini
Fri Aug 02 14:52:29 2013 WLForwardPath: /
Fri Aug 02 14:54:36 2013 TerminateFilter...

I don't see any log in iisproxy.log.
Could anyone please suggest where I am wrong?
Thanks.

A: Reset the iis once...
Before resetting iis the following things make sure...
you have enabled SSL port in weblogic console and make sure you have enabled that port in that server's firewall. otherwise it won't allow any outside/remote communication via that port
you have to bind an ip addess and port in IIS for ssl communication...and you must have to specify SecureProxy=ON in iisproxy.ini(the cert should be physically located..where it is specified in iisproxy.ini file like c:/mycert.pem)


text:
Q: PrestaShop Block Layered isn't working. Just Showing Loading circle everyone.
Yesterday I faced with a prestashop problem, my client ask me to create some filters for his shop. I thought that that will be easy, but when I set up everything in prestashop admin panel, it just showing me a loading circle  icon and it gives Error 500 in console.
 Maybe some of you already had this problem? I already checked .htaccess files, priorities, try to reinstall blocklayered module and so on... But it isn't working. Maybe I miss something? And its still one more thing which didn't let me sleep well. Its that prestashop showing me that my that "mod_rewrite" is off in my server. But its already on on my .htaccess file. How can I check is it turn on or not? And can it be a problem of not working items filter? Or maybe someone know some other free ajax filters for prestashop?
.htaccess file:
<IfModule mod_rewrite.c>
<IfModule mod_env.c>
SetEnv HTTP_MOD_REWRITE on
</IfModule>

RewriteEngine on

#Domain: alyvatau.lt
RewriteRule . - [E=REWRITEBASE:/]
RewriteRule ^api$ api/ [L]

RewriteRule ^api/(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]

# Images
RewriteRule ^([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$1$2$3.jpg [L]
RewriteRule ^([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$1$2$3$4.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$1$2$3$4$5.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg [L]
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg [L]
RewriteRule ^c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]
RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]
# AlphaImageLoader for IE and fancybox
RewriteRule ^images_ie/?([^/]+)\.(jpe?g|png|gif)$ js/jquery/plugins/fancybox/images/$1.$2 [L]

# Dispatcher
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ %{ENV:REWRITEBASE}index.php [NC,L]
</IfModule>

AddType application/vnd.ms-fontobject .eot
AddType font/ttf .ttf
AddType font/otf .otf
AddType application/x-font-woff .woff
<IfModule mod_headers.c>
    <FilesMatch "\.(ttf|ttc|otf|eot|woff|svg)$">
        Header add Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

#If rewrite mod isn't enabled
ErrorDocument 404 /index.php?controller=404

# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again


text:
Q: Backbone - How to pass dynamic server JSON output from One View to another View as an input to get the another level of category dynamically I am trying to pass the JSON output from one view to another view. But I stuck here as I don't know to how move forward. It seems, some event handling, triggers may help. I searched, but I couldn't figured out! I pasted my complete code. Backbone+underscore+jquery front-end with restful back-end. There 5-7 sub-category level. When we print the main category, it should have a hyperlink to navigate to the next sub-category & the sub-category will have links to another level. I successfully got main-category output. Now the main category view has some JSON values to link to the sub-category. I just need some idea on how to pass the JSON value to the another view(sub-category view) to post it to server to get the sub-category list. Hope, it makes clear.

    var MainCategoryListResponse = Backbone.Model.extend({
            urlRoot:'/main-dirctory',
            defaults:{
                "clientCompanyName":"GOD",
                "clientCountry":"ALL Country"
                "mainCategoryId":"", // This Id from server is used to get the sub-category list
                "rootId"":''// This Id from server is used to get the sub-category list
            }

        });

        var MainCategoryListResponseCollection = Backbone.Collection.extend({
            model: MainCategoryListResponse,
            url: '/main-dirctory'
        });

        var MainCategoryListView = Backbone.View.extend({
            el: '.page',
            render: function() {
                 var that = this;
                    var mainCategoryListResponseCollection = new MainCategoryListResponseCollection();

                 //  mainCategoryListResponseCollection.set({"typeId": "1"});
                    mainCategoryListResponseCollection.fetch({
                          type: 'POST',
                          data: JSON.stringify({'typeId': '1'}), //Passing the value manually here in the first parent view
                          contentType: "application/json",
                          dataType: "json",
                          success: function (mainCategoryListResponseCollection) {
            var template = _.template($('#user-list-template').html(), {mainCategoryListResponseCollection: mainCategoryListResponseCollection.models});
            that.$el.html(template);

         }
                      });
            }
        });

        var SubCategoryListView = Backbone.View.extend({
            el: '.page',
            render: function() {
                 var that = this;
                    var subCategoryListResponseCollection = new SubCategoryListResponseCollection();
                    subCategoryListResponseCollection.fetch({
                          type: 'POST',
                          data: JSON.stringify({'???': '???'}), //here I need to pass the dynamic value from the above view. The dynamic value should be like "mainCategoryId": "5", "rootId": "0" which is getting printed in the each loop down here.
                          contentType: "application/json",
                          dataType: "json",
                          success: function (subCategoryListResponseCollection) {
            var template = _.template($('#user-list-template').html(), {subCategoryListResponseCollection: subCategoryListResponseCollection.models});
            that.$el.html(template);

         }
         });
         }
        });

var Router = Backbone.Router.extend({

    routes:{
        "":"main_directory"
 }
});
var MainCategoryListView = new MainCategoryListView();
var router = new Router();
router.on('route:main_directory', function() {
    MainCategoryListView.render();

});
Backbone.history.start();

</script>


text:
Q: Spherical projection of a pointcloud to keep it organised As stated in this question, it is necessary to have an organized pointcloud for most functions, I was wondering how to convert my uorganized pointcloud to organized? Something like "So I organized it using spherical projection" is mentioned in the original question.
My final pointcloud which needs to be organized is the result of concatenation after transformation of two individual pointclouds from two real sense D415 cameras.


text:
Q: IE 9 Prompt to allow access data sources across domains My application has huge issues with internet explorer 9 and below. Because their default settings are that they do not allow access to data across domains.
I feel like I've attempted everything and because each of my clients have their own domain, I am unable to make the hack that makes an iframe.
So my question is:
Is there a way that you can prompt the user to set the setting: access data sources across domains to enabled?


text:
Q: flutter - add to firestore collection if not exists otherwise update In flutter, I am using firestore to store my users that log in.
I want if a user login the first time to add his information to a collection.
If he logout, then logs in, I want to update his document in the collection.
To check if there is a document corresponding to the user, I want to check by his 'id' which is a field in the document, and not by the document tag, since I get the 'id' from firebase api.
Here is the add which is working correctly
_firestore.collection('profiles').add({
        'firebase_id': profile['user_id'],
        'first_name': profile['first_name'],
        'last_name': profile['last_name'],
        'login_date': profile['login_date']
});

I tried to check if the user exists using the following but it returns always false
bool isEmpty = await _firestore
            .collection('profiles')
            .where('firebase_id', isEqualTo: profile['user_id'])
            .snapshots()
            .first
            .isEmpty;

A: Here an example that will check if the users exist or not and if it exists it will overwrite the previous data by simply using merge.
DocumentReference ref = _db.collection('users').document(user.uid);

return ref.setData({
  'uid': user.uid,
  'email': user.email,
  'photoURL': user.photoUrl,
  'displayName': user.displayName,
  'lastSeen': DateTime.now()
}, merge: true);

}
I hope it will help you

A: when you save users in the firestore make the documentID equal to userID.
Firestore.instance.collection('profiles').document( profile['user_id']).setData({
        'firebase_id': profile['user_id'],
        'first_name': profile['first_name'],
        'last_name': profile['last_name'],
        'login_date': profile['login_date']
});

then check if exists.
 bool userExists=(await Firestore.instance.collection('profiles').document('userid').get()).exists;


text:
Q: Op Amp Unity gain gives an unexpected constant saturated output I have this following circuit;
I use an Arduino DUE to send a 12-bit DAC output and I want to feed this in an Op Amp.
Every ground is tied to the same ground.
The Op Amp is ADA4000-2 from Analog device.
The USB power is used and DUE (SAM3 series MCU) outputs DAC output to the Op Amp input.

I created a DAC signal that goes up/down from 1.55V. As you see the yellow signal (channel 1), this 1.55V is like a DC-Offset.
The blue signal (channel 2) is the Vout pin, the output of the Op Amp.
If you take a close look at the part where the values are lower than 1.55V from channel 1,
I was expecting the same decreasing pattern from channel 2.
However, that part is constant to 4.1V and I think the output becomes saturated.
I cannot understand this reason.
What seems to be the reason for this constant output?
I wanted a unity gain, but I cannot find the reason for this.
Appreciate your help.


text:
Q: XPath Expression returns nothing for //element, but //* returns a count I'm using XOM with the following sample data:
Element root = cleanDoc.getRootElement();
//find all the bold elements, as those mark institution and clinic.
Nodes nodes = root.query("//*");

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml">
    <head>
        <title>Patient Information</title>
    </head>
</html>

The following element returns many elements (from real data):
//*

but something like
//head

Returns nothing. If I run through the children of the root, the numbers seem to match up, and if I print the element name, everything seems to look correct.
I'm taking HTML, parsing it with tagsoup, and then building a XOM Document from the resulting string. What part of this could go so horribly wrong? I feel there's some weird encoding issue going on here, but I'm just not seeing it. Java Strings are Strings, right?

A: Your document has a default namespace, which means in the XPath model all the elements are in that namespace.
The query should be //html:head. You will have to supply the namespace mapping to the XPath query.
Note that while the XPath expression uses a namespace prefix, it is the namespace uri that must match.
XPathContext ctx = new XPathContext("html", "http://www.w3.org/1999/xhtml");
Nodes nodes = root.query("//html:head", ctx );


text:
Q: How to implement this nested flow with optionals? I've have a method that takes String as an input and should also return a String.
The following ASCII art presents the logical flow:
Option<A> optA = finder.findA(input);

          optA
           /\
isEmpty() /  \ isDefined()
         /    \
 "ERR_1"       Option<B> optB = finder.findB(optA.get().bid);
                      / \
           isEmpty() /   \ isDefined()
                    /     \
                "ERR_2"    opt2.get().id

Basically for given input I'm looking for A object which is returned wrapped in an Option. Then is A is present I'm looking for B - wrapped in an Option too, otherwise return ERR_1. Then if B is present return it's id, otherwise return ERR_2.
I'm wondering how it could be implemented using optionals (or pattern matching maybe?) in a nice and concise way (without any ifology) - possibly in one-liner.
Could anyone please suggest something?
Source code to try out can be found here.

A: It looks like you have 3 possible exit points:

*

*optA empty                   -> "ERR_1"

*optA not empty && optB empty -> "ERR_2"

*both not empty               -> optB.get().bid

You can achieve this by doing this with Javaslang:
 optA
   .map(a -> finder.findB(a.bid)
      .map(b -> b.bid)
      .getOrElse("ERR_2"))
   .getOrElse("ERR_1");

If optA is empty, we will jump straight to orElse("ERR_1")
If optA is not empty, we are using the value stored inside for getting value b.bid or "ERR_2" in case of optB emptiness.
Also, in pure Java 8, it would look like this:
optA
  .map(a -> finder.findB(a.bid)
    .map(b -> b.bid)
    .orElse("ERR_2"))
  .orElse("ERR_1");

A: Since you're using javaslang, Try seems to be a better choice because it propagates the error throught the chain, while Option only propagates its "emptiness".
If you can change findA and findB to return Try you get:
Try<B> b = finder.findA(input)
    .flatMap(a -> finder.findB(a.bid))

If you can't, then:
Try<B> b = finder.findA(input).toTry(() -> new Exception("ERR_1"))
    .flatMap(a -> findB(a.bId).toTry(() -> new Exception("ERR_2")))

That gets a tentative B, I'm unsure if you want to collapse the valid value and the error into the same value, if that's the case then:
String value = b.getOrElseGet(Throwable::getMessage)

If you have an issue with creating pointless exceptions, you can use an Either in each of the find operations, where the left value is your error type. That seems to model the problem better, but may have the downside of longer type signatures, depending on how you split up the expressions.

A: You'll want to adapt this to your code, but this is an approach I'd use.
First, isolate the errors you want to encapsulate for each point of failure.
Supplier<? extends RuntimeException> missingAException = IllegalStateException::new;
Supplier<? extends RuntimeException? missingBException = IllegalStateException::new;

Doing this allows you to write a lambda later on to provide a specific error message if you so desire.
Now, we write the optionals.
Optional<A> optA = finder.find(input);
Optional<B> optB = finder.findB(optA.orElseThrow(missingAException));

To extract optB, use the same pattern as we did for optA.
B value = optB.orElseThrow(missingBException);


text:
Q: Calculating tcp packet checksum i am following a guide in
https://www.securitynik.com/2015/08/calculating-udp-checksum-with-taste-of_3.html
50 C7 BF 65 B5 CA 70 F3 95 00 A0 AF 08 00 45 00 00 28 3F 1C 40 00 80 06 00 00 C0 A8 01 A3 D2 F2 F3 65 C2 00 1A 4C 9F 5E 98 B7 70 8A A9 B8 50 10 40 18 88 BE 00 00
This is my packet..
source Ip 192.168.1.163     1100 0000 1010 1000              C0 A8
                            0000 0001 1010 0011              01 A3
dest IP 210.242.243.101     1101 0010 1111 0010              D2 F2
                            1111 0011 0110 0101              F3 65
TCP pro 0/6                 0000 0000 0000 0110              00 06
Padding
Length                      0000 0000 0001 1110              00 14 ? (Not sure)
S-Port       49664          1100 0010 0000 0000              C2 00
D-Port       6732           0001 1010 0100 1100              1A 4C
Seq #        2673776823     1001 1111 0101 1110              9F 5E
                            1001 1000 1011 0111              98 B7
Ack #        1888135608     0111 0000 1000 1010              70 8A
                            1010 1001 1011 1000              A9 B8
Flag #                      0101 0000 0001 0000              50 10
Window #     16408          0100 0000 0001 1000              40 18
Sum:                                                       5 86 49
                                          Adding first byte: 86 4E
                                         in Binary: 1000 0110 0100 1110
                                         Flip bit: 0111 1001 1011 0001
                                             My checksum is  79 B1
                                  but the packet checksum is 88 BE
the only info i was not sure of is the padding length.. which it was not explained well.. My understanding is.. it is either
by adding header length which in this case is 20 bytes + any payload bytes.. which there is none in my case.. so 14 in hex is 20 dec.. or maybe adding the flag number to it.. which 20 + 10 is 30.. i also tried both and the checksum still doesn't match?
Is my math wrong? or logic wrong..
Thanks for your help..
Chelvan.

A: IPv4 uses the checksum to detect corruption of packet headers at network layer. The TCP applies at transport layer an extra checksum to protect the packet payload as an addition to the header-checksum of IP. 12-byte TCP pseudo header is created prior to TCP checksum calculation. TCP pseudo header length comprises source address(4 byte), destination address(4 byte), reserved(1 byte), protocol(1 byte), TCP segment length(2 byte).
Pseudo header as 12 byte / 96 bits is placed before the the TCP segment then, the checksum is computed over the entire set of data (pseudo header plus TCP segment). The value of the checksum is placed into the Checksum field of the TCP header, and the pseudo header is discarded.
Calculation algorithm for the TCP and IPv4 checksums is the same. The data is processed 16 bits or 2 bytes at a time and those 16 bits as words are added using the ones-complement arithmetic. At the end of additions, the result is negated in ones-complement by taking the binary not, and the result is stored in TCP header by the source endpoint. At destination endpoint same calculation is repeated by setting the checkum to zero.
You can try to calculate it using below method from this utility class
public static short checksum( byte[] source ,byte[] destination ,byte protocol,
                              short  length ,
                              byte[] message ,
                              int offset )


text:
Q: Visual studio 2015 community report viewer version 12 Error getting extra margin using c# I am using Visual studio 2015 community report viewer version 12 to show rdlc reports in my c# project.
here is normal A4 page report

its works fine for windows xp, vista, win 7 on client PCs but when same application is installed on Windows 10 64 bit then I am facing problem like below

as you can see in above image there are unnecessary margins are coming from right and bottom side as well as font size also reduced. but when I export report to PDF then there is no problem in generated PDF its same as report which I designed.
What was I Tried :

*

*I Installed MICROSOFT® REPORT VIEWER 2015 RUNTIME from
https://www.microsoft.com/en-us/download/details.aspx?id=45496

*Installed Microsoft® SQL Server® 2014 Feature Pack (System CLR Types For SQL
Server 2014)

*tried  to Export RDLC directly to Printer using below code

Code for Print Class
public static class _cWainfoPrintReport
    {
        private static int m_currentPageIndex;
        private static IList<Stream> m_streams;
        public static Stream CreateStream(string name,
        string fileNameExtension, Encoding encoding,
        string mimeType, bool willSeek)
        {
            Stream stream = new MemoryStream();
            m_streams.Add(stream);
            return stream;
        }
        public static void _mExport(LocalReport report, bool print = true, double _pageWightInches = 8.27, double _pageHeightInches = 11.69, double _MarginTopInches = 0.025, double _MarginLeftInches = 0.025, double _MarginRightInches = 0.025, double _MarginBottomInches = 0.025)
        {
            string deviceInfo =
            @"<DeviceInfo> <OutputFormat>EMF</OutputFormat> <PageWidth>" + _pageWightInches + "in</PageWidth> <PageHeight>" + _pageHeightInches + "in</PageHeight> <MarginTop>" + _MarginTopInches + "in</MarginTop> <MarginLeft>" + _MarginLeftInches + "in</MarginLeft> <MarginRight>" + _MarginRightInches + "in</MarginRight> <MarginBottom>" + _MarginBottomInches + "in</MarginBottom> </DeviceInfo>";
            Warning[] warnings;
            m_streams = new List<Stream>();
            report.Render("Image", deviceInfo, CreateStream,
            out warnings);
            foreach (Stream stream in m_streams)
                stream.Position = 0;
            if (print)
            {
                _mPrint(_pageWightInches, _pageHeightInches, _MarginTopInches, _MarginLeftInches, _MarginRightInches, _MarginBottomInches);
            }
            report.ReleaseSandboxAppDomain();
        }
        // Handler for PrintPageEvents
        public static void _mPrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new
            Metafile(m_streams[m_currentPageIndex]);
            // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
            ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
            ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
            ev.PageBounds.Width,
            ev.PageBounds.Height);
            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);
            // Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }
        public static PaperSize CalculatePaperSize(double WidthInCentimeters, double HeightInCentimetres)
        {
            int Width = int.Parse((Math.Round((WidthInCentimeters * 0.393701) * 100, 0, MidpointRounding.AwayFromZero)).ToString());
            int Height = int.Parse((Math.Round((HeightInCentimetres * 0.393701) * 100, 0, MidpointRounding.AwayFromZero)).ToString());

            PaperSize NewSize = new PaperSize();
            NewSize.RawKind = (int)PaperKind.Custom;
            NewSize.Width = Width;
            NewSize.Height = Height;
            NewSize.PaperName = "Letter";

            return NewSize;

        }
        public static void _mPrint(double _pageWightInches = 8.27, double _pageHeightInches = 11.69, double _MarginTopInches = 0.025, double _MarginLeftInches = 0.025, double _MarginRightInches = 0.025, double _MarginBottomInches = 0.025)
        {
            if (m_streams == null || m_streams.Count == 0)
                throw new Exception("Error: no stream to print.");
            PrintDocument printDoc = new PrintDocument();

            PaperSize RequiredPaperSize = CalculatePaperSize(_pageWightInches * 2.54, _pageHeightInches * 2.54);
            bool FoundMatchingPaperSize = false;
            for (int index = 0; index < printDoc.PrinterSettings.PaperSizes.Count; index++)
            {
                if (printDoc.PrinterSettings.PaperSizes[index].Height == RequiredPaperSize.Height && printDoc.PrinterSettings.PaperSizes[index].Width == RequiredPaperSize.Width)
                {
                    printDoc.PrinterSettings.DefaultPageSettings.PaperSize = printDoc.PrinterSettings.PaperSizes[index];
                    printDoc.DefaultPageSettings.PaperSize = printDoc.PrinterSettings.PaperSizes[index];
                    FoundMatchingPaperSize = true;
                    break;
                }
            }

            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("Error: cannot find the default printer.");
            }
            else
            {

                printDoc.PrintPage += new PrintPageEventHandler(_mPrintPage);
                m_currentPageIndex = 0;
                printDoc.Print();
            }
        }
        public static void _mPrintToPrinter(this LocalReport report)
        {
            _mExport(report);
        }
        public static void _mDisposePrint()
        {
            if (m_streams != null)
            {
                foreach (Stream stream in m_streams)
                    stream.Close();
                m_streams = null;
            }
        }
    }

Code on Print Button
PrintViewer _PJobEntry = new PrintViewer();
DataTable dt = new DataSet1.MainTableDataTable();
dt.Rows.Add('vales for dataset');
_PJobEntry._RptView.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dt));
_PJobEntry._RptView.LocalReport.ReportEmbeddedResource = "WAINFOBUSSOLN.Printing.RptSaleInvoice02.rdlc";
_PJobEntry._RptView.SetDisplayMode(DisplayMode.PrintLayout);
_cWainfoPrintReport._mExport(_PJobEntry._RptView.LocalReport, true, 8.27, 11.69, 0.25, 0.25, 0.28, 0.25);

but its also printing same as describe above
the same application is running on my PC with Windows 10 64 bit but not working after deployment on client PC having Windows 10 64bit
On Client PC .Net 4.0 framework, SQL Server 2008, Windows 10 64 bit installed
How to resolve it.

A: I don't believe this issue has anything to do with any of the tools installed or only Windows 10 64-bit in particular for that matter.
Rather, it's an issue with DPI as mentioned by jdweng & Reza Aghaei. More specifically, high-DPI devices.
Not sure if you have noticed, but both the images you have uploaded are of different pixels and the image with low pixel shows proper rendering of the report. This arguably supports the point of the scaling issue being caused due to High DPI.

Now, there are many articles, posts and questions on this. But the one that comes very close of providing some sort of right direction to the victims is the one on Microsoft Support Portal which seems to have few possible resolutions (yes, plural) and workarounds (again, plural) provided for this behavior.
You can find this article here: https://support.microsoft.com/en-au/help/3025083/windows-scaling-issues-for-high-dpi-devices
I believe, the workaround I am quoting below should help you for time-being.

Change application properties
In Explorer or on the Start menu, right-click the application name, select Properties, select the Compatibility tab, and then select the Disable display scaling on high DPI settings check box.
Note:
In Windows 10 Version 1703 and later version of Windows, the text of the Disable display scaling on high DPI settings option is changed to Override high DPI scaling behavior, scaling performed by: Application.

A: You should disable the DPI unawareness and set your application to DPI aware - even though it is not, in order to prevent scaling.
On newer versions of Windows 10, I found a different solution: you can have your application in any DPI-awareness state, but have specific windows you open in different DPI-awareness states.
Unfortunately though, I am still looking for a state that is working 100% of the time, but 2 options seem to be good candidates.
Change DPI awareness
            if (WindowsVersion.WindowsIs10_1809OrNewer) // this you can get yourself, need to look at build number
            {
                // https://github.com/microsoft/Windows-classic-samples/blob/master/Samples/DPIAwarenessPerWindow/client/DpiAwarenessContext.cpp
                _prevHosting = WinAPI.SetThreadDpiHostingBehavior((IntPtr)WinAPI.DPI_HOSTING_BEHAVIOR.BEHAVIOR_MIXED);

                _prevDPIContext = WinAPI.SetThreadDpiAwarenessContext((IntPtr)win10DPIAwareness); // WinAPI.ContextDPIAwareness.Context_UnawareGdiScaled);
            }

Then you can open your new dialog in this thread, this dialog would contain the ReportViewer.
change back later
                    if (WindowsVersion.WindowsIs10_1809OrNewer)
                    {
                        WinAPI.SetThreadDpiAwarenessContext(_prevDPIContext);
                        WinAPI.SetThreadDpiHostingBehavior(_prevHosting);
                    }

Helpers
    public static bool WindowsIs10_1809OrNewer
    {
        get { return WindowsIs10OrNewer && Environment.OSVersion.Version.Build >= 17763; }
    }

    public static bool WindowsIs10OrNewer
    {
        get { return Environment.OSVersion.Version >= new Version(10, 0); }
    }

    public enum DPI_HOSTING_BEHAVIOR
    {
        BEHAVIOR_INVALID = -1,
        BEHAVIOR_DEFAULT = 0,
        BEHAVIOR_MIXED = 1
    }

    public enum ContextDPIAwareness
    {
        Context_Unaware = -1,
        Context_SystemAware = -2,
        Context_PerMonitorAware = -3,
        Context_PerMonitorAwareV2 = -4,
        Context_UnawareGdiScaled = -5,
    }

You could try Context_UnawareGdiScaled - which actually scales ReportViewer correctly - often - or Context_PerMonitorAware to disable the scaling.
I had issues here in RDP sessions, if you do not have that, probably you are fine with those options.
Also, sadly, this only works in newer Windows 10 versions. Since those updates are not optional, probably most Windows 10 users will be on the new version, and with Windows 8 being unpopular and all other Windows versions out of support, a lot of users should be on a recent Windows 10 version.
Still far from perfect, of course.
BTW, for older versions of Windows, I just disable scaling via SetProcessDpiAwareness, did not find a better way there.


text:
Q: Why are there so few robots in Star Trek? Okay, obviously beyond Data and the Soong-type androids. But seriously, we have more robots in our daily life now than there apparently are on Trek. Is there a canon answer why not? It seems like Star Wars is more on the nose in this regard - it's unclear why all dirty/dangerous/boring work wouldn't be done by robots (anthropomorphic or not).

A: The Doctor from Voyager basically became a robot with his personal holographic projector device.
The computers are obviously sophisticated enough to support interactive artificial intelligences (holograms), it seems to me the computer could also just pipe that behavior into a humanoid robot. Even if the robot isn't independent, it would wirelessly be controlled by the computer based on the behavior of the program.
Perhaps Star Fleet decided to follow the convictions of Werner von Braun:

Man is the best computer we can put aboard a spacecraft, and the only one that can be mass produced with unskilled labor.

A: This isn't an in-universe answer to the question, but when I was pitching stories to Trek, I went over some storylines with my agent before pitching and was given a strict "No androids" rule.  She (my agent) told me that it was Jeri Taylor's position that Data was unique and that there were no other robots or androids of that level of sophistication in the Federation.  I notice this rule held, since the only other androids were Lore, Data's Mother (Juliana Tainer) and Data's daughter (Lal).
There was no in-universe rationalization and I never did find out what Jeri's reasoning for that was. When you're pitching to producers, it's not exactly a good time to say, "Why did you make this rule?" - you just accept the rule and don't argue!
Obviously it's been a while, but I also remember being told not to pitch anything about Jack Crusher, avoid the "space seed" stories (not Khan, but about the Big E finding some spore or seed in space that grows into an alien) and if Q comes back, do NOT include any references to Vash or Q-pid because they would rather just forget that episode ever happened.  I can't remember the other off-limits stories, unfortunately.

A: This is from an exploration viewpoint.
Star Trek is supposed to be a reflection of what we want to do in the future. We don't want to explore the galaxy using robots because exploration by robots is a compromise. Star Trek is a society fueled by exploration.
We celebrated when we sent the first probes on the moon but we celebrated even more when we sent men on the moon.
We celebrated when we sent the first probes on Mars, but the truth is we would rather send humans to Mars (the act of sending a probe is a compromise it is proxy exploration - we can't do it ourselves yet so we compromise)
We don't exactly celebrate everytime the Voyager1 space probe gets deeper into space. We don't exactly feel as 100 percent real space explorers.
If we ever develop true warp drives, we wont be sending a ship full of Datas or robots to command and explore on our behalf to do proxy exploration. We will want to go ourselves with robots only in support roles.

To borrow quotes from Enterprise episode Fight or Flight
ARCHER: How about the Vulcan star charts?
T'POL: We have limited data on the course Starfleet has assigned you.
ARCHER: There are thousands of star systems along this path. There must have been something that piqued your people's interest. A sentient species, a trinary star cluster.
T'POL: We don't select our destinations by what piques our interest.
ARCHER: Vulcans always need a logical and pragmatic reason.
T'POL: My people don't share your enthusiasm for exploration. (squeak) Space is vast, Captain.

The Vulcans gave humans tons of data about planets and species discovered by Vulcans. But still humans insisted on doing the exploring themselves. We don't like proxy exploration not by Vulcans and not by robots or androids.

A: Nanites are a type of robot and got a story or two in TNG.  I seem to remember there being a repair bot type of thing in one TNG story as well.  And of course, the Borg are robots after a fashion (more cyborgs, really though).
It could simply be that there were none in TOS, so there were to be none in any later shows.  Robots were thought of and in many stories by the 60s, so perhaps Gene Roddenberry didn't like robots.  It's not so uncommon - many SciFi writers and editors of that time didn't like aliens, or robots or atomic mutations, etc

A: I think robots and artificial intelligence is an area that writers would rather avoid. Real artificial intelligence (as embodied in any myriad of physical or audible forms) would be impossible for humans to recognize as "different" because they had been designed to perfectly imitate human intelligence.  That obvious identity ambiguity would be extremely problematic for a writer trying to create a story populated by Joseph Campbell-ish archetypes.  They would be servants. slaves, and thus evoking unpleasant social memories and associations.  And the obvious question arises: what if they become self-aware?  This is probably why the "no androids/no robots" edict came about.  The ambiguities would be problematic to story development, especially when you have a small group of defined characters
Although I believe the infinite possibilities (and I've already written many) would present a huge and dynamic world of endless and fascinating narratives.

A: There were androids in TOS: the Mudd androids in the episode "I, Mudd", built "for the purpose of performing necessary service functions".
Memory Alpha has a list of various self-aware machines, as well as a list of self-aware programs. These could be considered either advanced robots or simple androids due to their capacity to think and perform independent judgements.
Arguably, a ship's computer (along with the whole ship itself) could be considered a giant robot, capable of interacting with it's human operators and performing various tasks requested of it.

A: From a pure 'TV production' standpoint, it could be that without all of the CGI technology that is available today, that it was impractical (given time and budgetary constraints) to have the art department create robots. Back then there was no way to make them move without being clunky or hokey looking, although I think that it's an area that could have been explored, especially a robot that was a left over from an alien race, perhaps an alien race that has long perished, yet the robot it still performing it's function. As both a filmmaker and a Star Trek fan, I'm seriously considering making a fan film with an alien robot.

A: There were the Exocomps and the Nanites.  Also, the automated spacedock that NX-01 encountered.  I imagine there must have been more manufacturing-type robots, but we never really see that side of life in the Federation.
Of course, after Exocomps and Nanites became self-aware, maybe Starfleet started frowning on new autonomous tech, wary of dealing with creating new life forms.

A: I would argue - in line with the other answers here - that there are robotic devices in ST, but they are different and more ubiquitous than we see today. The Borg are roboticly enhanced, the Doctor is a holographicly driven robot, I am sure that there are robotic features making the ship function year on year that we never hear about.
And the Borgs Nanobots - they are robots, of a sort. Replicators - surely they would count as manufacturing robots. What there is not much of is visible or anthropomorphic robots, because they do not need to be visible or human-like. Humans are better at it than robots, so - apart form a few exceptions - let the humans get on with their parts.
And there are relatively few dirty/boring/dangerous jobs left, for a vessel of that size. Some of the routine work, I would argue, is retained for a sense of discipline and order. And the human maintenance work is done because humans are better at bug-fixing-type problem solving than computers.
And yes, sometimes people need to be in difficult situations for plot purposes. But that is a completely different issue.

A: Lieutenant Commander Airiam from Star Trek: Discovery is at least in part robotic, even if her true nature is a bit unclear and not fully disclosed.

She has been described in various ways, from "synthetic-Human hybrid", to "augnemnted alien" to "augmented human", but it appears rather clear that she is at least in part cybernetic.

A: In the TOS era, there are examples of both human-made AI and alien-made AI (sometimes in anthropomorphic form e.g. "I, Mudd", "What are Little Girls Made of?", sometimes in the form of "space furniture" e.g. "The Ultimate Computer", "The Return of the Archons").
In all cases, they end up adversaries of the Enterprise crew. They are depicted as overly constrained by rigidly logical decision making, which leads to:

*

*Undesirable actions - blowing up friendly spaceships, hijacking (or threatening to hijack the Enterprise), killing, imprisoning, or threatening to kill or "absorb" members of the Enterprise landing party, etc.

*Their being outsmarted by illogical humans

In the Start Trek universe, androids as capable as humans without flaws that make them downright dangerous are very difficult things to create. It took until TNG era for Data to appear, and his creation was so difficult he remained a unique artifact. His close copies Lore had a more human-like manner but was thoroughly antisocial, and B4 was next to useless until he effectively had Data's essence downloaded into him, ambiguously becoming replacement Data.
Out-of-universe, Data's role is to look upon humanity as an outsider amongst the (mostly) human crew; we only need the one viewpoint, so there is need of only one "Data". And, Star Trek is about human adventures in space. If there were lots of "good" robots, it could easily make the humans seem superfluous, and so much for the adventures of humans in space.
Even though we have lots of robotics in our modern world, Star Wars-like robots may be very far into our future, beyond the Star Trek settings. To imbue a mechanical device with the sort of adaptive behaviors we see in R2-D2 or C-3P0 would make it unpredictable. If you can't predict the machine's behavior, how much confidence can you place in it choosing to do the "right" or desirable thing when a human life is on the line? And without such adaptability, how useful would it really be? To get it right could take many, many decades of further development. Star Trek may have gotten it right but for the wrong reasons. The absence of robots in Star Trek served storytelling, but might turn out to be more-or-less right.

A: Gene Roddenberry's Star Trek is pre-Aibo/iPhone era. The stories tend to lean against the original written work. Star Trek series don't avoid robots because they weren't anticipated. No one could have known what things like Arduino or SBCs would mean for us. It gave us options and interests to think about what we might expect to see in the future.

A: The Federation has evolved beyond robots. They deal with advanced computer technology with self aware systems. The super system known as "Computer" is the Federations main source of robotic intelligence.
Why robots are not used by other alien races is a mystery, theres no reason why that is missing from the Star Trek mythology. Perhaps they are universally impractical.


text:
Q: Two keyboards. Can I re keymap just one? I have my main keyboard, and I also have an old PS/2 keyboard that I'd like to re keymap without affecting the other keyboard. What's the best way to do this?
I'm running Windows 10. My main keyboard is USB, and the other is a generic PS/2 keyboard.

A: I came across a program called HID Macros. And it's exactly what I was looking for.
http://www.hidmacros.eu/


text:
Q: I don't Understand - *(uint*)((byte*)p + Offset) I am having trouble understanding this code and would like a good explanation.
The following function takes in a hex file and modifies the address without overwriting everything else.
Can someone explain to me how its doing that?
unsafe void WriteUint32(void* p, int Offset, uint value)
        {
            *(uint*)((byte*)p + Offset) = value;
        }

A: If we ignore Offset, you have
*(uint*)((byte*)p) = value;

which is just assigning value to what p points to, interpreted as a uint.
Adding Offset just changes the pointer to where value is being assigned.


text:
Q: Releasing Audio - Cocoa Xcode (Memory Management) So in my previous question FOUND HERE, I was trying to find the most optimal way for playing a "jump" sound every time I make my sprite jump in my iOS Game...
For some reason today, I've become worried that I'm loading the audio file millions of time and wasting memory :(
Anywho, the following has been suggested to me, (so every time I jump by tapping the screen, the sound is loaded and played)...
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
    {
            //NSString *
            jumpSound = [[NSBundle mainBundle] pathForResource:@"boing" ofType:@"mp3"];

            //AVAudioPlayer *
            jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];

            [jumpAffect prepareToPlay];
            [jumpAffect play];

            //then, make sprite jump
            jumpUp = 16;
    }

The above method allows me to press the jump quickly and restart the audio loop even if the previous loop (from the previous jump) hasn't finished yet.
It's worth baring in mind that this could happen hundreds of times a minute (or more realistically a couple of times a second)...
Is this a concern? Do I need to release the tracks when done with the method/game loop?

A: I think your last question was totally incorrect. AVAudioPlayer has too much latency for a game. When you jump the sound might happen a second later instead of immediately when you want it to. If you wan't to play a sound a million times a minute you should use AudioServices as so:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     NSURL *pathURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"boing" ofType:@"wav"]];

     SystemSoundID audioEffect;
     AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
     AudioServicesPlaySystemSound(audioEffect);
     //then, make sprite jump
     jumpUp = 16;
}

You would have to convert your mp3 to a wav or caf. But I think the tradeoff is worth it...


text:
Q: Responsive design: How to resize images/background images and align divs vertically? I am experimenting with responsive design. My images are not currently resizing. In my markup, I also have background images applied to certain divs which needs to be resized.
Here is the HTML view: http://jsbin.com/emojeg/2
See the code here: http://jsbin.com/emojeg/2/edit
For screen width between 800px and 1100px, I'd like to resize the images. For anything below 800px, I'd like to align the picture frames vertically - 1 or 2 per row whatever the screen width permits.
Currently when I resize the browser to the narrower width, up to 2 of the frames wrap to the next row but if I keep resizing further, the picture frame's background seems to cut off and some of the images seem to disappear. Not sure how to fix this.

A: It's because that slider you're using has loads of absolute positioning and fixed widths/heights. I'd recommend using something that is actually responsive, like Flexslider (http://www.woothemes.com/flexslider/)
But if you don't want to do that, you can remove the position:relative and the fixed height from the .mrpv_container class --
.mrpv_container {
    width: 100%;
    height: 710px;
    position: relative;
    overflow: hidden;
}

The rest of the CSS would probably have to be cleaned up also, but does that give the desired effect?

A: To get your images and backgrounds to resize correctly I'd suggest the following changes.
First set your image width and height with percentages, allowing enough space for the frame around the edges, and use position:relative to add a percentage offset from the top rather than setting a margin. You don't need to worry about the horizontal position, since it's already centered, unless you want to adjust it a little to account for the fact that your frame image isn't perfectly even.
ul.mrpv_slider li div img {
    position:relative;
    top:11%;
    width:67%;
    height:78%;
}

Then add background-size:100% 100% to the *image_container* so the background image for the frame resizes to match the container as well.
ul.mrpv_slider li div.image_container {
    text-align:center;
    background-image:url(http://i36.tinypic.com/5feusn.png);
    background-position:bottom;
    background-repeat:no-repeat;
    margin-right:10px;
    display:inline-block;
    zoom: 1;
    *display: inline;
    height:324px;
    width:250px;

    /* this is the line you need to add */
    background-size:100% 100%;
}

At that point, you can override the width and height of the container in your media queries and the images and frames will all adjust themselves appropriately.
I'm not exactly sure what you intended to do with the layout as the window size changed, but your current media query that sets the width to 100% and height to auto is definitely not going to work.
As an example though, you could make the images half size when the screen is less than 600px wide with a query like this:
@media screen and (max-width: 600px) {
    ul.mrpv_slider li div.image_container {
        height:162px
        width:125px;
    }
}

A: I too have been experimenting with responsive design and found Twitter's "Bootstrap" to be amazingly helpful. It's only 3 files and I build all my sites with it. Check it out if you haven't already: http://twitter.github.io/bootstrap/

A: Well I have used twitter bootstrap as well as http://responsiveimg.com/ for making images responsive and fix the aspect ratio as well according to the screen and image size.
If you are using an image slider then jquery bxslider is also very helpful


text:
Q: Getting the selected value from radio buttons into the database So I have an html table, and I am using a particular cell's value in each row to generate an array (using .split("")) and then for each value in the array, I am generating radio buttons using the code provided in a dialog box.
Where I am stuck as of now is: How can I get the value of the selected radio button [multiple selections are allowed], and submit this value to the database.
I have provided the code which I am using the get the cell value from the current row, as well the code which I am using to generate the radio buttons.
I am newbie so please don't mind if something sounds stupid. I am just trying to find my way to learning.
I am sorry if I am not able to explain the problem. I am trying my best.
Thanks.
I have tried using [alert :checked] but nothing comes up. I have not have had much luck coming up with logic / workflows on my own and would love to have a direction.

 $(".dialogbox").click(function(){
            $('#divid').dialog('open');
            var $row = $(this).closest("tr");
            var $text= $row.find(".reqcell").text();
            var valarray = new Array();
            valarray = $text.split(",");

## Here (".dialogbox") is the class of a button which when clicked open a dialog which has a div with id = '#divid'. I am using the this.closest(tr) to find the closest row to the button clicked, and then find the cell (whose values are needed), using the class name (".reqcell") for the class.
In the end I use text.split(",") to store these values into an array valarray. ##

## The below code is in continuation to the above mentioned code . I am just dividing it for the ease of understanding.

var buttons = valarray.filter(Boolean).map((valarray,index) => {

            return '<input type="radio" value='+ index +' name='+ valarray +'/><label for='+ valarray +'>'+ valarray +'</label>';
            });
            $("#buttonArea").html(buttons.join(""));});

## Here button area refers to the <span> in which the buttons will be displayed.

As I said before, I have to get the value of selected button/buttons and update it in the database.
If anyone can give me any kind of direction for the same , I will be really obliged.
And again, I am very sorry if the way I am trying to explain things is wrong.
Also, if someone could suggest some good books to learn Java (including the database connections and client-server web-apps building) and jQuery, it will be great.
Thank you everyone for your time.!


text:
Q: How can I get the value from textfield if it appears to be blank after I click another button? The price shows up without problems after i clicked the 'order' submit button
   but it cannot get the value of price anymore once i click the 'pay' button.
   How can i get the value from the textfield without losing is value after i
   click the value. Or some sort of saving it if  that's possible.
    form sample
<?php
if(!empty($_POST['myorder'])){

    $order=trim($_POST['myorder']);

    if($order=="wintermelon"){
    $price = 100 * $_POST['qty'] ;

    if($order=="taro"){
    $price = 110 * $_POST['qty'] ;

    }
    if($order=="caramel"){
    $price = 110 * $_POST['qty'] ;

}

}
}

if(isset($_POST['pay'])){

    **$price=trim($_POST['price']);**

    if(!empty($_POST['cash']) ){

    $cash=trim($_POST['cash']);

    if($cash >= $price){
        $change = $cash - $price;
    }
    if($cash < $price){

        $insuf = "*You have insufficient
cash.";
    }
}else{
    $errorMessage= "*Please insert cash.
";
}

}
?>

//HTML code:

<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="my form">

Order

    <input type="text" name="placeorder" id="placeorder" class="form-
control" value="<?php echo htmlentities($order)?>" disabled>

        Quantity
        <input type="number" class="col-xs-2" name="qty" id="qty1" min="1"
max="10" value="" >

Price

<input type="text" name="price" class="form-control" value='<?php echo htmlentities($price)?>' disabled>

<input type="submit" name="addorder" class="btn btn-primary"  value="Order">

Order

    <input type="text" name="placeorder" id="placeorder" class="form-
control" value="<?php echo htmlentities($order)?>" disabled>

        Quantity
        <input type="number" class="col-xs-2" name="qty" id="qty1" min="1"
max="10" value="" >

Price

<input type="text" name="price" class="form-control" value='<?php echo
htmlentities($price)?>' disabled>

<input type="submit" name="addorder" class="btn btn-primary"  value="Order">

Cash

<input type="text" name="cash" class="form-control" <?php echo
htmlentities($cash)?>>
<?php echo $insuf ?>
<?php echo $errorMessage ?>

**<input type="submit" name="pay" class="btn btn-primary" value="Pay">**

</form>


text:
Q: Selecting Multiple ListBox items from GridView column I have a databound Listbox with Multiselect enabled. On page load, I feed the information from a GridView column and select all the options that match, using this code:
string[] separators = { "<br />" };

String Departments = Session["ProjDept"].ToString();
string[] splitDepartments = Departments.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var dept in splitDepartments)
        {
            listDepartment.SelectedIndex = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
        }

However, I am running into a strange issue: when there is only one department in the GridView column, the option in the listbox gets properly selected, but when there's multiple departments only the LAST department gets selected.
I've ran System.Diagnostics.Debug.Print(dept) within my foreach to ensure that all the values are getting passed and they all appear in the STDOUT, but the listbox still won't cooperate.
Any ideas as to how I can fix this -- or alternatively, what other code could I use to achieve the same results?
Thank you!

A: The SelectedIndex property only allows one value at a time, so you're resetting it with each iteration.  That's why only the last one is being selected.  You need to access the "Selected" property from the ListItem itself.
Without trying it myself, it should look something like:
foreach (var dept in splitDepartments)
{
     int index = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
     listDepartment.Items[index].Selected = true;
}

As long as you do have SelectionMode="Multiple" - that code should work.


text:
Q: chaincode: failed to execute script docker compose I am not able to execute docker-compose script while trying to set up the chaincode environment. Any advices to solve this?
Snapshot: https://drive.google.com/file/d/0B0rw5s9roTIicUVSY3RFUFdPT2M/view?usp=sharing
Thanks!

A: It looks like you have a problem with docker-compose installation at the first place and seemed nothing to do with hyperledger.
Please try to follow getting started.


text:
Q: Latest Rep Changes The Reputation tab on the user page is great, except it orders it in amounts of reputation, is there a way to order it in date order? That way you can see why you reputation just went up and if you need to do something.

A: If you want something within the last month or so, click the envelope next to your name at the top and go to the reputation tab.  You can select the date range you prefer.
https://stackoverflow.com/users/recent/191463?Tab=Reputation&StartDate=2011-02-12&EndDate=2011-02-12

A: The easiest way to see the most recent changes is to select the far-right area of the graph.

Alternatively, the reputation change data returned by the API seems to be oreder by date.


text:
Q: C# String builder, displaying data nicely spaced out I am wondering how exactly can i order my date nicely in a stringbuilder?
Meaning something equal to ("{0,2}", ....) to space the data nicely out.
I do not want to use consolewrites of any kind, so the class can be re-used in a form, console code etc...
Currently i am using "   "  for the spacing, but in overall it does not give a proper display.
(it messed up when i have numbers with more then 1 digit)
public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        foreach (int value in tabel)
        {
            builder.Append(value); // should have something similiar to ("{0,2}", ....)
            builder.Append("  "); // should have something similiar to ("{0,2}", ....)
        }

        builder.Append("(top:");
        builder.Append(top);
        builder.Append(")");

        return builder.ToString();
    }/*ToString*/

Regards.

A: Use AppendFormat, eg:
builder.AppendFormat("{0}  ", value);

or
builder.AppendFormat("{0}  {1}  {2}", value.property1, value.property2, value.property3);

A: Use string formatting. This example will put 3 places for each number, even for less-digit numbers.
value.ToString("000");


text:
Q: Play sound in .NET using generated waveform data How can I play a sound based on waveform data that my .NET program is generating from user input and mathematical functions?
By "waveform data" I mean SPL (sound pressure level) values in a fixed interval time-series (probably 44.1 kHz). I presume that this requires some kind of streaming buffer arrangement.
Note, that this has to be live/real-time, so just creating a .wav file and then playing that will not be sufficient. VB.NET is preferred, but C# is acceptable also.
Just to clarify: What I am looking for is a simple working code example.

A: You can do this using NAudio. You create a stream that derives from WaveStream and in its overriden Read method, you return your samples which you can generate on the fly. You have control over the size of the buffers used by the soundcard which gives you control over the latency.

A: How to play from an array of doubles
    PlayerEx pl = new PlayerEx();

    private static void PlayArray(PlayerEx pl)
    {
        double fs = 8000; // sample freq
        double freq = 1000; // desired tone
        short[] mySound = new short[4000];
        for (int i = 0; i < 4000; i++)
        {
            double t = (double)i / fs; // current time
            mySound[i] = (short)(Math.Cos(t * freq) * (short.MaxValue));
        }
        IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);
        pl.OpenPlayer(format);
        byte[] mySoundByte = new byte[mySound.Length * 2];
        Buffer.BlockCopy(mySound, 0, mySoundByte, 0, mySoundByte.Length);
        pl.AddData(mySoundByte);
        pl.StartPlay();
    }

A: Check out this thread on loading up a DirectSound buffer with arbitrary data and playing it.
Per comment:  Yes, I know.  You will need to translate the C++ into C# or VB.NET.  But, the concept is what's important.  You create a secondary DirectSound buffer and then use it to stream over to your primary buffer and play.

A: IrrKlang, BASS.net (under "Other APIs"), NAudio, CLAM, G3D, and others that can do this.

A: I think you'll need to use DirectSound (DirectX API) for that. It works off buffers which you could fill with your generated data.
Maybe something like this (here in way back machine) will help

A: I have this code but you will have to have code to generate your wav file in memory.
Option Strict Off
Option Explicit On
Imports Microsoft.DirectX.DirectSound
Imports Microsoft.DirectX
Imports System.Threading

Public Class Form1
Const SRATE As Integer = 44100
Const FREQ As Integer = 440
Const DUR As Integer = 1

Private dsDesc As BufferDescription
Private wvFormat As WaveFormat
Private DS As Device

Dim SecondaryBuffer As Microsoft.DirectX.DirectSound.SecondaryBuffer
Dim BufferDescription As Microsoft.DirectX.DirectSound.BufferDescription
Dim DXFormat As Microsoft.DirectX.DirectSound.WaveFormat
Dim sbuf(DUR * SRATE) As Short

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Show()
    DS = New Microsoft.DirectX.DirectSound.Device
    DS.SetCooperativeLevel(Me, CooperativeLevel.Normal)
    wvFormat.FormatTag = WaveFormatTag.Pcm
    wvFormat.Channels = 1
    wvFormat.SamplesPerSecond = SRATE
    wvFormat.BitsPerSample = 16
    wvFormat.AverageBytesPerSecond = 2 * SRATE
    wvFormat.BlockAlign = 2
    dsDesc = New BufferDescription(wvFormat)
    dsDesc.BufferBytes = 2 * DUR * SRATE
    dsDesc.Flags = 0
    Dim buff1 = PlayWave(400)
    Dim buff2 = PlayWave(600)
    buff1 = PlayWave(400)
    buff1.Play(0, Microsoft.DirectX.DirectSound.BufferPlayFlags.Default)
    Thread.Sleep(1000)
    buff1 = PlayWave(600)
    buff1.Play(0, Microsoft.DirectX.DirectSound.BufferPlayFlags.Default)
    ' End
End Sub
Function PlayWave(FREQ As Integer) As SecondaryBuffer
    ' create a buffer
    Dim dsBuffer As SecondaryBuffer
    dsBuffer = New SecondaryBuffer(dsDesc, DS)
    Dim sbuf(DUR * SRATE) As Short
    ' create tone
    For i As Integer = 0 To DUR * SRATE
        sbuf(i) = CShort(10000 * Math.Sin(2 * Math.PI * FREQ * i / SRATE))
    Next
    ' copy to buffer
    dsBuffer.Write(0, sbuf, LockFlag.EntireBuffer)
    Return dsBuffer
End Function


text:
Q: Push new data from Node REST API to React-Native Problem
I've created a REST API using Node and a client app using React-Native.
So far I've configured it so the client app makes HTTP requests to the server.
Now I need to push new data from the server to the client as soon as it is available.  I need to push different data to the client app depending on which user is logged in.
I haven't done this before and I've been having trouble finding a good solution online, partially because I don't know the correct terminology.
The server will pull the data from an external API, save it to MongoDB via Mongoose.  I then need to push the new data to the client
If anyone has any suggestions that would be great!
Environment
Node.js with Express v4.16.4
React-Native v0.58.0-rc.2
Mongoose v5.4.5
Firebase is already installed in the react-native app. I'm proficient with both Mongoose and Firebase so either one could be good for the push queue if applicable.
Thanks!

A: 1. can use socket.io
   Server send data to client using Web socket(socket.io).
2. can use firebase push notification.
   Server can create new notification to firebase, and client can received signal from firebase, and get data from server via REST api.


text:
Q: Looking for a manga or hentai about the son of a lord who reluctantly chooses his first slave on his birthday I don't recall a lot about this story, but here are some details. The main character is the son of a lord of some smaller house in a medieval style fantasy setting with magic teleportation circles. His birthday is coming and he's supposed to choose a slave. He's reluctant to do so. He helps out a woman (I think she has red hair) who's running from some people who kidnapped her or are trying to kidnap her. I think she falls off a cliff (deliberately?) escaping and gets injured and has no memory of why she was running or who she actually is. She might be a princess of some usurped kingdom. I'm not sure. Since the MC treats her with respect and is nice to her, she decides to ask him to make her his slave in order to gain his protection, rather than fall into the hands of whoever was chasing her, as they are cruel and he is kind. The MC agrees.
A slave crest appears on her abdomen (?) after the slave ceremony. There is lots of sex and nudity in this manga so it may be a hentai, not sure. The woman becomes sexually aroused, I believe, under the full moon, possibly because of the slave crest. He is forced to satisfy her or some harm will come to her. I think he gains a number of female slaves or allies during the course of the story. Unfortunately for him, the people chasing the woman want her so badly that they're willing to have the MC's entire family exterminated. I think the story turns into a revenge story after the MC catches up with the actual murderer, who turns out to have been coerced by someone else at the pain of having his whole family slaughtered.
I think the story was published some time in the last ten years. That's all I recall about the story. If I remember anything else, I'll update.

A: Could the one you are looking for is Yahalue(Aharoo)
There is 2 season. The first slave he buy is a princess. She is indeed run away and fall from the cliff => don't remember her identity.
His family is indeed killed near the end of season 2.
Outside of red hair everything you describe is match with Yahalue(Aharoo).
Could this image make you remember anything? (MC and his harem)


text:
Q: create table in access database using Adox in vb I'm using a Windows form application in Visual Basic 2012 to create a new Microsoft Access database using .ADOX. I can create the database but can't create a table in the database.
My code is :
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim cat As New Catalog()
    Dim tablename As String = "Users"
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
    cat = Nothing
    myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
    myconnection.Open()
    str = "CREATE TABLE [ " & tablename & "] ([Username] varchar(50)), ([Password] varchar(50)), ([E-mail] varchar(75))"
    mycommand = New OleDb.OleDbCommand(str, myconnection)
    mycommand.ExecuteNonQuery()
    MsgBox("Database created")
End Sub
End Class

The error is get is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Additional information: Syntax error in CREATE TABLE statement.

Any help is appreciated.
EDITED:
The following code gets past the first error but i now get a field definition error, i know the code should work as it works with adding a number field, possible because the field type in access is short text and long text but anything i've tried doesn't seem to work.
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim cat As New Catalog()
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
    cat = Nothing
    myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
    myconnection.Open()
    str = "CREATE TABLE [Users] (Username Varchar(50), Password Varchar(50), E-mail Varchar(50))"

    mycommand = New OleDb.OleDbCommand(str, myconnection)
    mycommand.ExecuteNonQuery()
    MsgBox("Database created")
End Sub
End Class

A: Looks like you have too many parenthesizes, but I think the actual error is coming from the leading space you have in your query:
                     V
str = "CREATE TABLE [ " & tablename & "]

Try changing it to:
str = "CREATE TABLE [" & tablename & "] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(75))"

Make sure you dispose of your objects, preferably in a using block:
Example:
Using cn As New OleDb.OleDbConnection(mdb)
  cn.Open()
  Using cmd As New OleDb.OleDbCommand(str, cn)
    cmd.ExecuteNonQuery()
  End Using
End Using

A: At the end the code looks like this:
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
    Dim mycommand As OleDbCommand
    Dim myconnection As OleDbConnection
    Dim myReader As OleDbDataReader
    Dim str As String
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cat As New Catalog()
        cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb;Jet OLEDB:Engine Type=5")
        cat = Nothing
        Using myconnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb ")
            myconnection.Open()
            str = "CREATE TABLE [Users] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(50))"

            Using mycommand As New OleDb.OleDbCommand(str, myconnection)
                mycommand.ExecuteNonQuery()
            End Using
        End Using
        MsgBox("Database created")
    End Sub
End Class


text:
Q: In TensorFlow 2.0 with eager-execution, how to compute the gradients of a network output wrt input layer? I use network InceptionV3, I want to compute the gradients of the model output w.r.t. the input layer. I have the following code:
origin_image = load_img("dog.jpg", target_size=(299, 299))
origin_image = img_to_array(origin_image)
origin_image = (origin_image - 127.5) / 127.5
origin_image = np.expand_dims(origin_image, axis=0)

model = tensorflow.keras.applications.inception_v3.InceptionV3()

with tf.GradientTape() as gtape:
   output = model(origin_image)
   y_pred = output[0, 346]

gradient = gtape.gradient(y_pred, model.get_layer("input_1").trainable_variables)
print(gradient) # return []

but this code is running:
from keras import backend as K

model_input_layer = model.layers[0].input
model_output_layer = model.layers[-1].output

cost_function = model_output_layer[0, 346]
gradient_function = K.gradients(cost_function, model_input_layer)
grab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()],
                                                [cost_function, gradient_function])

cost, gradients = grab_cost_and_gradients_from_model([origin_image, 0])

How can tf.GradientTape be used to calculate the gradient of the output with respect to the input

A: You can perform this in TF2 by the solution offered here: How to compute gradient of output wrt input in Tensorflow 2.0
input = tf.Variable(np.random.normal(size=(25, 120)), dtype=tf.float32)

with tf.GradientTape() as tape:
   preds = model(inp)

grads = tape.gradient(preds, input)

Do not forget to change the input shape in size=(25, 120) depending on the number of input columns you have.
The model(input) and model.predict(input) do not do the same, predict works with numpy arrays, while model(input) does a symbolic computation that tensorflow can differentiate.
But looking into your code, it looks like you are trying to do this on a specific layer. By that, you can refer to this link: how to compute the gradients of a network output wrt a specific layer?
This may help.


text:
Q: Finding partially feasible solution in matplotlib Consider the snippet:
# Original code was taken from https://benalexkeen.com/linear-programming-with-python-and-pulp-part-1/

import numpy as np
import matplotlib.pyplot as plt

# Constraints:
## 3x0 + 2x1 <= 5
## 4x0 - x1 <= 3
constraints = ["(5 - 3*x)/2.0", "- (3 - 4*x)/1.0"]

x = np.linspace(-10.5, 10.5, 2000)
### Taking x1 at RHS
### 3x0 + 2x1 <= 5
y1 = eval(constraints[0])
### 4x0 - x1 <=  3
y2 = eval(constraints[1])

# Make plot
plt.plot(x, y1, 'blue', label=r'$'+constraints[0]+'$')
plt.plot(x, y2, 'red', label=r'$'+constraints[1]+'$')
plt.xlim((-10, 10))
plt.ylim((-10, 10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')

y3 = np.minimum(y1, y2) # Constraints of `<=` type

print (y3)

plt.plot(x, y3, 'green', label=r''+'overlap'+'')
#plt.fill_between(x, y1, y2, color='grey', alpha=0.5)
#plt.fill_between(x, y1, y3, color='pink', alpha=.5)
#plt.fill_between(x, y2, y3, color='yellow', alpha=.5)
plt.fill_between(x, y3, np.maximum(y1,y2), color='gray', alpha=.5)
#plt.fill_between(x, y2, y1, color='gray', alpha=.5)
#plt.fill_between(x, y1<=1, np.minimum(y1,y3), color='gray', alpha=.5)
#plt.fill_between(x, y3, y1, color='grey', alpha=0.5)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

What I am able to get is the common feasible solution and the non-feasible solution of the inequalities, such as:

What I actually wanted is to shade the partially feasible solutions individually (the upper and the lower triangles in the figure). Say, only the top triangle is shaded, rest is kept as is.
I tried multiple combinations (as can be seen from the code snippet), but could not achieve this. Any help would be appreciated.

A: You need to declare some upper and lower curves. Horizontal boundaries are good enough. Here y=-500 and y=500 are set up. A large number, i.e. 500 is needed.
y_ge_m500 = (x*0) - 500  #for lower-y bound
y_le_p500 = (x*0) + 500  #for upper-y bound

Then use
plt.fill_between(x, y_ge_m500, np.minimum(y1, y2), color='yellow', alpha=.5)  #get lower ^
plt.fill_between(x, y_le_p500, np.maximum(y1, y2), color='pink', alpha=.5)    #get Upper V

And you will get a plot similar to this:


text:
Q: Associated indexes of two list I have two list :
List<string> List1 = new List<string>()
{
    "xxxxxxxx_green_xxxxxxxxxxxxx",
    "xxxxxxxx_yellow_xxxxxxxxxxxxx",
    "xxxxxxxx_blue_xxxxxxxxxxxxx",
    "xxxxxxxx_white_xxxxxxxxxxxxx",
};

List<string> List2 = new List<string>()
{
    "yyyyyyyy_blue_yyyyyyyyyyyyy",
    "yyyyyyyy_green_yyyyyyyyyyyyy",
    "yyyyyyyy_white_yyyyyyyyyyyyy",
    "yyyyyyyy_yellow_yyyyyyyyyyyyy",
};

Where x and y is a random char.
I want to create a dictionary where values with the same color are associated
Expected output :
Dictionary<string, string> ExpectedDictionary = new Dictionary<string, string>()
{
    {"xxxxxxxx_green_xxxxxxxxxxxxx", "yyyyyyyy_green_yyyyyyyyyyyyy"},
    {"xxxxxxxx_yellow_xxxxxxxxxxxxx", "yyyyyyyy_yellow_yyyyyyyyyyyyy"},
    {"xxxxxxxx_blue_xxxxxxxxxxxxx", "yyyyyyyy_blue_yyyyyyyyyyyyy"},
    {"xxxxxxxx_white_xxxxxxxxxxxxx", "yyyyyyyy_white_yyyyyyyyyyyyy"}
};

What is the best way to do this ? With linq ? Or with a regex?

A: Using Linq's Join and String.Split:
var ExpectedDictionary = (from l1 in List1
                          join l2 in List2
                          on l1.Split('_')[1] equals l2.Split('_')[1]
                          select new
                          {
                              V1 = l1,
                              V2 = l2
                          }).ToDictionary(x => x.V1, x => x.V2);

Safety First Approach:
To handle invalid input, you can use regex:
private string getColor(string value)
{
    var matches = Regex.Matches(value, "_(.*?)_");

    foreach(Match match in matches)
    {
        int counter = 0;
        foreach(Group group in match.Groups)
        {
            if (counter++ == 0)
                continue;

            string color = group.Value;

            if (!String.IsNullOrWhiteSpace(color))
                return color.ToLower();
        }
    }

    return null;
}

Then we need to change the query to be:
var ExpectedDictionary = (from l1 in List1
                          join l2 in List2
                          on getColor(l1) equals getColor(l2)
                          select new
                          {
                              V1 = l1,
                              V2 = l2
                          }).ToDictionary(x => x.V1, x => x.V2);

Using Lambda Syntax:
var ExpectedDictionary2 = List1.Join(List2, l1 => getColor(l1),
                                            l2 => getColor(l2),
                                            (l1, l2) => new { V1 = l1, V2 = l2 })
                               .ToDictionary(x => x.V1, x => x.V2);