text:
Q: change select box value live on change on different select box I am stuck at a point on my project where I need to change the values of the select/dropdown box on change of the value of the first select/dropdown box. The values are to be extracted from database.
Database example:
Table: clicks_package
cpack_id    cpack_name    cpack_timer
1           Standard          30
2           Mini              20
3           Micro             10

Table: clicks_pricing
cp_id    cp_clicks    cp_amount    cp_package (cpack_id from table clicks package)
1        1000           30              2
2        500            20              1
3        1500           10              1
4        1500           10              2

CODE

            Clicks Package
            <select name="quantity" class="select-field" required>
                <option value=""></option>
                <?php while($f = $pacq->fetch()){ extract($f); ?>
                <option value="<?php echo $cpack_id; ?>"><?php echo $cpack_timer; ?> secs ( <?php echo $cpack_name; ?> )</option>
                <?php } ?>
              </select> // mistake in value rectified from value="<?php echo $cp_id; ?> to value="<?php echo $cpack_id; ?>

            Clicks Required
            <select name="quantity" class="select-field" required>
                <option value=""></option>
                <?php while($f = $cq->fetch()){ extract($f); ?>
                <option value="<?php echo $cp_package; ?>"><?php echo $cp_clicks; ?> clicks for $<?php echo number_format($cp_amount,2,'.',','); ?></option>
                <?php } ?>
              </select> // mistake in value rectified from value="<?php echo $cp_id; ?> to value="<?php echo $cp_package; ?>

Now what I want is I want to change the Clicks Required select box values  when the Clicks Package is changed depending on the package ID in table clicks pricing. For example, if user selects Standard from the select box Clicks Package the Clicks Required select box will display values of cp_id 2 and 3 as the cp_package has inherited the id 1 from the clicks_package table. I want this to be changed LIVE using jQuery. I tried my best to explain the question. Please help.

A: 1) Create one class clicks_package in First Dropdown which will be used in  to fetch dropdown values.
<select name="quantity" class="select-field clicks_package" required>
2) Create one class show_clicks_pricing in second  to show the result.

Updated Code

  Clicks Package

    <select name="quantity" class="select-field clicks_package" required>
      <option value=""></option>
      <?php while ($f = $pacq->fetch()) {
        extract($f); ?>
        <option value="<?php echo $cp_id; ?>">
          <?php echo $cpack_timer; ?> secs ( <?php echo $cpack_name; ?> )
        </option>
      <?php } ?>
      </select>

  Clicks Required

    <select name="quantity" class="select-field" required>
      <option value=""></option>
      <?php while ($f = $cq->fetch()) {
        extract($f); ?>
        <option value="<?php echo $cp_id; ?>">
          <?php echo $cp_clicks; ?> clicks for $<?php echo number_format($cp_amount, 2, '.', ','); ?>
        </option>
      <?php } ?>
    </select>

3) Create one page namely ajaxData.php. (If you want to change this page name, change in  too. Both are related.)
ajaxData.php
<?php
$cpack_id = $_POST['cpack_id'];

Now write query here using this `$cpack_id`. And fetch it like the same way you were fetching before.

?>
<select name="quantity" class="select-field" required>
  <option value=""></option>
  <?php while ($f = $cq->fetch()) {
    extract($f); ?>
    <option value="<?php echo $cp_id; ?>">
      <?php echo $cp_clicks; ?> clicks for $<?php echo number_format($cp_amount, 2, '.', ','); ?>
    </option>
  <?php } ?>
</select>

A: you can achieve this by calling ajax request to the server and by sending id of clicks_package to the server and in response you have to return clicks_pricing of that package then by using jquery you can render it.
   $.ajax({url: "getdata.php",data:{"id":"1"} success: function(result){
//you have to use loop here for result and set
var html="";
$.each(data.data, function(k, v) {
html+="<option value=\'"+v.cp_id+"\'>"+v.cp_amount+"</option>";
});
    $("#clicks_pricing_id").html(html);
}});


text:
Q: Searching by a coordinate using PostGIS I have a coordinate (longitude, latitude) which I get from my map (I'm using OSM with OpenLayers) so I get something like this lon: -46.502541777468984 lat: -23.474943422638063.
What I need? I need to know if there is some function in PostGIS that I can use to search on my database which will return the nearest result that I have in DB.
I know I can do this using a select, but it take too much time.

A: If it is just from one table then you could do:
SELECT * FROM table
ORDER BY geom <-> 'SRID=4326;POINT(-46.502541777468984 -23.474943422638063)'::geometry
LIMIT 1;

A: Don't use the chosen method. It's relying on unstandardized text-to-point conversion and is otherwise subject to rounding errors. They won't be a problem because of the precision, they will be a problem because of equality-testing. ST_MakePoint is typed is and standardized OGC/SQL-MM 3: 8.1.3, 9.5.4.
SELECT * FROM table
ORDER BY geom <-> ST_MakePoint(-46.502541777468984,-23.474943422638063)::geography
LIMIT 1;

EKWT(with the SRID in the WKT) is a PostGIS thing, and if OGC or ISO standardizes it then that behavior may change.
In my example above, I'm using the geography type because it's probably what you want anyway and it defaults to srid 4326.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Directive with dynamic attributes I need to render attributes on controls in Angular. The attributes will be configured based on a property. The user will send in a JSON file which will be serialized to an object in typescript. This typescript file will be used as the binding on the component.
{
      "row": 1,
      "col": 2,
      "key": "Input_2",
      "label": "First Name",
      "required": true,
      "type": 1,
      "hiddden": false,
      "maxLength": 100,
      "attributes": "required validateEqual='password' reverse='false'"
}

export class ControlBase<T> {
    row: number;
    col: number;
    value?: string;
    key: string;
    label: string;
    required: boolean;
    type: ControlType;
    hidden: boolean = false;
    attributes: string;
}

<input class="form-control" type="text" [(ngModel)]="value" {{control.attributes}}>

When I used the above binding {{control.attributes}} I get the following error : Failed to execute 'setAttribute' on 'Element': '{{control.attributes}}' is not a valid attribute name.

A: I don't think there is any template syntax that allows you to set a dynamic number of arguments. But it can be achieved with code
Here is a sample https://stackblitz.com/edit/angular-svcvsj
Check the input element with your browser's developer tools. The attributes should be there. I recommend  using a strongly typed object for the attributes to avoid doing the extra string parsing there


text:
Q: Updateing Android SDK in Eclipse ADT to API 19 from API 18 Is there anyway to update Android SDK version to API 19.0 or higher from API 17.0 without using SDK Manager in eclipse? I mean to say can I download the update files separately in some computer and include the downloaded files in the android-eclipse directory ?

A: Please look here for instructions
Quoting from there:

Open in browser
  https://dl-ssl.google.com/android/repository/repository-8.xml
For e.g. if you want to download Android SDK for version 4.0.3 for all
  platforms, you could look up that XML file. You will find a block
  under tag SDK 4.0.3 like this

<sdk:archive arch="any" os="any">

<sdk:size>44758833</sdk:size>
<sdk:checksum type="sha1">f2aa75133c29916b0b0b984974c2d5e46cb09e9c</sdk:checksum>
<sdk:url>android-15_r01.zip</sdk:url>
</sdk:archive>

So the URL will be is
  http://dl-ssl.google.com/android/repository/android-15_r01.zip

In such a way resolve the needed links. I've checked that there are file names for all versions upto the latest


text:
Q: Importing nested list into a text file I've been working on a problem which I realise I  am probably approaching the wrong way but am now confused and out of ideas. Any research that I have done has left me more confused, and thus I have come for help.
I have a nested list:

[['# Name Surname', 'Age', 'Class', 'Score', '\n'], ['name', '9', 'B',
  'N/A', '\n'], ['name1', '9', 'B', 'N/A', '\n'], ['name2', '8', 'B',
  'N/A', '\n'], ['name3', '9', 'B', 'N/A', '\n'], ['name4', '8', 'B',
  'N/A', '']]

I am trying to make it so this list is imported into a text file in the correct layout. For this I flattened the string and then joined it together with ','.
The problem with this is that because the '\n' is being stored in the list itself, it adds a comma after this, which ends up turning this:

Name Surname,Age,Class,Score,
Name,9,B,N/A,
Name1,9,B,N/A,
Name2,8,B,N/A,
Name3,9,B,N/A,
Name4,8,B,N/A,

into:

Name Surname,Age,Class,Score,
,
,Name,9,B,N/A,
,Name1,9,B,N/A,
,Name2,8,B,N/A,
,Name3,9,B,N/A,
,Name4,8,B,N/A,

If I remove the \n from the code the formatting in the text file is all wrong due to no new lines.
Is there a better way to approach this or is there a quick fix to all my problems that I cannot see?
Thanks!
My code for reference:
def scorestore(score):

    user[accountLocation][3] = score

    file = ("classdata",schclass,".txt")
    file = "".join(file)

    flattened = [val for sublist in user for val in sublist]

    flatstring = ','.join(str(v) for v in flattened)

    accountlist = open(file,"w")

    accountlist.write(flatstring)

    accountlist.close()

A: I'm not sure which list is the one in your post (sublist?) but when you flatten it, just discard the "\n" strings:
flattened = [x for x in sublist if x != ["\n"]]

A: The easiest way would probably be to remove the newlines from the sublists as you get them, the print each sublist one at a time. This would look something like:
for sublist in users:
    print(",".join(val for val in sublist if not val.isspace()), file=accountlist)

This will fail on the 0 in your list, however. I'm not sure if you intend to handle that, or if it's extraneous. If you do need to handle is, then you'll have to change the generator expression to str(val) for val in sublist if not str(val).isspace().

A: Instead of making one string, how about writing lines. Use something like this:
 list_of_list = [[...]]
 lines = [','.join(line).strip() for line in list_of_list]
 lines = [line for line in lines if line]
 open(file,'w').writelines(lines)

A: Use the csv module to make it easier:
import csv

data = [
    ['# Name Surname', 'Age', 'Class', 'Score','\n'],
    ['\n'],
    ['Name', '9', 'B', 'N/A','\n'],
    ['Name1', '9', 'B', 'N/A','\n'],
    ['Name2', '8', 'B', 'N/A','\n'],
    ['Name3', '9', 'B', 'N/A','\n'],
    ['Name4', '8', 'B', 0]
]

# Remove all the ending new lines
data = [row[:-1] if row[-1] == '\n' else row for row in data]

# Write to file
with open('write_sublists.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(data)

Discussion
Your data is irregular: some row contains the ending new line, some row don't. Yet some row contains all strings and some row contains a mixed data type. The first step is to normalize them by remove all ending new lines. The csv module can take care of mixed data types just fine.


text:
Q: Printing a nested list with formatting I am trying to write a Perl function that takes in two Lists/Arrays and computes the cross-product of them(cartesian product). I currently have code working that takes the two input Lists and computes the cross-product, but I having trouble printing the nested Lists.
I am looking for advice on the best way to print a nested List. Here is my current attempt that works:
for(@C) {
    for(@$_) {
        print $_;
    }
    print " ";
}

# prints
# 1A 1B 1C 1D 1E 1F 1G 1H 1I
# 2A 2B 2C 2D 2E 2F 2G 2H 2I
# 3A 3B 3C 3D 3E 3F 3G 3H 3I
# 4A 4B 4C 4D 4E 4F 4G 4H 4I
# etc ...

but this didn't look Perly enough for me. So I made another attempt with map:
print map {
    map { $_ } @$_;
} @C;

# prints
# 1A1B1C1D1E1F1G1H1I
# 2A2B2C2D2E2F2G2H2I
# 3A3B3C3D3E3F3G3H3I
# 4A4B4C4D4E4F4G4H4I
# etc ...

but the items are all pressed together. Is there anyway to format this approach with map? Are there better ways of accomplishing this?
Full function code:
use strict;
use warnings;

# globals
my @digits  = (1,2,3,4,5,6,7,8,9);
my @letters = ("A","B","C","D","E","F","G","H","I");
my @rows = @digits;
my @cols = @letters;
my @squares = cross(\@rows, \@cols);

sub cross {
    my @C = [];

    foreach (reverse @_) {
        my @A = @$_;

        @C = map { my $n = $_; map { [ $n, @$_ ] } @C } @A;
    }

    # works
    #for(@C) {
    #   for(@$_) {
    #       print $_;
    #   }
    #   print " ";
    #}

    print map {
        map { $_ } @$_;
    } @C;

    return @C;
}

A: There's nothing that says map can't return formatted strings:
print map { " $_" };

Or for more precise control, use join:
print join ' ', map { ... };

A: print map { join '', @$_, ' ' } @C;

A: By default arrays interpolate into strings as you want them here.  So:
#! /usr/bin/env perl
use common::sense;

my @a = ([qw/1A 1B 1C 1D 1E 1F 1G 1H 1I/],
         [qw/2A 2B 2C 2D 2E 2F 2G 2H 2I/],
         [qw/3A 3B 3C 3D 3E 3F 3G 3H 3I/],
         [qw/4A 4B 4C 4D 4E 4F 4G 4H 4I/],
         ['etc', '...']);

say "# prints";
say "# @$_" for @a;

Outputs:
# prints
# 1A 1B 1C 1D 1E 1F 1G 1H 1I
# 2A 2B 2C 2D 2E 2F 2G 2H 2I
# 3A 3B 3C 3D 3E 3F 3G 3H 3I
# 4A 4B 4C 4D 4E 4F 4G 4H 4I
# etc ...

Alternatively,
local $" = ', ';
say "# @$_" for @a;

Outputs:
# 1A, 1B, 1C, 1D, 1E, 1F, 1G, 1H, 1I
# 2A, 2B, 2C, 2D, 2E, 2F, 2G, 2H, 2I
# 3A, 3B, 3C, 3D, 3E, 3F, 3G, 3H, 3I
# 4A, 4B, 4C, 4D, 4E, 4F, 4G, 4H, 4I
# etc, ...


text:
Q: ngView with Node.js doesn't load the main page when the ULR is reloaded In the first load everything is okay but, when I reload/refresh the page the main page don't load and only the template load.
I use Node.js and express for route pages I think when I try reload page:
app.get('/', function (req, res) {
res.render('index.html');
console.log('GET: 200 index');
console.log(req.statusCode);

        {{lnkCadastrar}}
        {{lnkAcessar}}
        {{lnkHome}}

This is my route:
    var appRoute = angular.module('appRoute', ['ngRoute'])
    .config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {

            $routeProvider.when('/footer', {
                templateUrl: '../views/footer.ejs'
            }).when('/login/login', {
                templateUrl: '../views/login/login.html',
                controller: 'loginCtl'
            }).when('/cadastro/cadastro', {
                templateUrl: '../views/cadastro/cadastro.html',
                controller: 'cadastroControll',
                controllerAs: 'cadastroCtl',
                reloadOnSearch: false
            }).when('/home/home', {
                templateUrl: '../views/home/home.html',
                controller: 'homeControll'
            }).when('/*', {
                templateUrl: '../views/error.ejs'
            });

            $routeProvider.otherwise({
            }).otherwise({
                redirectTo: '/index.html',
                reloadOnSearch: false
            });

            $locationProvider.html5Mode({enabled: true, requireBase: false});

        }]);

appRoute.controller('appRouteCtl', ['$scope', function ($scope) {
    $scope.title = "Controlador de Patio";
}]);


text:
Q: How to setup Laravel application in AWS Elastic Beanstalk using external RDS database I want to start deploying my laravel app to production. To avoid changing AWS config in the near future, I decided to try to add continuous integration. To do this I'm using elastic beanstalk and pushing the code there using another AWS tool. All this is working perfectly. I put a test message in /public/index.php to output "hello world" and it works as expected when going to the URL. When I remove this text and run my laravel app as normal, I get a 500 internal server error. I'm not sure all what elastic beanstalk does on deployment for laravel apps. Because of this I'm not sure if this error is occurring from a bad DB connection or laravel app not fully setup yet.
I created an RDS DB instance outside of elastic beanstalk. I am able to access this from sequel pro and I added the database I will use to store all my data. I added all the necessary db connection values (host, port, database, username, password) to /config/database.php and the elastic beanstalk server configuration environment variables.
I've searched online for days for info but haven't found anything specific to this. Also part of my issue is a lack of understanding of how laravel is setup during a deployment in beanstalk. Is there something with /.ebextensions that will help me accomplish these goals?
When I deploy my code I need to make sure all vendor files are installed through composer and then I also need to make sure all database migrations/changes happen. I want to automate as many steps as possible so I can just push up code changes and server will change code and keep working.
I also want to make sure there isn't anything I'm missing for setting up my db connection. Are there any other files in laravel I need to setup or something in elastic beanstalk I need to have configured? I'm keeping my db open to all connections and then I can tighten restrictions later
EDIT: My database may not be configured correctly yet, but that appers to not be source of the issue. I think my issue is knowing what scripts and how to run them during deployment. I want to make sure composer and php artisan migrate is ran to keep everything up to date. How can I do this with elastic beanstalk?

A: This is a little off topic but with my experience I do not recommend using beanstalk to achieve a good workflow pushing and deploying. I recommend
you to use Forgelaravel.com to deploy your GitHub repository. In forge Laravel you will be able to create a server from AWS and it will automatically create database connections and stuffs, then with just one click you can deploy to the server and keep a good workflow.

A: Given that we're speaking of a Laravel application, this 500 Server Error

often occurs when one is creating new infrastructure. Why? It's likely to forget to add the environment variables to the EB environment.
Simply go to that EB environment configuration, then under software modify to include at least the following environment properties

*

*APP_DEBUG (can be, for example, false)

*APP_KEY (this is the key generated with php artisan key:generate)

*APP_NAME (tiagoPeres)

Then the issue will be gone.


text:
Q: How to modify each section of a vector in multiple threads I have a vector of u8 and I need to fill this vector with values that can be computed in parallel:
let vector: Vec<u8> = vec![0, len];

Given n_threads threads, each thread can take care of a section of the vector. The only way I know of to pass a mutable vector into multiple threads is to wrap it into a Mutex:
let vector: Arc::new(Mutex::new(vec![0, len]));

and for each thread move the clone of the atomic reference:
for _ in 0..n_hthreads {
    let vector = Arc::clone(&vector);
    thread::spawn(move || fill_vector());
}

The problem with this approach is that I would need to lock the entire vector inside the threads (which completely nullifies the parallelism):
fn fill_vector() {
    let vector = vector.lock().unwrap();
    vector[i] = /* ... */;
}

A possible alternative would be to have multiple vectors and pass each vector to each thread, and once the threads are joined concatenate the vectors, but that would require additional memory unless there is a way to move the sub-vectors into the final vector instead of copying them.
Is there any alternative that would allow me to lock only a specific section of the vector or to move multiple sub-vectors when concatenating (my goal is to have a single vector in the end), or any other alternative to safely write into the vector?


text:
Q: After update to Sonarqube 6.4 java code coverage exclusion does not work We have added one property in our maven project to exclude few of the java project from sonar coverage
<properties>
   <sonar.coverage.exclusions>**/*</sonar.coverage.exclusions>
</properties>

which was working fine in Sonarqube 6.3.
After upgrading to Sonarqube 6.4 we found this project are not excluding from sonar coverage.
Is this anissue in the Sonarqube 6.4? Do we have any work around for this.


text:
Q: FocusListener on JTextField not working I've created an application that uses FocusListener to make sure a text fieid's value is always positive. When the user inputs negative value and then click the "tab" key to move focus away from the text field, the value will be multiplied by -1 so that the resulted value is positive. However, when I ran the application, the text field didn't change. I am not sure what I did wrong, and will appreciate any help.
Here is my code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class AlwaysPositive extends JFrame implements FocusListener {
JTextField posField = new JTextField("30",5);

public AlwaysPositive() {
    super("AlwaysPositive");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pane = new JPanel();
    JTextField posField = new JTextField("30",5);
    JButton ok= new JButton("ok");
    posField.addFocusListener(this);
    pane.add(posField);
    pane.add(ok);
    add(pane);
    setVisible(true);
}

public void focusLost(FocusEvent event) {
    try {
        float pos = Float.parseFloat(posField.getText());
        if (pos < 0)
            pos = pos*-1;
        posField.setText("" + pos);
    } catch (NumberFormatException nfe) {
        posField.setText("0");
    }
}

public void focusGained(FocusEvent event) {
}

public static void main(String[] arguments) {
    AlwaysPositive ap = new AlwaysPositive();
}

}

A: The main problem is you are shadowing your variables
You declare
 JTextField posField = new JTextField("30",5);

As an instance variable, but in your constructor, you redeclare it again...
public AlwaysPositive() {
    //...
    JTextField posField = new JTextField("30",5);
    posField.addFocusListener(this);
    //...
}

Add attach the focus listener to it, but in the focusLost method, you are referring to the instance variable, which isn't the one that is actually on the screen
Start by changing the declaration within the constructor
public AlwaysPositive() {
    //...
    posField = new JTextField("30",5);
    posField.addFocusListener(this);
    //...
}

However, there are better solutions to use then FocusListener.
For example, you could use an InputVerifier that will allow you to verify the value of the field and make decisions about whether focus should be moved or not.
Take a look at How to Use the Focus Subsystem and Validating Input in particular
You could also use a DocumentFilter to restrict what the user can actually enter, filtering the input as the user types it.  Take a look at Text Component Features and Implementing a Document Filter in particular.
You can also take a look at these examples for more ideas

A: When you create object of same name inside a method, the listener is set to the method object and not to the Class object.


text:
Q: U-SQL Python extension: How can I import a pyd file? I've looked at: https://blogs.msdn.microsoft.com/azuredatalake/2017/03/10/using-custom-python-libraries-with-u-sql/
The blog post mentions that U-SQL's Python extension supports zipimport for custom modules. However, Python's zipimport does not support pyd files (e.g. compiled C-extensions).
I've tried modifying "UsqlPythonDeployPackage.zip\3.5.1\Lib\site-packages" by adding my modules (downloading the zip file, adding my module, uploading it again), but that didn't seem to work. It doesn't find my pyd-module.

A: Adding the compiled Python C-extension (pyd) to:
usqlext\assembly\python\UsqlPythonDeployPackage.zip\3.5.1\Lib\site-packages

seems to work just fine. However, I forgot to drop/creating the assembly again. Here's the code I used for that:
CREATE DATABASE IF NOT EXISTS master;
USE DATABASE master;

DROP ASSEMBLY IF EXISTS [ExtPython];
CREATE ASSEMBLY IF NOT EXISTS [ExtPython]
FROM @"/usqlext/assembly/python/ExtPy.dll"
WITH ADDITIONAL_FILES =
(
    @"/usqlext/assembly/python/ExtPy.pdb",
    @"/usqlext/assembly/python/UsqlPythonInvokePackage.zip",
    @"/usqlext/assembly/python/UsqlPythonDeployPackage.zip",
    @"/usqlext/assembly/python/version.python"
);


text:
Q: ggplot: remove lines at ribbon edges I am using ggplot to plot time course data (fixation proportions over time to different objects on the screen) and want to use a ribbon to show the SE, but the ribbon itself has lines at the top and bottom edges, which makes reading the graph a bit harder. I haven't been able to figure out how to get rid of those edge lines. Here is my plot code:
ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  stat_summary(fun.y = "mean", geom = "line", size = 2) +
  stat_summary(fun.data = "mean_se", geom = "ribbon", alpha = .3)

Any suggestions?
Here is a minimal working example. I've compressed my data to:
   Time Object          y      lower     upper
 1 1000      C 0.12453389 0.04510504 0.2039627
 2 1000      T 0.58826856 0.37615078 0.8003864
 3 1000      U 0.09437160 0.03278069 0.1559625
 4 1100      C 0.12140127 0.03943988 0.2033627
 5 1100      T 0.64560823 0.44898727 0.8422292
 6 1100      U 0.06725172 0.01584248 0.1186610

d <- structure(list(Time = c(1000L, 1000L, 1000L, 1100L, 1100L, 1100L), Object = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("C",
"T", "U"), class = "factor"), y = c(0.12453389, 0.58826856, 0.0943716,
0.12140127, 0.64560823, 0.06725172), lower = c(0.04510504, 0.37615078,
0.03278069, 0.03943988, 0.44898727, 0.01584248), upper = c(0.2039627,
0.8003864, 0.1559625, 0.2033627, 0.8422292, 0.118661)), .Names = c("Time",
"Object", "y", "lower", "upper"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

and here is the new plot code:
ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  geom_line(size = 2) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = .3)

A: You can remove the border using the colour argument:
ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  geom_line(size = 2) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = .3, colour = NA)

A: ggplot2's geom_ribbon() now includes an outline.type argument that helps control how the ribbon outlines are displayed.
Outline Type
library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red",
                outline.type = "lower") +
    geom_line(aes(y = level))

Created on 2020-05-28 by the reprex package (v0.3.0)
Linetype = 0
Alternatively, as suggested we can set linetype = 0 to remove all lines.
library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red", linetype = 0) +
    geom_line(aes(y = level))

Created on 2020-05-28 by the reprex package (v0.3.0)

A: geom_ribbon understands linetype aesthetic. If you want to map linetype to a variable include it in the aes() argument, otherwise, place linetype outside and just give it 0, like so:
ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  geom_line(size = 2) +
  geom_ribbon(aes(ymin = lower, ymax = upper), linetype = 0, alpha = .3)

More info here: http://docs.ggplot2.org/current/geom_ribbon.html

A: Here you go
ggplot(d, aes(Time, y,  fill=Object)) +
  geom_line(size=2, aes(colour = Object)) +
  geom_ribbon(aes(ymin=lower, ymax=upper), alpha=.3)


text:
Q: How would I convert C# delegate function to VB.Net? Here  there's an old question about this code.
xmpp.OnLogin += delegate(object o)
                {
                    xmpp.Send(
                        new Message(
                            new Jid(JID_RECEIVER),
                            MessageType.chat,
                            "Hello, how are you?"
                        )
                    );
                };

I want to use it in vb.net (version 10) but I couldn't figure out how to convert it.

A: The delegate is an anonymous function. The syntax is a bit different for VB .NET, as expected. Without having the VB compiler at hand, I would say you need something like:
AddHandler xmpp.OnLogin,
    Sub(o As Object)
        xmpp.Send(
                    new Message(
                        new Jid(JID_RECEIVER),
                        MessageType.chat,
                        "Hello, how are you?"
                    )
    End Sub

A: I don't know how to declare an anonymous delegate in VB.NET and I'm too lazy to Google it, but something like this should work (warning: not tested):
AddHandler xmpp.OnLogin, AddressOf Me.HandleSendMessage

Private Sub HandleSendMessage(ByVal o As Object)
xmpp.Send( new Message(
               new Jid(JID_RECEIVER),
                            MessageType.chat,
                            "Hello, how are you?"
                        )
                    )
End Sub


text:
Q: Color de fondo del botón Estoy intentando cambiar el color de fondo del botón y no el de detrás. A mis compañeros del proyecto les funciona bien, trabajan con Windows, yo con Mac. No se si eso influye en algo para que no me funcione a mí.
Este es el código:
        JButton resp1 = new JButton("");
        resp1.setFont(new Font("Georgia", Font.PLAIN, 11));
        resp1.setText(pregunta.getRespuesta_1());
        resp1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (contestado == false) {
                int boton = 1;

                if (boton == pregunta.getCorrecta()) {
                    acierto=true;
                    resp1.setBackground(Color.green);
                    resp1.setOpaque(true);
                    resp1.setBorder(null);
                } else {
                    resp1.setBackground(Color.red);
                    resp1.setOpaque(true);

                }
                contestado = true;
                button.setText("Continuar");
                button.setOpaque(true);
                button.setContentAreaFilled(true);
                button.setBorderPainted(true);
            }
        }
    });

El problema que no veo la forma de que conserve la forma del botón con el el fondo de diferente color, que en este caso es rojo o verde dependiendo de si se acierta o no.

A: Para que no se pinte el borde usa:
setBorderPainted(false);

Setear el borde a null es una mala práctica.
Asegúrate de que el área se pinta y de que es opaco.
Además, estando en OSX, tienes que tener en cuenta que el 'Look and Feel' de tu Mac puede estar ignorando el color de fondo del boton, prueba con otro 'Look and Feel'. Esto debería funcionar:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");


text:
Q: React async API call I'm trying to understand somebody else code,
I have this component:
import React from 'react';
import { useEffect, useState } from 'react';

export default function CountriesList({ searchValue }) {
  const [data, setData] = useState([])

  //Onmount
  useEffect(() => {
    async function init() {
      //API Calls- request data from the server
      const response = await fetch('https://restcountries.com/v2/all');
      const body = await response.json();
      setData(body);
    }
    init()
  }, [])//dependencies array
  return (

      {data
        .filter(country => country.name.toLowerCase().includes(searchValue.toLowerCase()))
        .map((country) => {
          const { name, flag } = country;
          return (

{name}

          )
        })}

  )
}

inside init(), the programmer call init() again, can you explain why?
I tried to look for this style of programming and I didn't find anything.
whiteout this line the API call doesn't work.
thank you!

A: I may be mistaken, but as far as I can see, init function is declared and called right after declaration.
Check this out: https://github.com/facebook/react/issues/14326


text:
Q: SQL server 2008: How to get the start date and end date of my data? As a newb, I already know that I will be berated for asking this question, but I did not find the answer on the site here and could use some help...
I have a table that lists data by the day, and by type.  For example
Transaction  |  Date  | Type
-----------------------------
Updat    | 11/7/2008  | Cash-out
Update   | 11/10/2008 | Wrote-check
Deposit  | 11/11/2009 | Cashed Check
Update   | 11/18/2008 | Wrote check
Deposit  | 11/19/2009 | Cashed Check

What I'm trying to do, is find the very first occurrence of each transaction type, and the very last occurrence of each transaction type.
so I'm trying to figure out an sql statement that I can write that will return something like this:
Transaction  |  First Date  | Last Date  |
----------------------------------------------
Update       | 11/7/2008    | 11/18/2008 |
Deposit      | 11/11/2009   | 1/19/2009  |

any ideas?

A: SELECT
     transaction,
     MIN([date]) AS [First Date],
     MAX([date]) AS [Last Date]
FROM
     My_Table
GROUP BY
     transaction

A: SELECT Transaction, Min([date])  AS [First Date] , Max([Date]) AS [Last Date]
FROM myTable GROUP BY Transaction


text:
Q: How do I disable "created 2 hours ago" from code VS code shows a timestamp when I am editing. Since I don't know what this feature is called, I can't turn it off.
How do I turn this off?

A: As mentioned in the comments, this is coming from the gitlens extension. Set the following in your settings.json:
"gitlens.codeLens.enabled": false,
"gitlens.currentLine.enabled": false,
"gitlens.statusBar.enabled": false,


text:
Q: Getting sound but no video on Android app? I've created an Android app which is for a small town to locate recreational activities. Fairly small and basic. I designed it with phonegap.
I've scoured the web for (22 hours) on this problem.
When I embed videos in the app (from anywhere) I get the audio, but no video.

A: I'm having the same problem with youtube and vimeo embed videos. But everything works in fullscreen mode.
<iframe class="youtube-player" type="text/html" src="http://www.youtube.com/embed/XXXXXXXXX" frameborder="0" allowfullscreen></iframe>


text:
Q: Randomize Color Scheme Selection in Theme on my site I'm using cenetric, a child theme of genesis and this theme comes with some predefined color schemes.
//* Add support for additional color style options
add_theme_support( 'genesis-style-selector', array(
    'centric-pro-charcoal' => __( 'Centric Charcoal', 'centric' ),
    'centric-pro-green'    => __( 'Centric Green', 'centric' ),
    'centric-pro-orange'   => __( 'Centric Orange', 'centric' ),
    'centric-pro-purple'   => __( 'Centric Purple', 'centric' ),
    'centric-pro-red'      => __( 'Centric Red', 'centric' ),
    'centric-pro-yellow'   => __( 'Centric Yellow', 'centric' ),
) );

Now I am looking for a way to create a random color scheme, so that every time any user visit my site, the color scheme gets automatically selected. I've tried the following:
$thm_out = array("Charcoal", "Green", "Orange", "Purple", "Red", "Yellow");

//* Add support for additional color style options
add_theme_support( 'genesis-style-selector', array(
    'centric-pro-charcoal' => __( 'Centric Charcoal', 'centric' ),
    'centric-pro-green'    => __( 'Centric Green', 'centric' ),
    'centric-pro-orange'   => __( 'Centric Orange', 'centric' ),
    'centric-pro-purple'   => __( 'Centric Purple', 'centric' ),
    'centric-pro-red'      => __( 'Centric Red', 'centric' ),
    'centric-pro-yellow'   => __( 'Centric Yellow', 'centric' ),
    'centric-pro-random'   => __( 'Centric '.$thm_out[array_rand($thm_out, 2)].'', 'centric' ),
) );

But its giving the following error in my admin panel and also not working properly.
Warning: Illegal offset type in C:\xampp\htdocs\dev\wp-content\themes\centric-pro\functions.php on line 69

So, can you guys please help me to fix this issue?

A: This:
$thm_out[array_rand($thm_out, 2)]
is the same as
$them_out[array(0,2)] where 0 and 2 are 2 random keys.
See array_rand
I hope you can see what is wrong there. Change that to:
$thm_out[array_rand($thm_out, 1)]
which is the same as
$them_out[2] where 2 is any random key.


text:
Q: How to add a button to custom post type's posts-page How can I add a button to a posts -page. (In this case a custom post type).
I'd like to place it next to, or near, the "Add new" button, to import content from a web service.

A: You can add button via add_meta_box function.
function add_your_meta_box(){

add_meta_box('your-metabox-id', 'Title', 'function_of_metabox', 'custom_post_type', 'side', 'high');}

add_action('add_meta_boxes', 'add_your_meta_box');

function function_of_metabox()
{?>
    <input type="submit" class="button button-primary button-large" value="Add New" id="add-new"/>
<?php }

if you add to multiple post type, you should use foreach loop.
function add_your_meta_box(){

  $types = array("post","page","custom_post_type");

  foreach($types as $type){

    add_meta_box('your-metabox-id', 'Title', 'function_of_metabox', $type, 'side', 'high');}

}

add_action('add_meta_boxes', 'add_your_meta_box');

A: Like this:
function custom_js_to_head() {
    ?>

    <?php
}
add_action('admin_head', 'custom_js_to_head');

That code (pasted to functions.php) will dynamically add new link tag after "Add new" link.


text:
Q: sharepoint online How to handle onClickListeners, eventListeners? I'm a newbie to Sharepoint online. I have done Migration project from Sharepoint 2007 to Sharepoint online (O365). Now comes the enhancements to the new site in sharepoint online. I'm searching without proper flow.
I hereby post the requirements as follows. Please guide me in this regard:

*

*I have forms based on content type

*I have a list named "sample_1", where there are many rows with "XXXX_details". If i click "multiple lines of text" field, it shows that rows data in the form view.
Till this ok. Now i need to create a button on the same page where when i click button, onClickListener, i need to create a task which should populate some of the fields in a row to the (1) form which i said in the First point.
Do this need sharepoint Designer or Visual Studio
If you unable to get what the question is, please comment and i clarify it.

*

*Please clear the air "what are the requirements and steps" to create sharepoint online apps.

Any related answers or comments are highly appreciated.

A: I hope I undestand correctly. You have a SharePoint list form and on that form you want a button that creates a task in another list? If so, this is what I would do using javascript.

*

*Add the button and javascript to the form through a content editor webpart. Either directly or through a linked html file.

*In the onclick event of that button make either a rest call or a csom/jsom call to create the task list item.

Using something like jQuery or SPServices will probably help out on creating the list item.


text:
Q: How to pass Multiple Class Object in $http Request My requirement is to pass multiple class object(which is going to map with request param or request body in rest controller) in angular $http service.
I can't pass class object in request body since one http call has only one request body.
When i'm trying to pass class object in $http param I'm getting class cast exception.
is there any way to pass multiple object in single $http call ??
@RequestMapping(value = "CommitObject", method = RequestMethod.POST)
public void Commit(@RequestParam(value = "clazz") final String clazz,
        @RequestParam(value = "Id") final String modelId,@RequestBody LinkedHashMap<String, Object> obj) {
    mService.Commit(Id,clazz workingmodelObj);
}

A: I tried it many times but always failed.So to overcome this I use to create a  Java Bean and encapsulate both objects into it at then accepting it in     @RequestBody.
Your Wrapper should look like this:
public class SampleWrapper {
    private Object1 object1;
    private Object2 object2;
    //getters setters and constructors go here
}

And your constructor should look like this:
@RequestMapping(value = "/url",method= RequestMethod.POST)
public String getRequest(@RequestBody SampleWrapper wrapper) {
    Object1 o1 = wrapper.getObject1();
    Object2 o2 = wrapper.getObject2();
}

JSON request should look like this:
 {
 "object1" : {//object1 body },
 "object2" : {//object2 body }
 }

A: If you're trying to make a $http.post request you can make an array of the objects you are trying to send and then attach it in the request.
$http.put('ROUTE HERE', Array Of Objects);

A: You can pass Objects by appending it in formData
Angular side
var formData=new FormData();
formData.append("obj1",new Blob([JSON.stringify(obj1)],{type: "application/json"}));
formData.append("obj2",new Blob([JSON.stringify(obj2)],{type: "application/json"}));
http({
     method: 'POST',
     url: '/MyProject/requestUrl',
     headers: { 'Content-Type': undefined},//to set boundary value by default
     data: formData,
    })

Spring side
@RequestMapping(value = { "/requestUrl" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST)
@ResponseBody
public String getRequest(@RequestPart("obj1") Object1 object1,
        @RequestPart("obj2") Object2 Object2,HttpSession session)
        throws IOException {

        //implementation
}


text:
Q: viewForHeaderInSection disappears when scrolling I am using a custom header view in my UITableView, but as soon as i begin scrolling down the header disappears instead of staying in place like with the default headers. And it's not scrolling off the screen either, just completely disappering. viewForHeaderInSection is still being called but the drawRect method of my custom header view isn't. What am I doing wrong? Here's some code...
My UITableView datasource...
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HeaderView* headerView = [[[HeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 40.0f)] autorelease];
    return headerView;
}

...and my custom header...
-(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 115.0f, 125.0f, 133.0f, 0.5f);
    CGContextFillRect(context, CGRectMake(0.0f, 0.0f, 320.0f, 40.0f));
}

A: I've had this problem in the past, and to avoid it I usually make an ivar on my table delegate / data source, and then I add a property that retains the object in place. This way, the object is not reclaimed later when scrolling, and I can even access and change its values from other parts of the code (which might actually be required depending on the app). This way you don't give up the advantages of subclassing and creating your own headers.


text:
Q: HTTP Get Node JS to parse using document elements I have written some javascript that goes to a page and returns the data from the site, however, I would like to get specific elements off this html site and use functions like document.getElementById. How can I use that sort of functionality here? Currently, the console.log(chunk) simply spits out the entire body of html, I want to be able to parse that.
var http = require("http");

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/news'
};

http.get(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function(chunk){
        console.log(chunk);

    });

}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

A: There are many npm modules to perform the same, here are some
1.cheerio
2.jsdom


text: Q: CloudEventMessageBuilder does not allow a timestamp for the "time" field According to the Cloud Event spec the field time is a date and time (i.e. timestamp) but  the setTime method in CloudEventMessageBuilder only allows a OffsetTime.  Is this a defect in CloudEventMessageBuilder?  Is there a way around this?


text:
Q: Using the same object on different classes while keeping content of one object I am having 3 classes. First class is a Authorize class which have get/set property for User and Pass. Second, Add class is creating new instance of Authorize class and assigning a value from it's textboxes to the properties by using initializing new object:
Authorize authorize = new Authorize();

Third class, Display, is trying to get the value of property User and Pass from class Authorize. The problem is that I can not use here a new object of Authorize, because it will empty the content of first created object.
// Can not do, because the object will be discarded and new one created.
Authorize authorize = new Authorize();

How can I avoid/change this so I can access the same object from different class? This is a theoretical example. I am working on code but it's lengthily. If needed, I can post it here. But for now I leave as it is.
Please ask questions if I am not clear enough.
Examples for dummies highly recommended :)
Regards
-- Edit -- Some code:
AddEntryWindow.sc as Display class
namespace Store_Passwords_and_Serial_Codes
{
    public partial class AddEntryWindow : Form
    {
        private string user, pass;

        // Initializind ArrayList to store all data needed to be added or retrived.
        static private ArrayList addedEntry = new ArrayList();

        // Initializing MainWindow form.
        MainWindow mainWindow;

        // Making authentication possible.
        // AuthenticateUser authenticateUser = new AuthenticateUser();

        EncryptDecrypt en = new EncryptDecrypt();

        // Default constructor to initialize the form.
        public AddEntryWindow()
        {
            InitializeComponent();
        }

        public AddEntryWindow(MainWindow viaParameter) : this()
        {
            mainWindow = viaParameter;
        }

        public AddEntryWindow(string user, string pass)
        {
            this.user = user;
            this.pass = pass;
        }

        private void btnAddEntry_Click(object sender, EventArgs e)
        {
            // Making sure that type is selected.
            if {}
            else
            {
                // reason why I need the content of AuthenticationUser content.
                string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
                string decrypted = en.Decrypt(encrypted, user, pass);

                MessageBox.Show(user + pass);
                    //encrypted + Environment.NewLine + decrypted;

                /*mainWindow.ChangeTextBox = stringBuilder.ToString() + Environment.NewLine +
                    "Encrypted" + Environment.NewLine +
                    encrypted + Environment.NewLine +
                    "Decrypted" + Environment.NewLine +
                    decrypted + Environment.NewLine;
                */
            }
        }

        public static void ShowMe(AuthenticateUser au)
        {
            au.UserName = user;
            au.Password = pass;
        }

        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Deciding which data must be entered depending on
            // what type is selected from combo box.

            // PC
            // Web Site
            // Serial Code
        }
    }
}

AuthenticationWindow.cs as Add class
namespace Store_Passwords_and_Serial_Codes
{
    public partial class AuthenticationWindow : Form
    {
        public AuthenticationWindow()
        {
            InitializeComponent();
        }

        private void btnAuthenticate_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
            {
                MessageBox.Show("Please fill both information first.");
            }
            else
            {
                AuthenticateUser au = new AuthenticateUser();

                au.UserName = txtUserName.Text;
                au.Password = txtPassword.Text;

                AddEntryWindow.ShowMe(au);

                MessageBox.Show(au.UserName + au.Password);

                Close();
            }
        }
    }
}

Less important AuthenticateUser.cs as Authorize class.
using System;

namespace Store_Passwords_and_Serial_Codes
{
    public class AuthenticateUser
    {
        private string userName, password;

        public AuthenticateUser()
        {
        }

        public AuthenticateUser(string userNamePassed, string passwordPassed)
        {
            this.userName = userNamePassed;
            this.password = passwordPassed;
        }

        public string UserName
        {
            get
            {
                return userName;
            }
            set
            {
                userName = value;
            }
        }

        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }
    }
}

A: Edit:
You've given a bit more clarification in your question, so I'll try to address it.
In the main form, make your code do something like this:
private AuthenticateUser storedAuth; // shared data...

private void btnLogin_Click(object sender, EventArgs e)
{
    AuthorizeWindow authWindow = new AuthorizeWindow();
    authWindow.ShowDialog();
    storedAuth = authWindow.Result; // Get the auth result back...
}

In the AuthorizeWindow, make a result property, and set it when you click OK and have filled in all the data:
public AuthenticateUser Result { get; set; }

private void btnAuthenticate_Click(object sender, EventArgs e)
{
    if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
    {
        MessageBox.Show("Please fill both information first.");
    }
    else
    {
        // Don't try to call the other window here, just set the result and close...
        Result = new AuthenticateUser();
        Result.UserName = txtUserName.Text;
        Result.Password = txtPassword.Text;

        Close();
    }
 }

Then on the main form, when you create and open the AddEntryWindow, pass it the authentication you stored:
private void btnAdd_Click(object sender, EventArgs e)
{
    AddEntryWindow addWindow =
        new AddEntryWindow(storedAuth.User, storedAuth.Password);
    addWindow.ShowDialog();
}

But oops, I've created a small bug here.  We should check if they've authenticated first:
private void btnAdd_Click(object sender, EventArgs e)
{
    if(storedAuth == null)
    {
        MessageBox.Show("You must log in before you add an entry");
    }
    else
    {
        AddEntryWindow addWindow =
            new AddEntryWindow(storedAuth.User, storedAuth.Password);
        addWindow.ShowDialog();
    }
}

Also, I found a small bug in your AddEntryWindow code.  Make sure that all the constructors for all your windows always call InitializeComponent.  In this case, edit the constructor that takes a username and password to call the default constructor, like your other constructor that takes a MainWindow does:
public AddEntryWindow(string user, string pass)
    : this() // important!
{
    this.user = user;
    this.pass = pass;
}

Before edit:
I don't completely understand your example code.  It would be easier if you would create new code samples to add to your question.
Here's what I got from what you've said, though:
public class Authorize
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Add
{
    public void Login()
    {
        Authorize authorize = new Authorize();
        authorize.Username = usernameTextBox.Text;
        authorize.Password = passwordTextBox.Text;
        // Todo: Rest of login logic here
    }

    // Todo: Other code here...
}

public class Display
{
    public void Show()
    {
        Authorize authorize = new Authorize();
        // uh oh, Username and Password are null!
    }

    // Todo: Other code here...
}

Solution
The easiest way to do this is to pass the instance of Authorize to the Show method (or whatever you are actually calling it) in your Display class.  Just accept an instance of Authorize as an argument to that method:
public class Display
{
    public void Show(Authorize authorize)
    {
        // Now we have the values that the Login method created...
    }

    // ...
}

public class Add
{
    public void Login()
    {
        Authorize authorize = new Authorize();
        authorize.Username = usernameTextBox.Text;
        authorize.Password = passwordTextBox.Text;
        display.Show(authorize);
    }

    // ...
}

A: There are two ways to achieve what you are looking for.  The first is to just pass a single instance of Authority around to all the different methods that will use it.  I assume this is prohibitive for some reason, otherwise you would already be doing it.  There is a design pattern called singletons that may be useful for what you're doing.  The linked page has some code examples.

A: Passing as Argument is the best solution, if you have problem in passing as argument,then go for Authorize as Property(Set/Get), so you can get rid out of Argument passing issue. If that is also problem then go either either with Singleton Pattern or create Static class.


text:
Q: Using NHibernate and not referencing its assembly in the client application We have a multi-tiered application using CSLA Business Objects and NHibernate ORM.
In our Business Objects, we hold our collection data members as ICollection<T>, and in our object mapping files we define them as <set>s.
Since NHibernate uses its own concrete types to fetch these collections, we have a problem when these collections reach the client, because we don't reference the NHibernate assembly in the client application (and we don't want to change that).
Is there a way to solve that or somehow force NHibernate to use a .net collection type, or our own collection type, without implementing any NHibernate collection type interface?
Thanks in Advance,
Yaron.

A: NHibernate needs its own implementations of the collections to manage the persistency states. So you can't change NHibernates behaviour.
We are using WCF, it turns collections to arrays or lists when serializing. If your infrastructure doesn't do this, you need to convert the objects before sending to the client.
It's best to use a DTO (data transfer object) model anyway. You need copy all data from the business model to the DTO model.
If you don't like to have a DTO model, I think you need to exchange your collections. Write a method that exchanges NH's collections with .NET framework collections, eg. using reflection.
Or - you live with the reference to NHibernate on the client.

A: You can use ICollection<T> and HashSet<T> without referencing Iesi.Collections


text:
Q: Laravel scope query with nested models in 3-way pivot table I have a Product Model that needs to be connected with Processings, that describe how the Product can be manipulated, and Positions, that describe where the Product can be manipulated.
In other words, a Product can be processed into multiple positions.
The "Product Data" should be returned with nested processings into positions, so that, for every Position into the database, a Product can be associated with related Processings, in a scheme similar to the one below:
Products [
    product_attributes,
    Positions [
        position_attributes,
        Processings: [
            processing_attributes
        ]
    ]
]

So, I have created a 3-way Pivot Table with the following code:
Schema::create('product_position_processing', function (Blueprint $table) {

    // 3-way pivot
    $table->integer('product_id')->unsigned()->index();
    $table->foreign('product_id', 'ppp_aid_foreign')->references('id')->on('products')->onDelete('cascade');
    $table->integer('position_id')->unsigned()->index();
    $table->foreign('position_id', 'ppp_bid_foreign')->references('id')->on('positions')->onDelete('cascade');
    $table->integer('processing_id')->unsigned()->index();
    $table->foreign('processing_id', 'ppp_cid_foreign')->references('id')->on('processings')->onDelete('cascade');
    $table->primary(['product_id', 'position_id', 'processing_id'], 'index-base-combined');

    // these attributes define the minimum and maximum order amount based on the product + position + processing combination
    $table->integer('minimum_order_amount')->nullable();
    $table->integer('maximum_order_amount')->nullable();

    $table->timestamps();
});

Then, I have defined the relations between the 3 different models in this way:
Processing Model
class Processing extends Model {
    use SoftDeletes;

    protected $dates = ['deleted_at'];
    protected $guarded = ['id', 'created_at', 'updated_at'];
    protected $casts = [
        'is_publicly_hidden' => 'boolean'
    ];
    protected $hidden = ['pivot'];

    public function products() {
        return $this -> belongsToMany ( Product::class, 'product_position_processing', 'processing_id', 'product_id' );
    }

    public function positions () {
        return $this -> belongsToMany ( Position::class, 'product_position_processing', 'processing_id', 'position_id' );
    }

    ...
    ...

}

Position Model
class Position extends Model {
    use SoftDeletes;

    protected $dates = ['deleted_at'];
    protected $guarded = ['id', 'created_at', 'updated_at'];
    protected $hidden = ['pivot'];

    public function products() {
        return $this->belongsToMany ( Product::class, 'product_position_processing', 'position_id', 'product_id' );
    }

    public function processings ( ) {
        return $this -> belongsToMany ( Processing::class, 'product_position_processing', 'position_id', 'processing_id' );
    }

    ...
    ...
}

Product Model
class Product extends Model implements SluggableInterface {
    use SoftDeletes;
    use SluggableTrait;

    protected $dates = ['deleted_at'];
    protected $guarded = ['id', 'created_at', 'updated_at'];
    protected $sluggable = [
        'build_from' => 'name',
        'save_to'    => 'slug',
        'include_trashed' => true
    ];

    ...
    ...

    public function processings() {
        return $this->belongsToMany(Processing::class, 'product_position_processing', 'product_id', 'processing_id');
    }

    public function positions() {
        return $this->belongsToMany(Position::class, 'product_position_processing', 'product_id', 'position_id');
    }

    ...
    ...

    public function scopeWithCompleteData ($query) {
        return $query->with([
            ...
            ...
            'positions' => function($query) {
                return $query->with(['processings' => function ( $query ) {
                    return $query->select('id', 'name')->groupBy('processing_id');
                }])->groupBy('position_id');
            },
            ...
            ...
        ]);
    }

}

Now, the Products are returned in json via the ProductsController that, with the following code, returns a JSON in this format.
Product Getter:
...
...
$products = Product::withCompleteData() -> get();
return $this -> ok ( $products );

Example "ALL Products" @get JSON:
{
    "status": "OK",
    "data": [
        {
            "id": 1,
            "category_id": 1,
            "subcategory_id": 0,
            "brand_id": 1,
            "sku": "BD615149D6",
            ...
            ...
            "positions": [
                {
                    "id": 1,
                    "name": "POS1",
                    "processings": [
                        {
                            "id": 1,
                            "name": "PROC1",
                            "pivot": {
                                "position_id": 1,
                                "processing_id": 1
                            }
                        },
                        {
                            "id": 2,
                            "name": "PROC2",
                            "pivot": {
                                "position_id": 1,
                                "processing_id": 2
                            }
                        },
                        {
                            "id": 3,
                            "name": "PROC3",
                            "pivot": {
                                "position_id": 1,
                                "processing_id": 3
                            }
                        }
                    ]
                },
                {
                    "id": 2,
                    "name": "POS2",
                    "created_at": "2016-08-01 07:39:11",
                    "updated_at": null,
                    "deleted_at": null,
                    "processings": []
                },
                {
                    "id": 3,
                    "name": "POS3",
                    "created_at": "2016-08-01 07:39:11",
                    "updated_at": null,
                    "deleted_at": null,
                    "processings": []
                }
            ]
        },
        {
            "id": 2,
            "category_id": 2,
            "subcategory_id": 0,
            "brand_id": 2,
            "sku": "BD615149D6",
            ...
            ...
            "positions": [
                {
                    "id": 5,
                    "name": "POS5",
                    "created_at": "2016-08-01 07:39:11",
                    "updated_at": null,
                    "deleted_at": null,
                    "processings": []
                }
            ]
        }
    ]
}

The problem is, the data returned is not correct. The Query Builder seems to connect the various relationships in a strange way. Unfortunately I'm still not enough proactive in understanding what lies below the magic of the query builder, and don't know how to debug and where to make modifications to the code.
Can anyone help out with this 3-way pivot table with nested objects into the Laravel query builder?


text:
Q: Can't get this 'url-label' regex to be accurate I was writing a Python regex to match urls. I have written a reasonably complex one that is working fairly well. I was trying to get the label part in the hostname to be more accurate based on what I read on Wikipedia.
Basically if you see my code snippet, I have a truth table to test the label part I have written. If you want to understand the truth table, its based on 'Restrictions on hostnames' in the hostname Wiki page.
I just can't get case 1(strings[0]) to work without breaking other cases and cannot figure out just why case 1 wouldn't work. I have used debugging tools but the failure string in question is too small for me to get any significant information.
Please help me out and give me a fix to the one I have written so that I know what I am missing.
If you are wondering why I am not using a third party library to match urls, I am learning regular expressions.
import re

F = False
T = True

results = [T,F,T,F,F,F,T,F,T,F,F,F,F,F]

strings = ['a','-','aa','--','-a','a-','aaa','aa-','a-a','a--','-aa','-a-','--a','---']

x = list(range(len(strings)))

regex_test = r'(?P<Label>(?P<Label_start>[a-zA-Z0-9])((?P<Label_mid>[a-zA-Z0-9-]{1,61})?)(?=(?P<Label_end>[a-zA-Z0-9](?=[./])))(?P=Label_end)?)\.'

if len(strings) == len(results):
    for n in x:
        if results[n] == bool(re.match(pattern = regex_test, string = strings[n] + '.')):
            print("Works.")
            if results[n] == True:
                print(re.match(pattern = regex_test, string = strings[n] + '.').groupdict())
        else:
            print("Bug for: " + strings[n])
            #print(str(re.match(pattern = regex_test, string = strings[n] + '.',flags=re.DEBUG)))

A: Sometimes it is easier (and more readable) to just use python! However, there is one portion of the domain name validation that benefits from re. See my attempt here, or my full snipett below.
# What are valid hostnames?
#    (1) Series of labels separated by periods.
#    (2) Each label can contain only letters, numbers and hyphens.
#    (3) Each label can not start or end with a hyphen.
#    (4) Each label can be 1-63 characters
#    (5) Entire domain cannot be longer than 253 characters.

import re

domains = ['en.wikipedia.org',
           'my.his-site.com',
           '-bad.site-.5345']

def is_valid_hostname(domain):
    # Utilize rule 1 to split into labels.
    labels = domain.split('.')

    for label in labels:
        # Check rules 2 and 3.
        if not re.search(r'^[A-z0-9][A-z0-9\-]*[A-z0-9]$', label):
           return False

        # Check rule 4.
        if not (0 < len(label) < 64):
            return False

    # Check rule 5.
    if len(domain) > 253:
        return False

    return True

for domain in domains:
    if is_valid_hostname(domain):
        print('{}:\tvalid'.format(domain))
    else:
        print('{}:\tinvalid'.format(domain))


text:
Q: Android 4.3 KeyStore - chain == null while trying to retrieve keys Following this blog, I'm using this code to create and store a KeyPair in Android KeyStore:
Context ctx = getApplicationContext();
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(1, Calendar.YEAR);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx).
setAlias(RSA_KEYS_ALIAS).setSubject(
  new X500Principal(String.format("CN=%s, OU=%s",
    getApplicationName(), ctx.getPackageName()))).
setSerialNumber(BigInteger.ONE).
setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();

KeyPairGenerator kpGenerator;
try {
    kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

    kpGenerator.initialize(spec);
    kpGenerator.generateKeyPair();
} catch (Exception e) {
    showException(e);
}

When I try to retrieve public key from the KeyStore using this code, a NullPointerException with the message chain == null is thrown.
public RSAPublicKey getRSAPublicKey() {
    RSAPublicKey result = null;
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyStore.PrivateKeyEntry keyEntry =
            (KeyStore.PrivateKeyEntry) keyStore.getEntry(RSA_KEYS_ALIAS, null); // --< exception is thrown here
        result = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
    }
    } catch (Exception e) {
        showException(e);
    }
    return result;
}

The same goes with the the code to retrieve private key.
Update:
I compared my code with Google BasicAndroidKeyStore sample. The mechanism to generate, store and retrieve the key pair in that sample is virtually the same to what I've implemented. I'm puzzled as to why this code has stopped functioning after a few months of perfectly working.
Any suggestions or hints would be appreciated.

A: Apparently names in Android KeyStore must be unique amongst all Apps. I had another app which used the same name for its keys. After changing the the common library used by both apps to create and and use keys to include package name in its key names, the problem went away...

A: In my case, I had multiple calls to obtain the KeyStore at nearly the same time. I had to create a single instance and refer to that if it existed, otherwise KeyStore.getInstance("AndroidKeyStore") returned null and raised an Exception.
To protect against multiple async requests causing a crash, use a stored instance from just one KeyStore.getInstance().

A: In my case, I was trying to get public key before generating it. (getRSAPublicKey() called before generateKeyPair())


text:
Q: Pagination In Javascript Is Not Working I am going to paginate my search page because i have total 16 records in it, So i paginated into 4 pages each comprises of 4 records in each page.I have used javascript to handle pagination.And I have used ajax request in javascript. But My problem is when i click submit button of script.js the first 4 records will display but when i click next button it dosen't display any thing, can u please tell where i went wrong what corrections i need to make, please,
Thank you in advance.
book_search.php
 <?php
    include('assets/page_header.php');

    ?>

SEARCHING THE BOOK

    <form  id="search"  name="search" action="#" method="post">
    Search : <input type="text" name="author" id="author">

    <input id="submit" name="submit"  type="submit" value="Submit">

    Next
    Previous
    back
    LastPage
    1
    2
    3
    4

    </form>

ajax.php

    <?php
    include('db.php');
    $page="";
    if(isset($_GET['page']))
    {

    $page=$_GET['page'];
    echo $page;
    }

    $num_rec_per_page = 5;
    ?>

    <
    <?php
    if(isset($_POST['author']))//&&isset($_POST['page'])&&isset($_POST['total']))
    {

        $author=mysql_real_escape_string($_POST['author']);
        $total_pages=mysql_real_escape_string($_POST['total']);
        if($author=="")
        {
            echo "Please Enter Title or Author or Publisher";
        }
        else
        {

            if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
            $start_from = ($page-1) * $num_rec_per_page;

            $query1="select * from books  where  title LIKE '%$author%' OR author LIKE '%$author%' OR publisher LIKE '%$author%'  LIMIT $start_from, $num_rec_per_page  ";
            echo $query1;
            $rs_result=mysql_query("select * from books  where  title LIKE '%$author%' OR author LIKE '%$author%' OR publisher LIKE '%$author%'");

            $total_records = mysql_num_rows($rs_result);
            echo $total_records;//count number of records
            $total_pages = ceil($total_records / $num_rec_per_page);
            $phpself=$_SERVER['PHP_SELF'];
            if($page>1)
            {
            $pagenumber=$page-1;
            $prev="[Back]";
            $first="[FirstPage]";
            }
            else
            {
            $prev='';
            $first='';
            }
            if($page<$total_pages)
            {
            $pagenumber=$page+1;
            $next="[Next]";
            $last="[LastPage]";
            }
            else
            {

            $next="";
            $last="";
            /*$next='[next]';
            $last='[LastPage]';*/
            }
            //for ($i=1; $i<=$total_pages; $i++) {
               // echo " ".$i." ";

          //  };

            echo $first.$prev."Showing page<bold>$page</bold>of<bold>$total_pages</bold>pages".$next.$last;

            /*if($total_records > 0) {
                echo " ".'<'."  "; // Goto 1st page
            }
             // echo " ".'<<'."  ";

            if($total_records > 0) {
                echo " ".'>'."  "; // Goto last page
            }*/

            $result1=mysql_query($query1) or  die(mysql_error());
            //print_r($result1);
            $count=mysql_num_rows($result1);
            //echo $count;
            $display= "
";
            $display.= "
title	   author	   publisher	   numcopies	    status	    number_of_copies_available	 Action
";
            while($row=mysql_fetch_array($result1)){
                $count=mysql_num_rows($result1);
                //print_r($row['bookid']);
                $r12=$row['bookid'];
                $query2=mysql_query("select bookid from bookrentalinfo where bookid=$r12");
                $num_copies_borrowed=mysql_num_rows($query2);
                $num_copies_count=$row['numcopies'];
                $number_of_copies_available=$num_copies_count-$num_copies_borrowed;
                $display.= "
";
                //echo "".$row['bookid']."	";
            $display.="".$row['title']."	";
                $display.= "".$row['author']."	";
                $display.= "".$row['publisher']."	";
                $display.= "".$row['numcopies']."	";
                $display.= "".$row['status']."	";
                $display.= "".$number_of_copies_available."	";
                if($number_of_copies_available>0)
                {
                    $display.= "Rent	";
                }
                else {
                    $display.= "rent link is not activated";
                    $display.="	";
                }

                $display.= "
";
            }
            $display.="
";
            echo $display;

        }
    }
    ?>

        <?php
        if(isset($_POST['start'])&& isset($_POST['end'])&&isset($_POST['author']))
        {
        echo "hi";

        $author=mysql_real_escape_string($_POST['author']);

        $start_val=mysql_real_escape_string($_POST['start']);
        $end_val=mysql_real_escape_string($_POST['end']);
        $start_val=$page;
        $end_val=$start_val*5;

        $string=" select * from books  where  title LIKE '%$author%' OR author LIKE '%$author%' OR publisher LIKE '%$author%'  LIMIT $start_val, $end_val  ";
        echo $string;
        $query20=mysql_query($string);
        echo $query20;

        $display= "
";
            $display.= "
title	   author	   publisher	   numcopies	    status	    number_of_copies_available	 Action
";
            while($row=mysql_fetch_array($query20)){
                $count=mysql_num_rows($query20);
                //print_r($row['bookid']);
                $r12=$row['bookid'];
                $query2=mysql_query("select bookid from bookrentalinfo where bookid=$r12");
                $num_copies_borrowed=mysql_num_rows($query2);
                $num_copies_count=$row['numcopies'];
                $number_of_copies_available=$num_copies_count-$num_copies_borrowed;
                $display.= "
";
                //echo "".$row['bookid']."	";
            $display.="".$row['title']."	";
                $display.= "".$row['author']."	";
                $display.= "".$row['publisher']."	";
                $display.= "".$row['numcopies']."	";
                $display.= "".$row['status']."	";
                $display.= "".$number_of_copies_available."	";
                if($number_of_copies_available>0)
                {
                    $display.= "Rent	";
                }
                else {
                    $display.= "rent link is not activated";
                    $display.="	";
                }

                $display.= "
";
            }
            $display.="
";
            echo $display;

        }

        ?>
page.js

var no_of_records=16;
    var items_per_page=4;
    var page=1;
    var start_page=1;
    var end_page=0;

    function Next(e)
    {
    var start_page=page;
    var end_page=start_page*5;
    var TotalPages=Math.ceil(no_of_records/items_per_page);
    page++;
    e.preventDefault();

    $.ajax({
            type: "POST",
            url: "db/ajax.php",
            data: {'start':start_page,'end':end_page,'page':page},
            cache: false,
            success: function(result){
            //alert("submitted"+result);
            $('#display').html(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
            }

        });
        }

    function pagination()
                {

                    e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: "db/ajax.php",
                    data: {'start':start_page,'end':end_page,'page':page},
                    cache: false,
                    success: function(result){
                    //alert("submitted"+result);
                    $('#display').html(result);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                            alert(xhr.status);
                            alert(thrownError);
                    }

                });

                }
                function Previous(e)
            {
            var start_page=page;
            var end_page=start_page*5;
            var TotalPages=Math.ceil(no_of_records/items_per_page);
            page--;
            e.preventDefault();

            $.ajax({
                    type: "POST",
                    url: "db/ajax.php",
                    data: {'start':start_page,'end':end_page,'page':page},
                    cache: false,
                    success: function(result){
                    //alert("submitted"+result);
                    $('#display').html(result);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                            alert(xhr.status);
                            alert(thrownError);
                    }

                });
                }

script.js

    $(document).ready(function(){
    $("#submit").click(function(e){
    var author = $("#author").val();

        var dataString='author='+author;
        alert(dataString);

            if(author=='')
            {
            alert("Please Enter Author or Title or Publisher Fields");
            }
            else
            {
                // AJAX Code To Submit Form.
                $.ajax({
                type: "POST",
                url: "db/ajax.php",
                data: dataString,
                cache: false,
                success: function(result){
                //alert("submitted"+result);
                $('#display').html(result);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                }
                });
            }
            e.preventDefault();
            });
    });

A: here is a simple way of pagination according to the class name:
    var totalPages;
function updatePagination(page) {
    $(".pagination").html("");
    for (var i = page-1; i < page + 3; i++) {
        $('.pagination').append("
" + (i+1) + "
 ");
    }
}
var limitPerPage=25;
function displayPage(currentPage){
        if(currentPage==totalPages) return false;
        updatePagination(currentPage);
      // Check if page number that was clicked on is the current page that is being displayed
    //   if ($(this).hasClass('active')) {
    //     return false; // Return false (i.e., nothing to do, since user clicked on the page number that is already being displayed)
    //   } else {
        //var currentPage = $(this).index();
        //updatePagination(currentPage);
         // Get the current page number
        $(".pagination li").removeClass('active'); // Remove the 'active' class status from the page that is currently being displayed
        $(this).addClass('active'); // Add the 'active' class status to the page that was clicked on
        $("#cardsdisplay .ma-card").hide(); // Hide all items in loop, this case, all the list groups
        var grandTotal = limitPerPage * currentPage; // Get the total number of items up to the page number that was clicked on

        // Loop through total items, selecting a new set of items based on page number
        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
          $("#cardsdisplay .ma-card:eq(" + i + ")").show(); // Show items from the new page that was selected
        }
     // }

}

function PaginateVideos(){
    'use strict';
    console.log("inisde pagination");
    var numberOfItems = $('#cardsdisplay .ma-card').length; // Get total number of the items that should be paginated
    console.log(numberOfItems);
    var limitPerPage = 25; // Limit of items per each page
    $('#cardsdisplay .ma-card:gt(' + (limitPerPage - 1) + ')').hide(); // Hide all items over page limits (e.g., 5th item, 6th item, etc.)
    totalPages = Math.round(numberOfItems / limitPerPage); // Get number of pages
    //$(".pagination").append("
" + 1 + "
 "); // Add first page marker

    // Loop to insert page number for each sets of items equal to page limit (e.g., limit of 4 with 20 total items = insert 5 pages)
    for (var i = 0; i <3; i++) {
      $(".pagination").append("
" + (i+1) + "
 "); // Insert page number into pagination tabs
    }

    // Add next button after all the page numbers
    $(".pagination").append("
»
");

    // Function that displays new items based on page number that was clicked
    // $(".pagination li.current-page").on("click", function() {

    // });

    // Function to navigate to the next page when users click on the next-page id (next page button)
    $("#next-page").on("click", function() {
      var currentPage = $(".pagination li.active").index(); // Identify the current active page
      // Check to make sure that navigating to the next page will not exceed the total number of pages
      if (currentPage === totalPages) {
        return false; // Return false (i.e., cannot navigate any further, since it would exceed the maximum number of pages)
      } else {
        currentPage++; // Increment the page by one
        $(".pagination li").removeClass('active'); // Remove the 'active' class status from the current page
        $("#cardsdisplay .ma-card").hide(); // Hide all items in the pagination loop
        var grandTotal = limitPerPage * currentPage; // Get the total number of items up to the page that was selected

        // Loop through total items, selecting a new set of items based on page number
        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
          $("#cardsdisplay .ma-card:eq(" + i + ")").show(); // Show items from the new page that was selected
        }

        $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass('active'); // Make new page number the 'active' page
      }
    });

    // Function to navigate to the previous page when users click on the previous-page id (previous page button)
    $("#previous-page").on("click", function() {
      var currentPage = $(".pagination li.active").index(); // Identify the current active page
      // Check to make sure that users is not on page 1 and attempting to navigating to a previous page
      if (currentPage === 1) {
        return false; // Return false (i.e., cannot navigate to a previous page because the current page is page 1)
      } else {
        currentPage--; // Decrement page by one
        $(".pagination li").removeClass('active'); // Remove the 'activate' status class from the previous active page number
        $("#cardsdisplay .ma-card").hide(); // Hide all items in the pagination loop
        var grandTotal = limitPerPage * currentPage; // Get the total number of items up to the page that was selected

        // Loop through total items, selecting a new set of items based on page number
        for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
          $("#cardsdisplay .ma-card:eq(" + i + ")").show(); // Show items from the new page that was selected
        }

        $(".pagination li.current-page:eq(" + (currentPage - 1) + ")").addClass('active'); // Make new page number the 'active' page
      }
    });

}

UpdatePagination() is only if you had huge number of pages, so you can control the display


text:
Q: Python3: Class inheritance and private fields I am trying to understand how class inheritance works in Python 3, in particular how private fields interact with local and inherited methods. Here are some examples to illustrate the issue.
First, if a variable var in the Superclass is public, then any method in the Subclass will also be able to alter it:
class Superclass:
    var = 1
    def getVar(self):
        print(self.var)

class Subclass(Superclass):
    def __init__(self):
        self.var = 123

my_object = Subclass()
my_object.getVar() # outputs 123

The same is not true if the variable __var in the Superclass is private, any inherited method will ignore modifications done by the Subclass:
class Superclass:
    __var = 1
    def getVar(self):
        print(self.__var)

class Subclass(Superclass):
    def __init__(self):
        self.__var = 123

my_object = Subclass()
my_object.getVar() # outputs 1!

Local methods in the Subclass can alter it:
class Superclass:
    __var = 1

class Subclass(Superclass):
    def __init__(self):
        self.__var = 123
    def getVar(self):
        print(self.__var)

my_object = Subclass()
my_object.getVar() # outputs 123

But in order to use an inherited method with the altered value, I must use self._Superclass__var instead of self.__var in the Subclass:
class Superclass:
    __var = 1
    def getVar(self):
        print(self.__var)

class Subclass(Superclass):
    def __init__(self):
        self._Superclass__var = 123

my_object = Subclass()
my_object.getVar() # outputs 123

Why is this the case? Are private fields not being inherited by the subclasses and therefore the variable self.__var inside the Subclass is NOT pointing to the same value the variable self.__var inside Superclass?

A: Python doesn't really have private variables, there are two conventions:

*

*Variables prefixed with underscore (_var) are used to let you and other people know that it's intended to be private

*Variables prefixed with two undersores (__var) are also mangled by python interpreter and also are prefixed by class name, but they are still accessible like self._Superclass__var in your example

See also the documentation.
There is one more issue in your code - you are using class variables, not instance variables (this is what usually called static class variables in other languages).
Check this example:
class Superclass:
    var = 1

    def getVar(self):
        print(self.var)

my_object = Superclass()
my_object2 = Superclass()
my_object.getVar()  # outputs 1
my_object2.getVar()  # outputs 1

Superclass.var = 321  # this value is share across all instances
my_object.getVar()  # outputs 321
my_object2.getVar()  # outputs 321

And when you are doing self.var = xxx assignments in your methods, you just hide the class-level variable and add the new instance-level variable with same name.
See also the documentation: https://docs.python.org/3.6/tutorial/classes.html#class-and-instance-variables


text:
Q: Creating an SQL with subquery Woo Commerce I have the following query:
    SELECT o.`order_id`, o.`order_item_name`,

(select  pm.`meta_value`
 from
 `wp_postmeta` as pm
 WHERE
 pm.`post_id` = o.`order_id`
AND
 pm.`meta_key` = '2-certificate') as 'certificate',

 (select  pm.`meta_value`
 from
 `wp_postmeta` as pm
 WHERE
 pm.`post_id` = o.`order_id`
AND
 pm.`meta_key` = '3-serial') as 'serial'

 FROM `wp_woocommerce_order_items` as o,
`wp_woocommerce_order_itemmeta` as om,
`wp_postmeta` as pm
WHERE
o.`order_item_id` = om.`order_item_id`
AND
pm.`post_id` = o.`order_id`
AND
om.`meta_key` = 'bcs'

I want to be able to connect the order_item, order_item_meta, and post meta, and the post meta will call out 2 different meta_keys which are 3-serial and 2-certificate on 2 different columns. But when I will do the query, it will say this error

Blockquote
#1242 - Subquery returns more than 1 row

Is there any way to fix this? It may be that the subquery is causing the problems.

A: It seems that some of your orders return more than one value in your subqueries. You can not use a sintax:
select (select ...), (select ...)

where the (select ...) return more than one value.
If you want to find what orders are behaving this way, you can use the next query.
select  pm.`post_id`, pm.`meta_key`
from  `wp_postmeta` as pm
where pm.`meta_key` in ('2-certificate', '3-serial')
group by pm.`post_id`, pm.`meta_key`
having count(*) > 1


text:
Q: Trasnforming/Changing all variables at one go in python I'm new to python & I'm looking to transform the variables in my data set. I have around 89 variables to be transformed & hence, transforming them one by one is tedious. I'm looking to transform 88 variables.
How do I go about doing this? One option I can think of is to create a list of all the columns of the data set & then call this list in the function I define.
Is there any other way?
Thank you,
Nimish


text:
Q: Reading data from a file in C++ I'm trying to read data from a file line by line and push them back to a vector
The data is of the format
123 23 45
19 46 22
87 26 31
The program gives no output and an error code of 11.
std::vector<int>* readDataFromFile(std::string path){

    std::vector<int>* v = new std::vector<int>;
    int a, b, c;
    std::ifstream inputStream;
    inputStream.open(path);
    while(inputStream>>a>>b){
        v->push_back(a);
        v->push_back(b);
        v->push_back(c);
    }
    inputStream.close();

}

int main() {

    std::vector<int>* v = readDataFromFile("file1.txt");
    for(auto it= v->begin(); it != v->end(); it++){
        std::cout<<*it<<std::endl;
    }

    return 0;
}

A: *

*Don't forget to read c in the loop:
while(inputStream>>a>>b>>c) {
    v->push_back(a);
    v->push_back(b);
    v->push_back(c);
}

*You are allocating a std::vector dynamically and never deleting it. Instead return the vector by value.

*And also the call to fstream::close is not necessary, the stream is closed from fstream's destructor when it goes out of scope.

*In general it is better to pass read-only string parameters by const reference.
#include <iostream>
#include <fstream>
#include <vector>

std::vector<int> readDataFromFile(const std::string& path){
  std::vector<int> v;
  int a, b, c;
  std::ifstream inputStream(path);
  while(inputStream>>a>>b>>c){
      v.push_back(a);
      v.push_back(b);
      v.push_back(c);
  }

  return v;
}

int main() {
  std::vector<int> v = readDataFromFile("file1.txt");
  for(auto it = v.begin(); it != v.end(); it++){
      std::cout<<*it<<std::endl;
  }

  return 0;
}


text:
Q: Possible to force logistic regression or other classifier through specific probability? I have a data set with a binary variable[Yes/No] and a continuous variable (X). I'm trying to make a model to classify [Yes/No] X.
From my data set, when X = 0.5, 48% of the observations are Yes. However, I know  the true probability for Yes should be 50% when X = 0.5. When I create a model using logistic regression X = 0.5 != P[Yes=0.5].
How can I correct this? I guess all probabilities should be slightly underestimated if it does not pass true the correct point.
Is it  correct just to add a bunch of observations in my sample to adjust the proportion?
Does not have to be just logistic regression, LDA, QDA etc is also of interest.
I have searched Stack Overflow, but only found topics regarding linear regression.

A: I believe that in R (assuming you're using glm from base R) you just need
glm(y~I(x-0.5)-1,data=your_data,family=binomial)

the I(x-0.5) recenters the covariate at 0.5, the -1 suppresses the intercept (intercept = 0 at x=0.5 -> probability = 0.5 at x=0.5).
For example:
set.seed(101)
dd <- data.frame(x=runif(100,0.5,1),y=rbinom(100,size=1,prob=0.7))
m1 <- glm(y~I(x-0.5)-1,data=dd,family=binomial)
predict(m1,type="response",newdata=data.frame(x=0.5)) ## 0.5

A: The OP wrote:

How can I correct this? I guess all probabilities should be slightly underestimated if it does not pass true the correct point.

This is not true. It is perfectly possible to underestimate some values (like the intercept) and overestimate others.
An example following your situation:
The true probabilities:
set.seed(444)

true_prob <- function(x) {

  # logit probabilities
  lp <- (x - 0.5)

  # true probabilities
  p <- 1 / (1 + exp(-lp))
  p

}

true_prob(x = 0.5)
[1] 0.5

But if you simulate data and fit a model, the intercept could be underestimated and other values overestimated:
n <- 100
# simulated predictor
x <- runif(n, 0, 1)
probs <- true_prob(x)

# simulated binary response
y <- as.numeric(runif(n) < probs)

Now fit a model and compare true probabilities vs fitted ones:
> true_prob(0.5)
[1] 0.5
> predict(m, newdata = data.frame(x = 0.5), type = "response")
       1
0.479328
> true_prob(2)
[1] 0.8175745
> predict(m, newdata = data.frame(x = 2), type = "response")
        1
0.8665702

So in this example, model underestimates at x = 0.5 and overestimates at x = 2


text:
Q: How can I have in a __m128 variable a whole complex number? I don't have too much experience using intrinsics in C. My problem is having this function
void function(complex float* A, complex float* B, complex float alpha) {

I want to use alpha like __m128, but if I do this
__m128 alfa = _mm_load_ps((float const *)&alpha);

alfa only gets the real part of the complex number.
How can I have in __m128 alfa the whole complex number?

A: This code worked fine for me:
complex float a __attribute__ ((aligned (16))) = 5 + 10*I;
__m128 f = _mm_load_ps((float const *)&a); // requires 16B alignment
float *p = (float *)&f;
printf("real(0): %f, imag(1): %f, (2): %f, (3): %f\n", p[0], p[1], p[2], p[3]);

prints
real(0): 5.000000, imag(1): 10.000000, (2): 0.000000, (3): 0.000000

Are you sure alpha has a non-zero imaginary part? How do you know you are only getting the real part?


text:
Q: How do I set file permissions when opening a file in C++? In C++, I want to open a file and set its permission, but I failed. Below is my program:
string filename="test.cnf";
ofstream ofile;
ofile.open(filename.c_str(),O_RDONLY);
ofile.close()

But I get the following error:
error: invalid conversion from 'int' to 'std::_Ios_Openmode'

error:   initializing argument 2 of 'void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]'

How to set the permission of the file to such as 644, 700?

A: The option you seem to want to specify (O_RDONLY) isn't a
"permission", it's an access mode.  These are set implicitly according
to the combinations of std::ios_base::in and std::ios_base::out:
in alone results in O_RDONLY, out alone in O_WRONLY and in |
out in O_RDWR.
For the permissions on a created file, the answer is, rather annoyingly,
thet you can't specify them.  std::filebuf::open() (which is what
std::ifstream and std::ofstream ultimately call) has no options or
provisions for passing in any indication of permissions to be used if it
must create the file.
The only way to do this is by using your system level functions (open
under Linux, CreateFile under Windows—despite the names, open
may create a file, and CreateFile will open an existing file, without
creating anything).  Using system level open/CreateFile, however,
means using system level read/ReadFile and write/WriteFile.

A: There is not O_RDONLY mode for fstream. You should use one of:

*

*ios::app

*ios::binary

*ios::ate

*ios::in

*ios::out

*ios::trunc
Or their combinations (say ios::app | ios::binary). For your case you should use ios::in (maybe with ios::binary). Look at this for more details.

A: If you are on unix systems, what you need is the "setmode" or "getmode" function.
From your shell command-line, type "man setmode"

A: *

*The second argument of fstream::open is a combination of flags chosen in ios::app, ios::binary, ios::ate, ios::in, ios::out, ios::trunc.

*There is no standard C++ interface to set the access right.  The implementations I know are using 0666 which is then masked by the value set by umask(2). This is also the usual behavior of unix applications (the umask is inherited from the parent and shells have a builtin umask command).  My recommandation is that you do nothing and rely on the umask set by the user. If that is not applicable, temporarily change the umask in your app.


text:
Q: Recursive descent parsing and abstract syntax trees I'm hard-coding a recursive decent parser, mostly for learning purposes and, I've run into some trouble.
I'll use this short excerpt from the CSS3 grammar as an example:
simple_selector = type_selector | universal;
type_selector = [ namespace_prefix ]? element_name;
namespace_prefix = [ IDENT | '*' ]? '|';
element_name = IDENT;
universal = [ namespace_prefix ]? '*';

First, I didn't realize that namespace_prefix was an optional part within both the type_selector and universal. That led to the type_selector always failing when fed input like *|* because it was blindly being considered for any input that matched the namespace_prefix production.
Recursive decent is straightforward enough but my understanding of it is that I need to do a lot of (for lack of better word) exploratory recursion before settling on a production. So I changed the signature of my productions to return Boolean values. This way I could easily tell whether a specific production resulted in success or not.
I use a linked list data structure to support arbitrary look-ahead, and can easily slice this list to attempt a production and then return to my starting point if the production doesn't succeed. However, while trying out a production, I'm passing along mutable state, trying to construct a document object model. This isn't really working out because I have no way of knowing whether the production will be successful or not. And if the production isn't successful, I need to somehow undo any changes made.
My question is this. Should I use an abstract syntax tree as an intermediate representation and then go from there? Is this something you would commonly do to work around this problem? Because the issue seems to be primarily with the document object model not being a suitable tree data structure for recursion.

A: I'm not intimately familiar with CSS, but in general what you would do is refactor the grammar to eliminate ambiguities as much as you can. In your case here, the namespace_prefix production that can be at the beginning of both type_selector and universal can be pulled out in front as a separate optional production:
simple_selector = [ namespace_prefix ]? (type_selector | universal);
type_selector = element_name;
namespace_prefix = [ IDENT | '*' ]? '|';
element_name = IDENT;
universal =  '*';

Not all grammars can be simplified for simple look-ahead like this, though, and for those you can use more complicated shift-reduce parsers, or - as you suggest - backtracking. For backtracking, you usually just attempt to parse productions and record the path through the grammar. Once you have a production that matches the input you use the recorded path to actually perform the semantic action for that production.