text:
Q: has_many :through with class_name and foreign_key not working i need to create parental relation i.e child and parent relation within a customer model. For storing information about parent and child, i have created a join table i.e ParentalRelation.
My customer model is:
class Customer < ApplicationRecord
  has_many :parental_relations
  has_many :children, class_name: 'Customer', foreign_key: 'child_id', through: :parental_relations
  has_one :parent, foreign_key: 'parent_id', class_name: 'Customer', through: :parental_relations, source: :parent
end

My parental_relation model is:
class ParentalRelation < ApplicationRecord
  belongs_to :parent, class_name: 'Customer'
  belongs_to :child, class_name: 'Customer'
end

I am trying to get data by:
Customer.first.children

But i am not getting data. getting like this even when there is data:

Customer::ActiveRecord_Associations_CollectionProxy:0x3fe49a819750

It would be really great help if anybody could help me out. Thank you in advance

A: if parent_relation has column parent_id and child_id
I believe it should be
class Customer < ApplicationRecord
  has_many :children_relations, class_name: 'ParentalRelation', foreign_key: 'parent_id'
  has_many :children, class_name: 'Customer', foreign_key: 'parent_id', through: :children_relations, source: :child

  has_one :parent_relation, class_name: 'ParentalRelation', foreign_key: 'child_id'
  has_one :parent, foreign_key: 'parent_id', class_name: 'Customer', through: :parent_relation, source: :parent
end

according to your relation, Rails will excute sql SELECT  "customers".* FROM "customers" INNER JOIN "parental_relations" ON "customers"."id" = "parental_relations"."child_id" WHERE "parental_relations"."customer_id" = $1 LIMIT $2
But I don't know your table struct. So you can read the sql in rails console and find out how Rails find records. It should help you to solve this problem.

A: Given you have customer has_one :parent in your model, it looks like you are trying to create a one-to-many relationship.  If this is correct, you don't need a join table.  You only need a join table if you are creating a many-to-many relationship.
To do this as a one-to-many, remove the ParentalRelation model and table and update your customer class to something like this:
class Customer < ApplicationRecord
  belongs_to parent, class_name: "Customer"
  has_many children, class_name: "Customer", foreign_key: :parent_id
end

Check out the guides here for creating a self joining table:
https://guides.rubyonrails.org/association_basics.html#self-joins
Once you have that, you should be able to do this:
Customer.first.children


text:
Q: Django: Show 'copy file progress notifications' on GUI web page I wanted to know if we can show 'progress notifications' on web GUI (template)? For example, I am copying contents of location X from my system(machine A) to location Y of another system(machine B). After that, I am executing a .exe file on the remote. So, I want to show the progress on my template as follows:
Copying files and folders from location X to location Y on machine B...
Copy completed.
Executing xyz.exe on machine B...
and so on.
I know there should be some way to do that, but am just not able to figure it out. It would help if someone can guide me in proper direction.
(An example to go along with this would be really helpful)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert 3D Obj file to adjacency matrix of a graph matrix I have a 3D OBJ file I would like to convert it to adjacency matrix of a graph. I know that adjancent matrix repersent if there is an edge between vertices, giving the OBJ file has faces indices, how would I convert it to adjacnet matrix ?
OBJ File gives
Vertices, and Faces as indices of triangles.
So I would like giving the vertices and faces information a graph like that:
gr2 = {
    1 : [2, 6],
    2: [1, 3],
    3: [2, 4, 7],
    4: [3, 5, 8, 9],
    5: [4, 6, 8],
    6: [1, 5, 9],
    7: [1, 3],
    8: [4, 5, 6],
    9: [3, 6]
}

A: so you want this?
cf = open("cube.obj")

vertices = []
faces = []

def valid(a):
    return a.strip() != ""

def spl(a, fn):
    return list(map(fn, filter(valid ,a.split(" "))))

for l in cf:
    if l[0] == "v":
        vertices.append(spl(l[2:], float))
    if l[0] == "f":
        faces.append(spl(l[2:], int))

graph = {}

for f in faces:
    for i in f:
        if not i in graph:
            graph[i] = set()
    graph[f[0]] |= set(f[1:])
    graph[f[1]] |= set([f[0],f[2]])
    graph[f[2]] |= set(f[:2])

for g in graph:
    print(g, ":", graph[g])


text:
Q: GraphQL WS server doesn't appear to be running I'm trying to get GraphQL Subscriptions working (without Apollo) using these libraries:
import { graphqlHTTP } from 'express-graphql';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';

I've been reading the source of these libraries and everything written online I can find and just can't get Graphiql to initiate the socket connection. It's probably a small configuration issue I'm missing - can you spot it?
BEHAVIOR:
When I open GraphiQL and attempt to create a subscription, I immediately get returned a null result and no connection is made in Chrome's Network > WS tab. The subscribe method doesn't get called but the resolve method does though payload is empty. 2 days trying to sort this out. Please help.
import http from "http";
import express from "express";
import { graphqlHTTP } from "express-graphql";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";

import graphQLSchema from "./graphql";

const { NODE_ENV } = process.env;
console.log(`NODE_ENV: ${NODE_ENV}`);

(async () => {
    /**
     * Setup Express
     */
    const app = express();

    /**
     * Setup GraphQL Server
     */
    const API_ENDPOINT = "/api";
    const PORT = 8080
    const ENABLE_GRAPHIQL = NODE_ENV !== "production";
    app.use(
        API_ENDPOINT,
        graphqlHTTP((req, res, graphQLParams) => {
            return {
                schema: graphQLSchema,
                graphiql: ENABLE_GRAPHIQL,
                context: { req, res },
            };
        })
    );

    const httpServer = http.createServer(app);

    const wsServer = new WebSocketServer({
        server: httpServer,
        path: API_ENDPOINT,
    });

    /**
     * Start Server
     */
    try {
        httpServer.listen(8080, () => {
            console.log(` GraphQL available at http://localhost:${PORT}${API_ENDPOINT}`);

            // create and use the websocket server
            useServer(
                { schema: graphQLSchema },
                wsServer
            );

            const wsAddress = wsServer.address();
            console.log(` WebSockets listening on ws://localhost:${wsAddress.port}${API_ENDPOINT}`);
        });
    } catch (error) {
        console.error(error);
    }
})();

Subscription: {
    invitationCreated: {
        resolve: payload => {
            console.log(payload);
            return payload;
        },
        subscribe: () => pubsub.asyncIterator('INVITATION_CREATED'),
    },
}

type Subscription {
    invitationCreated: Invitation
}

Result:
subscription invitationCreatedSub {
  invitationCreated {
      email
  }
}

# returns -->
{
  "data": {
    "invitationCreated": null
  }
}

EDIT
I found out you can do websockets in Postman which gives a little more insight:


text:
Q: Loading 3D model in iOS I'm creating a game application from scratch with xcode for iOS, and I've use the OpenGL Game projet template to create mine.
I've searched a lot in the past few days, but I can't find any tutorials or example as to how I would load 3D model (via .obj files) in my application. I've found some documentation on loading them onto an app with a console script, but I need to do it programmatically.
Any help would be very appreciated
Also, my 3D models are created using blender

A: The future will be here momentarily — SceneKit, available in OS X since v10.8, will be in iOS 8. It can build and render a scene with COLLADA (.DAE) models directly. No need for third-party tools or code, nothing complicated to learn.
Apple's documentation is pretty good but if you prefer then other tutorials are available.

A: OpensceneGraph has support for iOS and a lot of prebuilt code which can help you develop the game. It supports loading OBJ models.

A: I recommend to use an Engine (like isgl3d, nineveh, Cocos3D, ...) for creating a 3D game, it will be hard if you use Opengl for a start.
Note: you can search for a list of game engine to choose the suitable one for you game, cause there is a lot of game engine, open-source or paid engine.

A: You can download the zip file from here and then run ./obj2opengl.pl 3DModel.obj in terminal .It will give you 3DModel.h file as output.
You need to use glDrawArrays  instead of glDrawElements as the .h file contains array.

A: Obj files are simple to parse and are well described on wikipedia. You should be able to load them in one or 2 hours. But if you want to load the materials you need to invest some more time in your engine and into loading the obj file.


text:
Q: Installation Zabbix I am trying to install a Zabbix monitoring system on my Ubuntu. But when I try to install it. I get this error:
The following have unmet dependencies:
 zabbix-server-mysql : Depends: libsnmp15 (>= 5.4.3~dfsg) but it is no installable
                       Reccomends snmptt but it is not going to be installed
Unable to correct problems, you have held broken packages.

I already tried:
apt-get update -f
apt-get install snmpd -f

but nothing seems to work, anyone has a solution for me?
Thanks

A: Starting from a stock Ubuntu 12.04.3 LTS install, Zabbix can be installed in the following way:
From the Zabbix 2.2 documentation:
wget http://repo.zabbix.com/zabbix/2.2/ubuntu/pool/main/z/zabbix-release/zabbix-release_2.2-1+precise_all.deb
dpkg -i zabbix-release_2.2-1+precise_all.deb
apt-get update

then, to install the server and web frontend:
apt-get install zabbix-server-mysql zabbix-frontend-php

to install the Zabbix agent only:
apt-get install zabbix-agent

A: at first delete zabbix.list
sudo rm /etc/apt/sources.list.d/zabbix.list

and then run commands from in documentation (Answer Y or I when you run dpkg -i .....):
# wget http://repo.zabbix.com/zabbix/2.2/ubuntu/pool/main/z/zabbix-release/zabbix-release_2.2-1+precise_all.deb
# sudo dpkg -i zabbix-release_2.2-1+precise_all.deb
# sudo apt-get update


text:
Q: Hyperledger Composer Rest Server Query from WebApp i am developing a front end application using html and javascript for interaction with locally deployed hyperledger composer rest server. I have been able to use Get method to list all the assets that have been already created. But now i am trying to use a search query for a specific asset. And i have created a separate file for testing purposes for that query.
This is the code thus far.

            Enter Number
            <input type="text" id="txtNumber" />

    <input type="button" id="btnGetCheque" value="Get Cheque Data">

But it produces following error.
It produces this dialog box on browser
And there is nothing on console log, it is empty.
EDIT
This is the business model file
namespace org.acme.chequebook

asset Cheque identified by chequeNumber {

o String chequeNumber

}

And this is the query.qy file
 query ChequeByNumber {
   description: "Returns a cheque in the registry"
   statement:
      SELECT  org.acme.chequebook.Cheque
      WHERE   (chequeNumber == _$Cheque_Number)
  }
query AllCheques {
   description: "Returns all cheques in the registry"
   statement:
      SELECT  org.acme.chequebook.Cheque
 }

This is api url if i search a specific cheque from rest api
http://localhost:3000/api/queries/ChequeByNumber?Cheque_Number=12345

A: It's working with Cheque_Number , user tested it by changing datatype and then changing it back to json and now it's working fine.


text:
Q: Puma server inside heroku container fails to connect to port I have a docker container: (called Dockerfile.web, relevant parts)
ARG PORT=3000
ENV PORT=$PORT

EXPOSE $PORT

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["rails", "server"]

Puma: config/puma.rb
before_fork do
  ActiveRecord::Base.connection_pool.disconnect! if defined? ActiveRecord
end

on_worker_boot do
  ActiveRecord::Base.establish_connection if defined? ActiveRecord
end

preload_app!

So when I run heroku container:push web followed by heroku container:release web, the app deploys, but the puma server doesn't come up b/c the port cannot be connected to:
Booting Puma
Rails 5.2.2 application starting in development
Run `rails server -h` for more startup options
 Puma starting in cluster mode...
 * Version 3.12.0 (ruby 2.6.0-p0), codename: Llamas in Pajamas
 * Min threads: 5, max threads: 5
 * Environment: development
 * Process workers: 1
 * Preloading application
 * Listening on tcp://localhost:41626
 Use Ctrl-C to stop
 - Worker 0 (pid: 28) booted, phase: 0
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Stopping process with SIGKILL

I'm following the official guide but I haven't added the sections:
rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

Where could my error be? Any ideas?

A: I'm not sure why you left this part out:
port        ENV['PORT']     || 3000

You can't pick your own port. Use the $PORT that Heroku gives you.

A: For people arriving here, the solution was to invoke the puma server directly from the docker CMD so that all the settings in the config file are applied. The reason is that on heroku, stuff like port is added dynamically, so container images (which are built out earlier) will not have those images. Somehow using the $PORT values inside Dockerfile also did not help. The solution was to do
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]

# or if you prefer the bash style
CMD bundle exec puma -C config/puma.rb


text:
Q: Use SimpleXML to grab nested code
Possible Duplicate:
php simplexml issue in reading an attribute that has a 'column - : ' in its name

I'm in the process of learning PHP, so I'm making a weather app to display an image based on the weather. I'm using the Yahoo Weather API.
My problem is that I'm looking for a way to grab the code of the weather, located next to yweather:condition . I found simpleXML but can't figure out how to grab something that's located in something like the way Yahoo does its xml in the form of
<yweather:condition text="Fair" code="34" temp="37"

So my question is how can I grab the code="34" portion of the Yahoo weather and display it as a variable like $weathercode = 34;?
Thanks for any and all help, and I'm here to give more details if you need them!
Also, I'm not sure if the title of this post is correct, so sorry if it's not!

A: You can use the SimpleXMLElement::attributes call in a similar way to below.
$string = {Yahoo Weather Feed}

$xml = simplexml_load_string($string);

$weathercode = $xml->channel->item->children('yweather', true)->condition[0]->attributes()->code;

You may need to tinker to get it right, but this is just a guide.
Reference: http://php.net/manual/en/simplexmlelement.attributes.php

A: You could try the following:
$xml = simplexml_load_file('http://weather.yahooapis.com/forecastrss?w=12793465&u=f');
var_dump($xml);

This will load the URL and dump the SimpleXML object.
More on simplexml_load_file here


text:
Q: navigateToSObject is not defined I'm trying to figure out why navigateToSObject is coming back undefined. I'm new to Lightning so I'm sure it is something simple I'm missing.
The debug showed $A returning SecureAura: [object Object]{ key: {"namespace":"c"} }
I'm calling the method from the component here:
<button class="slds-button slds-button--brand" onclick="{!c.gotoContact}">Go To Contact</button>
},
gotoContact: function(cmp, event, helper) {
    var action = cmp.get('c.getContact');
    action.setParams({ guid : cmp.get("v.guid") });
    action.setCallback(this, function(response) {
        var state = response.getState();
        if(state == "SUCCESS") {
            var sobjectEvent = $A.get("e.force:navigateToSObject");
            sObjectEvent.setParams({
                "recordId": response.getReturnValue(),
                "slideDevName": "detail"
            });
            sObjectEvent.fire();
        }
    });
    $A.enqueueAction(action);
},

A: Rolling up comment as answer:
As per your original post, you had declared the event variable within the if block and you were using it outside the scope and thus you were getting undefined variable error.
if(state == "SUCCESS") {
        var sobjectEvent = $A.get("e.force:navigateToSObject"); // declared here
        sObjectEvent.setParams({
            "recordId": response.getReturnValue(),
            "slideDevName": "detail"
        });

    }
});
$A.enqueueAction(action);
sObjectEvent.fire();  // used here and thus error

Later when you moved it to the if block, it was case sensitivity which was not working.
if(state == "SUCCESS") {
        var sobjectEvent = $A.get("e.force:navigateToSObject");
        sObjectEvent.setParams({
            "recordId": response.getReturnValue(),
            "slideDevName": "detail"
        });
        sObjectEvent.fire(); // it was case sensitivity this time, declaration needed to be changed to sObjectEvent (notice the upper O)
    }
});
$A.enqueueAction(action);

Finally, changing the variable name to sObjectEvent and using it within the block where declared resolved the issue.


text:
Q: Do I need to import members of a singleton object into its companion class in Scala? The Good Book states that:

A class and its companion object can access each other's private members.

Perhaps naively, I took this as meaning that a class didn't need to explicitly import the members from its companion object. I.e., the following would work:
object Foo {
  def bar = 4
 }

class Foo {
 def foo = bar
}

Well, the reason you're reading this is that it doesn't. So do I really need to declare something like this:
class Foo {
  import Foo._

  def foo = bar
}

A: "Can access private members" means that the following works:
object Foo {
  private def bar = 4
}

class Foo {
  def foo = Foo.bar
}

A: Yes (and I want my 15 points for that!)
But to expand, their scopes do not overlap, so the import is necessary.

A: Yes, you do, just as you state. There's access, and there's scope -- what companion class/objects have is access, not scope.
It's like declaring something public vs private -- it doesn't bring those members into everyone's scope, just give them access to it.


text:
Q: Alternative of swapping out sticky nav bar for 60 FPS performance with scrollTop? I got a requirement that our sticky bar has to swap to be another bar if user scrolls down to a certain point. I have the working code but when I look at the performance it's quite slow. I use Chrome Dev Tool sometime it goes beyond 30 FPS which causes sluggishness on scrolling.
Here's the code I was wondering how do I code this and not use scrollTop to keep checking the position of the scroll bar for better performance?
I already use debounce to reduce the number of events being fired but still seeing some performance impact.
if ( this.dom.singleTitle.length ) { // this is to check if the element is present on the page
    this.dom.window.on('scroll', $.proxy( debounce( this.toggleNav, 50 ), this ) )
}

    toggleNav: function() {

        var screenTop = this.dom.document.scrollTop();
        if ( screenTop > this.dom.singleTitle.offset().top + 50 ) {
            if ( this.dom.mainNav.hasClass('expanded') ) {
                this.dom.mainNav.removeClass('expanded');
                this.dom.toggleTopbar.toggleClass('icon-menu icon-close');
                this.dom.body.removeClass('disable');
            }
            this.dom.headerShare.fadeIn(600);
        }
        else {
            this.dom.headerShare.fadeOut(600);
        }
    }

A: Try to use CSS3 if possible and only jQuery as a fallback.
CSS3 animations are much more smooth. Instead of using scrollTop use the transformation translate3d and you'll notice the difference.
To see if css3 is supported or not, you could check this solution.
Also, try avoiding things such as fadeIn or fadeOut and the use of shadows or borders with radius.
Needles to say, images should be optimized in weight and size for a better performance when animating them.


text:
Q: Include JavaScript file in another JavaScript file on a local drive I have seen many ways to include a JS file in another JS file, but all of them seem to require the files to be located on a server, as opposed to on the local drive. Is there any way to include a JS file in another while keeping all files on the local drive?

A: In the html file, add 2 script tags, with the src property of the top one being to one you want to include in the other
<script src="include.js"></script>
<script src="code.js"></script>


text:
Q: _tkinter.TclError: image "pyimage3" doesn't exist I need to display an image but the terminal always returns :
TclError: image "pyimage3" doesn't exist
I don't understand why because at the beginning it worked but when I modified other elements (without modifying my image) it started to bug.
fenetre = Tk()
fenetre.title("Cookie Game.py")
fenetre.geometry("650x550")
global_color = equ()
color_b, color_f  = global_color[0],global_color[1]
fenetre.minsize(625,525)
fenetre.config(background = color_b)

...

box_centre = Frame(fenetre, bg=color_b)
box1 = Frame(box_centre, bg= color_b)

txt_1 = Label(box1, text="Cookie Game", font=("Courier New",50), bg=color_b, fg="white")
txt_1.pack() #side =LEFT / =RIGHT /  =BOTTOM / =TOP

your_gold = Entry(box1, font=("Helvetica Neu",25), bg=color_b, fg="#F7B719",bd=0,highlightthickness=0)
your_gold.pack()
box1.pack(side=TOP)

#image
larg = 300 #largeur img
haut =  300 #hauteur img
img = PhotoImage(file="cookie_1.png").zoom(50).subsample(100)
canvas = Canvas(box_centre, height=haut, width=larg, bg=color_b, bd=0, highlightthickness=0)

canvas.create_image(larg/2, haut/2, image=img)     # <-- line error

canvas.pack(pady = 25)
box_centre.grid(row=0, column=1,sticky=W)

Thank you in advance for your answers.

A: tkinter uses tcl different interpreters for each Tk() window. Each interpreter has its own memory. All of the children of the window are managed by the same tcl interpreter. When you don't pass in the master parameter tkinter uses the first created tcl interpreter.
Consider this example:
import tkinter as tk

root_1 = tk.Tk() # Note this is the default root now
root_2 = tk.Tk()

label_1 = tk.Label(text="Hi") # By default `master=root_1`
label_1.pack()

tk_img = tk.PhotoImage(file="...") # By default `master=root_1`
label_2 = tk.Label(root_2, image=tk_img) # We are trying to use something that doesn't exist in this tcl interpreter.
label_2.pack()

Note that we haven't passed in a master for label_1 and tk_img. The first argument of tkinter widgets are usually the master so for label_2 the master is root_2.
Tkinter can't create a widget without a master as the widget must live in a tcl interpreter so it tries to guess which tcl interpreter it should use (always the first one that has been created). Therefore, the master for label_1 and tk_img will be root_1. So when we tell the second interpreter that we want it to use the variable tk_img (on this line label_2 = tk.Label(root_2, image=tk_img)), it fails as the second interpreter (for the second window) doesn't know about the other interpreter.


text:
Q: Neo4j Creating a relationship conditionally based on one of the property of node I need to create two different type of relationship between two nodes. Type of relationship depends upon one of the property of the node.
For Example,
I have two nodes USER and EVENT. I have two relationships to create between them.
 1. invite
 2. requestToInvite
Even node has property inviteOnly.
Create a "Invite" relationship if inviteOnly is true. Otherwise create "requestToInvite" relationship.
This is what i am trying:
MATCH (u:User)
WHERE ID(u) = 13
WITH u
MATCH (e:Events)
WHERE ID(e) = 0
WITH u,e
CREATE (u)-[:inviteONLYTrue]->(e) WHERE e.inviteOnly = true
CREATE (u)-[:inviteONLYFALSE]->(e) WHERE e.inviteOnly = false
WITH u,e
RETURN u,e

A: Currently there is no conditional but you can work around it by iterating over a zero or one-element list which is created by a CASE statement.
MATCH (u:User) WHERE ID(u) = 13
MATCH (e:Events) WHERE ID(e) = 0
FOREACH (_ in case e.inviteOnly when true then [1] else [] end |
  CREATE (u)-[:inviteONLYTrue]->(e) )
FOREACH (_ in case e.inviteOnly when false then [1] else [] end |
  CREATE (u)-[:inviteONLYFALSE]->(e) )
RETURN u,e

A: APOC Procedures just updated with support for conditional cypher execution, but in this particular case all you'll need is a way to create a relationship with a dynamic relationship type. APOC has a procedure for this too. Here's an example:
MATCH (u:User)
WHERE ID(u) = 13
WITH u
MATCH (e:Events)
WHERE ID(e) = 0
WITH u,e, CASE WHEN e.inviteOnly THEN 'inviteONLYTrue' ELSE 'inviteONLYFALSE' END as relType
CALL apoc.create.relationship(u, relType, {}, e) YIELD rel
RETURN u,e


text:
Q: Printing an Array of Staff objects with a toString I'm having trouble printing out an array of StaffMember objects by utilizing the defined toString method with my driver.  I keep getting a cannot find symbol error and I'm confused as to what I need to replace the staffList with in my driver to make things work out.
This is the part of the question I'm stuck on "Your program should first print all the staff members (use toString() method of the StaffMember class) to the terminal window"
Here is my code (the Staff and StaffMember classes are from the textbook and were not required to be changed for the assignment, so all problems are with my driver).
public class Staff
{
  private StaffMember[] staffList;

  public Staff ()
  {
    staffList = new StaffMember[6];

    staffList[0] = new Executive ("Sam", "123 Main Line",
    "555-0469", "123-45-6789", 2423.07);

    staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
    "987-65-4321", 1246.15);

    staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
    "010-20-3040", 1169.23);

    staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
    "555-0690", "958-47-3625", 10.55);

    staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
    "555-8374");

    staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
    "555-7282");

    ((Executive)staffList[0]).awardBonus (500.00);

    ((Hourly)staffList[3]).addHours (40);
  }

    public void payday ()
    {
      double amount;

      for (int count=0; count < staffList.length; count++)
      {
        System.out.println (staffList[count]);
        amount = staffList[count].pay();

        if (amount == 0.0)
          System.out.println ("Thanks!");
        else
          System.out.println ("Paid: " + amount);
        System.out.println ("-----------------------------------");
      }
    }
 }

This is the abstract class:
abstract public class StaffMember
{
  protected String name;
  protected String address;
  protected String phone;
//-----------------------------------------------------------------
// Constructor: Sets up this staff member using the specified
// information.
//-----------------------------------------------------------------
  public StaffMember (String eName, String eAddress, String ePhone)
  {
    name = eName;
    address = eAddress;
    phone = ePhone;
  }
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
  public String toString()
  {
    String result = "Name: " + name + "\n";
    result += "Address: " + address + "\n";
    result += "Phone: " + phone;
    return result;
  }
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
  public abstract double pay();
}

And this is what I've gotten for a driver so far:
import java.util.*;
public class EmployeeBinaryList
{
  public static void main (String args[])
  {
    for (int i = 0; i < staffList.length; i++)
    System.out.println(staffList[i].toString());
  }
}

I've tried various things in place of the staffList and staffList[i], but I just can't seem to figure it out.  Thanks a ton to anyone who can help me

A: you need to think about scope here. A variables scope is where that variable can be accessed. The easiest way to know the scope of a variable is by the curly braces. a variable is only accessible directly within the braces where it was defined. So, staffList is defined in the staff class, as such it is only accessible directly in the staff class.
you would have to access that variable through an object of the staff class:
System.out.println(StaffObject.StaffList) //StaffObject would be an object of the Staff class
however, in this case you also need to look at whether the variable is public or private. Private means it can not be accessed directly outside of its class. so in this case StaffObject.staffList would not be accessible outside of the Staff class
In order to access that StaffList variable you need what's called an Accessor method. A method which is public, and allows access to the variable for printing purposes.
so, here's whatcha gotta do:
First off you need an object of the staff class
Then, you need to use that object to access the appropriate Accessor method for printing
take a good look at the code, chances are its all there for a reason.
good luck!!

A: package com.cisco.staff;

public class Staff
{
  private StaffMember[] staffList;
public Staff ()
  {
    staffList = new StaffMember[6];
staffList[0] = new Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 2423.07);

staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
"987-65-4321", 1246.15);

staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 1169.23);

staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 10.55);

staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");

staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");

/* ((Executive)staffList[0]).awardBonus (500.00);
((Hourly)staffList[3]).addHours (40);*/

}
public void payday ()
{
  double amount;

  for (int count=0; count < staffList.length; count++)
  {
    System.out.println (staffList[count]);
    amount = staffList[count].pay();

    if (amount == 0.0)
      System.out.println ("Thanks!");
    else
      System.out.println ("Paid: " + amount);
    System.out.println ("-----------------------------------");
  }
}

public StaffMember[] getStaffList() {
    return staffList;
}

public void setStaffList(StaffMember[] staffList) {
    this.staffList = staffList;
}

}

package com.cisco.staff;

abstract public class StaffMember
  {
   protected String name;
   protected String address;
   protected String phone;
//-----------------------------------------------------------------
  // Constructor: Sets up this staff member using the specified
  // information.
  //-----------------------------------------------------------------
  public StaffMember (String eName, String eAddress, String ePhone)
  {
    name = eName;
    address = eAddress;
    phone = ePhone;
  }
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
  public String toString()
  {
    String result = "Name: " + name + "\n";
    result += "Address: " + address + "\n";
    result += "Phone: " + phone;
    return result;
  }
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
  public abstract double pay();
}
package com.cisco.staff;

import java.util.List;
public class EmployeeBinaryList
{
  public static void main (String args[])
  {
      Staff staff = new Staff();
      StaffMember[] staffList = staff.getStaffList();
    for (int i = 0; i < staffList.length; i++)
    System.out.println(staffList[i].toString());
  }
}
package com.cisco.staff;

public class Executive extends StaffMember {
      protected String somestrString;
      protected double somelong;
public Executive(String eName, String eAddress, String ePhone, String someString , double pay) {
    super(eName, eAddress, ePhone);
    this.somestrString= someString;
    this.somelong=pay;
    // TODO Auto-generated constructor stub
}

@Override
public double pay() {
    // TODO Auto-generated method stub
    return 0;
}

}
package com.cisco.staff;

public class Volunteer extends StaffMember {
      protected String somestrString;
      protected double somelong;
public Volunteer(String name, String address, String phone) {
    super(name, address, phone);
    // TODO Auto-generated constructor stub
}

@Override
public double pay() {
    // TODO Auto-generated method stub
    return 0;
}

}
package com.cisco.staff;

public class Employee extends StaffMember {
  protected String somestrString;
  protected double somelong;

public Employee(String name, String address, String phone,
        String somestrString, double somelong) {
    super(name, address, phone);
    this.somestrString=somestrString;
    this.somelong=somelong;

}

@Override
public double pay() {
    // TODO Auto-generated method stub
    return 0;
}

}
package com.cisco.staff;

 public class Hourly extends StaffMember {
  protected String somestrString;
  protected double hourly;

public Hourly(String eName, String eAddress, String ePhone, String somString, double hourly) {
    super(eName, eAddress, ePhone);
    this.somestrString=somString;
    this.hourly=hourly;
    // TODO Auto-generated constructor stub
}

@Override
public double pay() {
    // TODO Auto-generated method stub
    return 0;
}

}


text:
Q: Multiplication of series Suppose $a_n\geq0$ and $\sum a_n$ is convergent. Show that $ \sum 1/(n^2\cdot a_n)$ is divergent.
I haven't been able to get any result from any of my approaches (which include the general tests for positive series). However if I were to create $\sum b_n$ such that the terms are in the same order as in $\sum a_n$ except the terms for which $a_n=0$ have been omitted, then of course I would be able to solve it. But would this approach be correct.
I was also wondering whether some result related to p test could be used.
Or, if you have a better approach please do share it

A: I think that you have to suppose that $a_n>0$ for all $n$, otherwise your second series does not exist. With this hypothesis, put $u_n=a_n$, $\displaystyle v_n=\frac{1}{n^2 a_n}$, and use the inequality $2\sqrt{u_nv_n}\leq u_n+v_n$.

A: Assuming $a_n\ne 0$:
If $\sum\limits_{n=1}^{\infty}{\frac{1}{n^2a_n}}<\infty$, then by Cauchy-Schwarz we would have
$$\left(\sum\limits_{n=1}^{\infty}{\frac{1}{n}}\right)^2 = \left(\sum\limits_{n=1}^{\infty}{\sqrt{a_n}\frac{1}{n\sqrt{a_n}}}\right)^2 \le \sum\limits_{n=1}^{\infty}{a_n}\sum\limits_{n=1}^{\infty}{\frac{1}{n^2a_n}}<\infty,$$
contradiction.


text:
Q: How to get the last inserted item from dynamodb, after that create new item using Aws appsync I am using aws appsync and dynomoDB. I have a table called Payment and I want to create each item with an unique sequential number that is PaymentNo.
If we want to achive this, we have to get last inserted item in order to update the PaymentNO count. Actually, I don't know, "how to get the last inserted item from table in the same resolver?
could anyone help me to write a resolver for this ?
schema
type Payment @model(subscriptions: null) {
    id: ID!
    paid_amount: Float
    paid_date: AWSDate
    description: String
    PaymentNO: Int
}

My request resolver
## [Start] Set default values. **
$util.qr($context.args.input.put("id", $util.defaultIfNull($ctx.args.input.id, $util.autoId())))
#set( $createdAt = $util.time.nowISO8601() )

## Automatically set the createdAt timestamp. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $createdAt)))

## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $createdAt)))
## [End] Set default values. **

## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("__typename", "FeePayment"))
#if( $modelObjectKey )
  #set( $condition = {
  "expression": "",
  "expressionNames": {},
  "expressionValues": {}
} )
  #foreach( $entry in $modelObjectKey.entrySet() )
    #if( $velocityCount == 1 )
      $util.qr($condition.put("expression", "attribute_not_exists(#keyCondition$velocityCount)"))
    #else
      $util.qr($condition.put("expression", "$condition.expression AND attribute_not_exists(#keyCondition$velocityCount)"))
    #end
    $util.qr($condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key"))
  #end
#else
  #set( $condition = {
  "expression": "attribute_not_exists(#id)",
  "expressionNames": {
      "#id": "id"
  },
  "expressionValues": {}
} )
#end
#if( $context.args.condition )
  #set( $condition.expressionValues = {} )
  #set( $conditionFilterExpressions = $util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition)) )
  $util.qr($condition.put("expression", "($condition.expression) AND $conditionFilterExpressions.expression"))
  $util.qr($condition.expressionNames.putAll($conditionFilterExpressions.expressionNames))
  $util.qr($condition.expressionValues.putAll($conditionFilterExpressions.expressionValues))
#end
#if( $condition.expressionValues && $condition.expressionValues.size() == 0 )
  #set( $condition = {
  "expression": $condition.expression,
  "expressionNames": $condition.expressionNames
} )
#end
{
  "version": "2018-05-29",
  "operation": "PutItem",
  "key": #if( $modelObjectKey ) $util.toJson($modelObjectKey) #else {
  "id":   $util.dynamodb.toDynamoDBJson($ctx.args.input.id)
} #end,
  "attributeValues": $util.dynamodb.toMapValuesJson($context.args.input),
  "condition": $util.toJson($condition)
}
## [End] Prepare DynamoDB PutItem Request. **

response resolver
#if( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type)
#else
$util.toJson($ctx.result)
#end


text:
Q: Why's my solution wrong for reversing an integer? I need to reverse an integer, in this case, 123 should come out to 321.  I'm converting the int to string, reversing the string, converting it back to an int, and then returning it but some how I'm getting the error.
What's a good way to solve this problem?
Here's my code:
public static int solution(int x) {
    String s = Integer.toString(x);
    String result = " ";
    int ans = 0;

    for(int i = s.length() - 1; i >= 0; i--) {
        result += s.charAt(i);
    }

    ans = Integer.parseInt(result);

    return ans;
}

public static void main(String args[]) {
    int x = 123;

    System.out.print(solution(x))
}

Here's my error:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 321"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Node.solution(Node.java:28)
at Node.main(Node.java:47)

A: Do not add a white space at the beginning:
String result = " ";

Use empty string
String result = "";

And, not related to the question, you can also achieve it by this:
int x = 123;
StringBuilder stringBuilder = new StringBuilder(x);
int y = Integer.parseInt(stringBuilder.reverse().toString());

A: There is no need in redundant conversions to string and vice versa.
Python code (note leading zero eliminating):
def rev(x):
    res = 0
    while (x > 0):
        res = res * 10 + x % 10
        x  = x // 10
    return res

print(rev(9801), rev(120))
>>> 1089 21


text:
Q: What is the use of the "Partition" keyword in MySQL? As I am a MySQL newbie. What does PARTITION mean in this MySQL statement?
CREATE TABLE employees (
    id INT NOT NULL,
    fname VARCHAR(30),
    lname VARCHAR(30),
    hired DATE NOT NULL DEFAULT '1970-01-01',
    separated DATE NOT NULL DEFAULT '9999-12-31',
    job_code INT NOT NULL,
    store_id INT NOT NULL
)
PARTITION BY RANGE (store_id) (
    PARTITION p0 VALUES LESS THAN (6),
    PARTITION p1 VALUES LESS THAN (11),
    PARTITION p2 VALUES LESS THAN (16),
    PARTITION p3 VALUES LESS THAN (21)
);

A:
Partitioning is a way of
  pre-organizing table storage. You can
  say "some of the table's rows will go
  here, some will go there, still others
  will go to to still other places".
  Often, depending on the storage
  engine, the effect is to spread the
  table's rows over different files or
  even different disks.

From: MySQL 5.1 New Features: MySQL Partitions

You may also be interested in seeking further information on "horizontal partitioning", in order to better understand the scenarios where this is particularly useful.

A: Partitioning helps in organize the data stored in the table by splitting across different buckets.
This is analogous to how a library has separate sections of shelves for different subjects, while the catalogue/index card drawers are usually separated alphabetically.
This helps in two ways:

*

*It is easier to manage the physical storage using partitioning. For instance, one strategy could be to have separate disks for each partition's storage. This usually helps spread the data in a balanced manner across multiple physical disks.

*The database can optimize the retrieval and delivery of the data by identifying limited partitions that need to be retrieved. Partitioning is usually done keeping in mind the physical storage characteristics. Thus, even while retrieving, the database engine will typically need to read only from a specific partition and so can read entire blocks of data from the physical storage.

Here are a few links where you can get many more details:
Wikipedia article: http://en.wikipedia.org/wiki/Partition_(database)
MySQL documentation regarding partitions: http://dev.mysql.com/doc/refman/5.5/en/partitioning.html


text:
Q: PHP: How to add database result (string) as array (using explode) to null array elements in sequence I would like to generate a multidimensional array as follows:
$arrayTwo = [
[ 'This','array','needs','to','be','filled'],
['This','cat','needs','to','be','filled'],
[ 'This','cat','needs','to','get','eaten'],
[ 'This','array','needs','to','get','eaten'],
[ 'This','array','needs','to','count','sheep']
];

I have created code which fills in the blanks using the top result from a database search, based on length and then filtered by google-results, then bing-results, then yahoo-results. However, this means if I have an array which contains multiple instances of two consecutive NULL members, then it will fill them with the same word pair every time. This would not be an issue for the first time $arrayOne is entered into $arrayTwo, as it is a valid response, but if I create a loop then I want the next formulation of $arrayOne to contain the selection of word groups which has the next highest values in the google-/bing-/yahoo-results sections.

Database:
|column 1   |length |google-results |bing-results   |yahoo-results  |
|array      |1      |1213253        |3456365        |253645         |
|be filled  |2      |5463656        |4255665        |424535         |
|cat        |1      |4564747        |9678744        |345636         |
|get eaten  |2      |4543636        |5356456        |424253         |
|count sheep|2      |4355665        |5645647        |476578         |
|umbrella   |1      |6973435        |5356356        |346476         |

HTML
$arrayOne = [0=> 'This',1=> ,2=> 'needs',3=> 'to',4=> ,5=> ];
$arrayTwo = [];

array_unshift($arrayOne, 'Suggestion:');

for($i=0;$i<count($arrayOne);$i++) {
    if($arrayOne[$i] == NULL) {
        if($arrayOne[$i-1] != NULL) {
            $counter = 1;
            for($x=$i+1;$x<count($arrayOne);$x++) {

                if($arrayOne[$x] == NULL && $arrayOne[$x-1] == NULL) {

                    $counter++;
                }

                elseif($arrayOne[$x] != NULL && $arrayOne[$x-1] == NULL) {

                    $queryBlank = "SELECT * FROM table_name WHERE length = ".$counter." ORDER BY `google-results` DESC, `bing-results` DESC, `yahoo-results` DESC";
                    $resultBlank = mysqli_query($conn,$queryBlank);

                    if($row = mysqli_fetch_assoc($resultBlank)) {

                        $blank = explode(' ', $row['column 1']);

                        foreach($blank as $key => $value) {

                            $arrayOne[$i+$key] = $value;
                        }
                    }
                }
            }
            array_push($arrayTwo, $arrayOne);
        }
    }
}

A: I don't know my result is exactly with your mind or not
But I tried my best xD
$arrayOne = [0=> 'This',1=> '',2=> 'needs',3=> 'to',4=> '',5=> ''];
$arrayTwo = [];
$arrayThree = [];

for($i=0;$i<count($arrayOne);$i++) {
    if($arrayOne[$i] == NULL) {
        if(isset($arrayOne[$i+1]) && $arrayOne[$i+1] != NULL){
            $counter = 1;
            $queryBlank = "SELECT * FROM table_name WHERE length = ".$counter." ORDER BY `google-results` ASC, `bing-results` ASC, `yahoo-results` ASC";
            $resultBlank = mysqli_query($conn,$queryBlank);
            while($row = mysqli_fetch_array($resultBlank)) {
                // echo $row['column 1'];
                $blank = explode(' ', $row['column 1']);
                $arrayTemp = array();
                foreach($blank as $key => $value) {
                    $arrayTemp[$i+$key] = $value;
                }
                array_push($arrayTwo, $arrayTemp);
            }
        }elseif(isset($arrayOne[$i+1]) && $arrayOne[$i+1] == NULL){
            // echo $i;
            $counter = 2;
            $queryBlank = "SELECT * FROM table_name WHERE length = ".$counter." ORDER BY `google-results` ASC, `bing-results` ASC, `yahoo-results` ASC";
            $resultBlank = mysqli_query($conn,$queryBlank);
            while($row = mysqli_fetch_array($resultBlank)) {
                // echo $row['column 1'];
                $blank = explode(' ', $row['column 1']);
                $arrayTemp = array();
                foreach($blank as $key => $value) {
                    $arrayTemp[$i+$key] = $value;
                }
                array_push($arrayThree, $arrayTemp);
            }
        }
    }
}
foreach ($arrayTwo as $key => $value) {
    $newArray = array_replace($arrayOne,$value);
    foreach ($arrayThree as $key2 => $value2) {
        print_r(array_replace($newArray,$value2));
        echo '<br>';
    }

}

And my result

Why count sheep is the best match. Please recheck your database it is 5645647 > be filled with 5463656
I'm not sure but you can set ASC or DESC with your mind.


text:
Q: How to change a formula when changing the axis? I have been lerning about acceleration and free fall recently, and we were told the formula for distance is $s=s_0+v_0t+\frac {1}{2}at^2$ (for movement along $x$-axis) but when we change the axis (to movement along $y$-axis) and describe the free fall equation it will now be like this $s=s_0+v_0t-\frac {1}{2}at^2$. My question is, if I have any formula for something (now generally, not talking about the example above, for any movement or anything) along the $x$-axis and I want to describe the movement (or anything else) along the $y$-axis, how do i know, when to change the + for - (or the quantify in this case $+g$ for $-g$)? Please explain for this case and also generally so that i can use the knowledge in the future when talking about different topics/problems.

A: The equation $x = x_0 + v_0t + 1/2 at^2$ is the general kinematic equation that describes motion under constant acceleration.  For motion in two or three dimensions, it is customary to use "x" for the horizontal direction, "y" for the vertical direction, and "z" for the "depth" direction.  Thus, if an object is falling straight down, with no horizontal or z-directed motion associated with it, the equation to describe this motion would normally be $y = y_0 + v_0t + 1/2at^2$, where "a" is the acceleration due to gravity.  Note that if "x" and "y" motion is occurring simultaneously (e.g., projectile motion), and equations of motion are being used to represent vector components, it is customary to use subscripts on the variables "v" and "a" to indicate which component variables are being described.
Regarding the direction of the motion, you are free to choose that direction at the start of the problem, and as long as you stay consistent in the sign designation, everything will work as it should.  For most problems, up will be designated as positive and down will be designated as negative.  Under this directional assignment, the acceleration due to gravity is negative, because it is in the negative direction.  On the other hand, some problems may work better if down is defined as the positive direction.  If that is the case, then the acceleration due to gravity is positive, and any motion in the upwards direction is negative.

A: Very generally, everything is a choice. We choose to favor one direction, or one sign, over the other. Often times, though, we will choose a convention that makes the most sense.
For example, it could make sense for the sign to be negative in the $y$-axis because it reminds us that the height of the object is decreasing with time. Conventionally, the positive direction of the $y$ axis is "up" and the negative direction is "down".
These choices eventually become the convention, and everyone agrees that that choice is the choice to use. It doesn't really matter which choice it is, so long that everyone is using it, consistiently. This is actually kind of weird because you already know a lot of conventions, but you've never even thought about it. Everyone knows that $x$ and $y$ are used as variables, while $a$, $b$, and $c$ are used as constants, and it just looks strange if you don't do it like that. Conventions are sometimes silent agreements that are hardly touched upon or "taught"; those are the ones that will almost never cause confusion.
Other times, the choice is in the hands of the teacher or author, for their own reasons. In these cases, you have to go and ask them what convention they are using (or read the "about this book" section). In your case, ask the teacher: "Hey, is this negative sign always going to be the case?" and make sure that you understand how they are choosing to express their equations or signs so that there are no misunderstandings.
Similarly, if you are talking about or teaching a topic and you're choosing to use some unnatural conventions, be sure to let others know, so you that they can understand you.
Ultimately, the universe doesn't care. The answers should be the same, regardless of which ones we choose.


text:
Q: Динамический прокси Вот мой код:
import java.lang.reflect.Proxy.*;
import java.util.Set;
import java.lang.reflect.*;
import java.util.*;

interface PersonBean {

    String getName();
    String getGender();
    String getInterests();
    int getHotOrNotRating();

    void setName(String name);
    void setGender(String gender);
    void setInterests(String interests);
    void setHotOrNotRating(int rating);
}

class OwnerInvocationHandler implements InvocationHandler {
    PersonBean person;

    public OwnerInvocationHandler(PersonBean person) {
        this.person = person;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws IllegalAccessException {

        try {
            if (method.getName().startsWith("get")) {
                return method.invoke(person, args);
               } else if (method.getName().equals("setHotOrNotRating")) {
                throw new IllegalAccessException();
            } else if (method.getName().startsWith("set")) {
                return method.invoke(person, args);
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

class NonOwnerInvocationHandler implements InvocationHandler {
    PersonBean person;

    public NonOwnerInvocationHandler(PersonBean person) {
        this.person = person;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws IllegalAccessException {

        try {
            if (method.getName().startsWith("get")) {
                return method.invoke(person, args);
               } else if (method.getName().equals("setHotOrNotRating")) {
                return method.invoke(person, args);
            } else if (method.getName().startsWith("set")) {
                throw new IllegalAccessException();
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

class PersonBeanImpl implements PersonBean {
    String name;
    String gender;
    String interests;
    int rating;
    int ratingCount = 0;

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

    public String getInterests() {
        return interests;
    }

    public int getHotOrNotRating() {
        if (ratingCount == 0) return 0;
        return (rating/ratingCount);
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setInterests(String interests) {
        this.interests = interests;
    }

    public void setHotOrNotRating(int rating) {
        ratingCount++;
    }
}

public class MatchMakingTestDrive {
    public Hashtable <String, PersonBean> datingDB = new Hashtable <String, PersonBean> ();
     String Name;
    String gender;
    String Interests;
    int HotOrNotRating;
public static void main(String[] args) {
        MatchMakingTestDrive test = new MatchMakingTestDrive();
        test.drive();
    }

    public void drive() {
        PersonBean joe = getPersonFromDatabase("Joe Javabean");
        PersonBean ownerProxy = getOwnerProxy(joe);
        System.out.println("Name is " + ownerProxy.getName());
        ownerProxy.setInterests("bowling, Go");
        System.out.println("Interests set from owner proxy");
        try {
            ownerProxy.setHotOrNotRating(10);
        } catch (Exception e) {
            System.out.println("Can't set rating from owner proxy");
        }
        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());

       PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
        System.out.println("Name is " + nonOwnerProxy.getName());
        try {
            nonOwnerProxy.setInterests("bowling, Go");
        } catch (Exception e) {
            System.out.println("Can't set interests from non owner proxy");
        }
        nonOwnerProxy.setHotOrNotRating(3);
        System.out.println("Rating set from non owner proxy");
        System.out.println("Rating is " + nonOwnerProxy.getHotOrNotRating());
    }

    PersonBean getOwnerProxy(PersonBean person) {

        return (PersonBean) java.lang.reflect.Proxy.newProxyInstance(
                person.getClass().getClassLoader(),
                person.getClass().getInterfaces(),
               new OwnerInvocationHandler(person));
    }

    PersonBean getNonOwnerProxy(PersonBean person) {

       return (PersonBean)java.lang.reflect. Proxy.newProxyInstance(
          person.getClass().getClassLoader(),
           person.getClass().getInterfaces(),
         new NonOwnerInvocationHandler(person));
    }

    PersonBean getPersonFromDatabase(String name) {
        return datingDB.get(name);
    }

    void initializeDatabase() {
        PersonBean joe = new PersonBeanImpl();
        joe.setName("Joe Javabean");
        joe.setInterests("cars, computers, music");
        joe.setHotOrNotRating(7);
        datingDB.put(joe.getName(), joe);

        PersonBean kelly = new PersonBeanImpl();
        kelly.setName("Kelly Klosure");
        kelly.setInterests("ebay, movies, music");
        kelly.setHotOrNotRating(6);
        datingDB.put(kelly.getName(), kelly);
    }
 }

После запуска программы мне выдает это:
Exception in thread "main" java.lang.NullPointerException
        at MatchMakingTestDrive.getOwnerProxy(MatchMakingTestDrive.java:150)
        at MatchMakingTestDrive.drive(MatchMakingTestDrive.java:125)
        at MatchMakingTestDrive.main(MatchMakingTestDrive.java:119)

A: Кажется, вы забыли проинициализировать (заполнить записями) datingDB. Добавьте строчку, помеченную восклицательными знаками, в метод main:
public static void main(String[] args) {
    MatchMakingTestDrive test = new MatchMakingTestDrive();
    test.initialize();  // !!
    test.drive();
}

getPersonFromDatabase() возвращает null, т.к. пользователь "Joe Javabean" не найден в БД. Тогда на строке person.getClass().getClassLoader() конечно же возникнет NPE.


text:
Q: Popping/Buzzing sound when pluging in speakers with external power I have these speakers (Genius SP-HF1250B) with power drawn from power socket and every time I am plugging them in, from the point when connector touches the jack input connector to the point of full insertion, it buzzes/pops very loud (same if I touch end of cable with finger). Could this damage those speakers and more importantly could this damage the PC?
If so, what would you suggest to prevent this from happening? If I turn off speakers by switch on the back of them before inserting and turn them back on after, the sound is obviously not there, but I am worried that some power "surge" is still there and could damage PC/speakers.
Also I plug it in/out every day because as far as I know there is no way to have connected headphones and speakers so they would both play (or alternatively ito have possibility to choose - for me always front jack plays if both inserted) at the same time right?
Thanks for any suggestions. :)

A: This is normal behavior. When you turn on the speaker, it will amplify electric signals that come through the jack, an "armed" speaker will therefor cause these sounds to be played on the speaker because the plus and minus on the cable will cause for imbalances.

from the point when connector touches the jack input connector to the point of full insertion, it buzzes/pops very loud (same if I touch end of cable with finger). Could this damage those speakers and more importantly could this damage the PC?

Yes, if you have the speaker turned on, it is possible to damage the speaker or the soundcard. It is unlikely but it can happen. This is basically true for any audio equipment.

If so, what would you suggest to prevent this from happening? If I turn off speakers by switch on the back of them before inserting and turn them back on after, the sound is obviously not there, but I am worried that some power "surge" is still there and could damage PC/speakers.

Exactly this. You turn off the speaker, then plug it in, then turn it on. That is the safe method to do it and that should not yield in any damage. If that does yield in damage, then you have a really cheap speaker that will break no matter what. No, a speaker and soundcard will normally withstand that.

Also I plug it in/out every day because as far as I know there is no way to have connected headphones and speakers so they would both play (or alternatively ito have possibility to choose - for me always front jack plays if both inserted) at the same time right?

That's fine. Note that the front jack with the headphones are not amplified and can be removed and inserted safely. But if it is that same jack you plug in the speakers too, then yes, the speakers need to be turned off. Usually there is also a jack on the back of your pc (laptops excluded, they only have one), and if you plug the speakers in the back, and the headphones in the front, on most systems the speakers are automatically muted.


text:
Q: Accessing xaml elements from code if I have their string name I have a code in wich i need to be able to access to a different amount of prebuilt grids in XAMl and make them visible or collapsed
All grid are named like grid1,grid2,grid3 etc. I have the ability in code to obtain the string name via a random number and get the name od the grid i'd like to show.
I searched online and people suggest to use the reflect method, but i'm having a hard time trying to figure out the syntax that i have to use.
Best regards

A: The most straight forward way of doing this is to just declare a Name value for each Grid...:
<Grid Name="Grid1">
    ...
</Grid>

... and then you can access them by that name from the code behind:
Grid1.Visibility = Visibility.Hidden;

However, this is WPF and that is generally not recommended. A preferred method would be to add some bool properties to your code behind or view model...:
public bool IsGrid1Visible { get; set; } // Implement INotifyPropertyChanged interface

... and then to bind these directly to the Grid1.Visibility property using a BooleanToVisibilityConverter:
<Grid Grid1.Visibility="{Binding IsGrid1Visible, Converter={StaticResource
    BooleanToVisibilityConverter}}">
    ...
</Grid>

Then you can change the Grid.Visibility value by simply setting the IsGrid1Visible property to true or false.


text:
Q: Not getting folders in Sharepoint list With Postman (standalone app) I try to get the folders from a SP Online list.
So
https://mydomain.sharepoint.com/sites/DocStorage/_api/lists/getbytitle('Demo')

properly returns the data of the list. However, getting its folders via
https://mydomain.sharepoint.com/sites/DocStorage/_api/lists/getbytitle('Demo')/RootFolder/Folders

returns an empty result:
{
  "d": {
    "results": []
}

Trying to access a folder in that list directly, such as:
https://mydomain.sharepoint.com/sites/DocStorage/_api/Web/GetFolderByServerRelativePath(decodedurl='/sites/DocStorage/Demo/aFolderName')

comes back with 403 Access denied.
I believe the two problems are related and it's most likely an authorization problem. However, there is a valid token sent along with above requests, and the client app is configured with fullControl rights on the SP online site:
Site.FullControl.All
So, I wonder why I'm able to access the list ('Demo') but not its folders.


text:
Q: How do you insert content to a custom status cel which contains a UITextField? I have two view controller that for adding my "Routines". One is to display a list of all routines and one to edit/create routines.
In the first view controller I have two way to enter to the second controller

*

*by selecting an already created routine

*by pressing the "+" button on the navigation bar

If the press option is pressed the data should be recalled from CoreData entity and the fields in the second view controller shall be populated.
But I get the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Would anyone know how to insert content to a custom status cell named "NameCell" which contains a UITextField?
Thanks in advance,
Ace

A: If you are using static cells in your table view in the storyboard, but want to populate data in one of them, one does not implement any of the UITableViewDataSource methods, but rather just create IBOutlet from the UILabel in question, and then you can populate it as you see fit.
class ViewController: UITableViewController {

    @IBOutlet weak var foo: UILabel!
    var bar: String!  // this is populated by `prepareForSegue` of presenting view controller

    override func viewDidLoad() {
        super.viewDidLoad()

        foo.text = bar
    }

}

As the Table View Programming Guide for iOS says:

Note: If a table view in a storyboard is static, the custom subclass of UITableViewController that contains the table view should not implement the data source protocol. Instead, the table view controller should use its viewDidLoad method to populate the table view's data. For more information, see Populating a Static Table View With Data.


text:
Q: Repetir 2 veces cada caracter de una palabra Se que parece muy simple, quizas lo sea.-
Tengo un string con la palbra "Hola" y necesito que me decuelva la palabra con cada caracter retepito dos veces. Ejemplo.- "Hhoollaa"
Probe con repeat
con split
for each,

A: Puedes utilizar un ciclo for que recorra cada carácter del String de entrada y cree un nuevo String de salida guardando cada carácter dos veces.
Código en Python:
def duplicar_caracteres(entrada):
string_duplicado = ''
for caracter in entrada:
    string_duplicado = string_duplicado + caracter + caracter
return string_duplicado

print(duplicar_caracteres('Hola'))

Ten en cuenta que el resultado va a ser "HHoollaa".


text:
Q: Why there is no iPad mini 3, opposite to iPad mini 2 on apple website? On the root site you can buy iPad mini 2 and iPad mini 4.

Why there is no iPad 3? Is there any reason for this? iPad mini 2 is better than 3?

A: On September 9, 2015, the iPad Mini 3 was discontinued and was replaced by the iPad Mini 4.


text:
Q: ${}$Conservative and Non-Conservative Forces For work done by conservative forces ($W = F.S$), we consider $S$ as the displacement and not the actual path travelled. However for non conservative forces we consider the total path length and not just the initial and final point. So can we say that all Conservative forces have fixed direction whereas all non-conservative forces are always parallel or antiparallel to path length being travelled?

A: The definition you gave is a bit confused. For any force, conservative or not, its work along a trajectory $\Gamma$ is defined as:
$$W=\int_\Gamma\vec{F}.d\vec{l}$$
where $d\vec{l}$ is a small fragment of the trajectory.
After that, if $\vec{F}$ is conservative, there exists a potential energy $V$ that depends only on position such that:
$$\vec{F}=-\vec{\nabla}V$$
Therefore:
$$W
=\int_\Gamma-\vec{\nabla}V.d\vec{l}
=-\int_\Gamma dV
=-\Delta V$$
So work is just the variation of potential energy between the starting and ending points.
Conservative forces don't have to maintain a constant direction. Counter-examples are easy to find:

*

*elastic force: $\vec{F}=-k\vec{r}$

*newtonian force: $\vec{F}=-\dfrac{k}{r^2}\,\hat{r}$
Both forces don't have a constant direction, and they're famous examples of conservative forces.


text:
Q: How to show a progress bar, when using ExecutorService's awaitTermination method? I am building an app, which scrapes prices from several webpages, and then displays the result, after all tasks are completed. Everything works fine, except that I am struggling to add a progress bar.
Below is a simplified version of what I am trying to do. After pressing a button the program runs 2 tasks: the first one sleeps 3 seconds, the second one - 7 seconds. When all is done, toastmessages from each task are displayed.
public class MainActivity extends AppCompatActivity {
Button button;
ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.btn);
    progressBar = findViewById(R.id.pb);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            progressBar.setVisibility(View.VISIBLE);

            ExecutorService executorService = Executors.newFixedThreadPool(5);

            executorService.submit(new Task1());
            executorService.submit(new Task2());

            executorService.shutdown();

            try {
                executorService.awaitTermination(1, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            progressBar.setVisibility(View.INVISIBLE);

        }
    });

}

private class Task1 implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(3000);
            Log.d("task1", "run: ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "task1", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

private class Task2 implements Runnable {

    @Override
    public void run() {
        try {
            Log.d("task2", "run: ");
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "task2", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

}
As I understand the problem is that all threads are blocked when using awaitTermination method, including UI thread, and therefore Task results appear only after all tasks are completed.
Is there a way to wait until all tasks are completed, while still displaying a progress bar?

A: Yes, you are right about awaitTermination. But it blocks only main thread, others are not touched with it.
One way to solve your problem is to define active task counter. Every time you run task, it increases. Every time task ends (including fail) counter decreases.
And of course you should remove awaitTermination method. In Android (and mostly in all UI related frameworks) you should not block UI thread.
Pseudo code of my proposition:
Button button;
ProgressBar progressBar;
int activeTaskCounter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.btn);
    progressBar = findViewById(R.id.pb);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ExecutorService executorService = Executors.newFixedThreadPool(5);

            executorService.submit(new Task1());
            executorService.submit(new Task2());
            executorService.shutdown();
        }
    });
}

private void increaseActiveCounter() {
    activeTaskCounter += 1;
    progressBar.setVisibility(View.VISIBLE);
}

private void decreaseActiveCounter() {
    activeTaskCounter -= 1;
    if (activeTaskCounter == 0) {
        progressBar.setVisibility(View.INVISIBLE);
    }
}

private class Task1 implements Runnable {
    @Override
    public void run() {
        // It's lambda here, but you can use anonymous class. It's up to you
        runOnUiThread(() -> increaseCounter());
        try {
            Thread.sleep(3000);
            Log.d("task1", "run: ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            runOnUiThread(() -> decreaseActiveCounter());
        }

    }
}

private class Task2 implements Runnable {

    @Override
    public void run() {
        runOnUiThread(() -> increaseCounter());
        try {
            Thread.sleep(7000);
            Log.d("task2", "run: ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            runOnUiThread(() -> decreaseActiveCounter());
        }
    }
}


text:
Q: The encode() function on my command is sending a b' prefixed request to the server When I execute this script, I always get a Bad Request output. I don't understand what is going wrong. I wanted to print the output of my cmd variable and I see a b' as the prefix. I think this is how it is going to the server as a request and as a result it's failing. It's Python 3.7.0, by the way.
My code snippet is as follows:
import socket

brows = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
brows.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
print(cmd)
brows.send(cmd)

while True:
    data = brows.recv(512)
    if (len(data) < 1):
        break
    print(data.decode())
brows.close()

My output is as follows:

I'm completely new to Python. Can someone please help me solve this?

A: I don't think the b' is the problem. That's just how bytes objects (which is what .encode() returns) are printed or converted to strings with str().
I don't know what your server is like, but I would guess that the problem is in the request, not the Python.
I would make one other recommendation, however. Use with to make sure the socket closes automatically at the end, whether there is a failure or not. As it is, if the program has an exception, the socket will not be closed. The with syntax tells Python to try to run it and automatically close it when done.
with socket.socket(...) as brows:
    # socket is open; we can do stuff with it
    brows.connect(...
# The socket is no longer open here

You don't even need to call .close() explicitly at the end!
Edit: To clarify, the socket is only open within the with block.


text:
Q: Is there a name for comedically ignoring something major while pointing out something mundane? Example: a video shows someone being injured and often times the top comment is something like "Wow... it's so tragic that people still think it's ok to wear green pants" or something similarly minor and unrelated to the more serious, obviously intended focus of the situation. I see this done frequently by comedians and on TV (South Park does this a lot).

A: You are describing an instance of Bathos:
OED:

2. Rhetoric. Ludicrous descent from the elevated to the commonplace in writing or speech; anticlimax.
1875   A. Maclaren Serm. 2nd Ser. xii. 211   It is as absurd bathos
as to say, the essentials of a judge are integrity, learning, and an
ermine robe!
c. 1979: I'm Sorry I'll Read That Again (BBC Radio Comedy) MARY:
"John – once we had something that was pure, and wonderful, and good.
What's happened to it?"
JOHN: "You spent it all."

A: Facetious (Wiktionary)

*

*Treating serious issues with (often deliberately) inappropriate humour; flippant.
Robbie's joke about Heather's appearance was just him being facetious.

*Pleasantly humorous; jocular.

*Of an idea or statement, humorously silly or counterproductive for the purpose of sarcastically advocating the opposite.
Flippant (Wiktionary)

*

*Showing disrespect through a casual attitude, levity, and a lack of due seriousness; pert.

*(archaic) glib; speaking with ease and rapidity

A: There are a few words which might be Partially Suitable here.

gallows humour
Comedy that makes light of death or other serious matters
humor that makes fun of a life-threatening, disastrous, or terrifying situation

faux pas
A socially awkward or tactless act
Embarrassing Error

gaffe / gaucherie / solecism
Synonyms for faux pas

non sequitur
A reply that has no relevance to what preceded it

We could combine these terms into something like this :

The top comment in the car accident video was a non-sequiturial (??) faux pas bordering on gallows humour.
The Prince , known for his gaffes , indulged in gallows humour , when he non-sequiturially (??) voiced his faux pas observations.

A: The general comedic device is called a misdirection although it is mainly associated with stand-up comedy.

A comedian will sometimes use misdirection to have the audience think they're going to say one thing but then get the proverbial rug pulled from under them during the punchline.  Wikipedia/Comedic_device

Bait-and-Switch is a more specific term provided by TVTropes. The name is originated from a now-illegal advertising practice and it differs from paraprosdokian:

A type of setup where a character leads the audience or other characters into thinking they are going to say or do something, but says or does something unexpected. This is usually a joke, and if the punch line of the joke causes the first part to take on a new meaning (e.g., "I just flew in from Chicago, and boy are my arms tired"), it is technically called a "paraprosdokian."

There are examples of bait-and-switch from Western animations like Family Guy, South Park and The Simpsons. Here is a good and absurd example from Family Guy provided by TVTropes:

In an earlier episode, there's a Cutaway Gag where Peter cuts a cake but ends up accidentally slicing a woman inside the cake (who was supposed to surprise the guests by jumping out of it). Peter yells, "Ah, crap!" but not because he killed the woman; it was because the cake was coconut flavor.


text:
Q: vba access: each Ctl in report.controls i need all the rectangles on my form to be red when the report opens. how do i do this?
here's my code:
Private Sub Report_Load()
    For Each ctl In fill_boxes.Controls
            If ctl.Name = acRectangle Then
                ctl.Name.BackColor = "#ED1C24"
            End If
    Next ctl
End Sub

i get an error OBJECT REQUIRED on this line:     For Each ctl In fill_boxes.Controls
fill_boxes is the name of the report
how do i tweak the code to make all rectangles red on report open/?

A: Is the BackStyle on the rectangle set to Transparent or Normal - Normal is what you want to be if you want to colour the contents of it.
ctl.Name.BackStyle = Normal


text:
Q: Cannot access /home/user directory with permissions drwxrwxrwx My company's server uses Linux Redhat Enterprise version. I notice other users' home directories have permission drwxrwxrwx. However, I cannot cd or ls other users' home directories. Why this happens?
More backgrounds: My company has N machines 1, 2, 3, .. , N. Suppose there are userA, userB, userC, userD 4 users. Each user can log on any machine to access his own /home/user[A|B|C|D] directory.(From this behavior, I guess the data in the home directories is stored on a shared drive and then mounted on each machine). In addition, each user can see other users' /home/userA, /home/userB, etc with permission drwxrwxrwx. However, each user cannot cd or ls other users' home directories. What is my company's system setup to achieve this?


text:
Q: Python: How can I indent two "if" statments I am following a tutorial in French about Python and both in IDLE and the terminal, I have some problems.
Picture from tutorial

My attempt who failed

I cannot go to my second if condition without printing pos. Someone has an idea ?

A: First, learn how to post formatted code in your questions so that you don't have to post links to other sites. The goal is to make your question as easy to answer as possible.
You are wanting to see whether or not variable a is greater or less than 0 and then to print something. Right now your code is saying the same thing twice:
if a > 0:
    print('pos')
pos

if a > 0:
    print('pos')
pos

Your code as it is written now, will never print out your other if statement even if you had written it because you have said that a = 5. So your code is saying 'a IS greater than 0 so I'm going to print "pos" '. You need to say that a = <negative number> so that your other if statement will be true once you have written it. Then your program will analyze the first if statement, see that it is not true, and move onto the next one, see that it is true and print whatever you have in the if statement.


text:
Q: Maximal Subgroups cannot be generated. Quick question. I have a list of conjugacy classes (in ATLAS notation) such as:
(2A, 3A, 8A) and (2A, 4A and 6A) - these are triples of conjugacy classes that are present in $M_{12}$ (Mathieu Group). I wish to show that these triple of elements do not generate $M_{12}$, but rather they generate proper subgroups of $M_{12}$.
EDIT: I'm extremely sorry, I forgot to add the condition that the for the conjugacy classes $(C_1, C_2, C_3)$ of $M_{12}$ we require that for $g_i \in C_i$, $M_{12}$ = $<g_1, g_2, g_3>$ with $g_1g_2g_3 = 1$ (that the product of elements from each conjugacy class in the triple is the identity element of the group).
Apparently, one can retrieve this information by looking at the character tables  of the maximal subgroups of $M_{12}$ (as one can do so in GAP) to show that $M_{12}$ cannot be generated by the above conjugacy classes. My question is essentially how do the character tables of the maximal subgroups help us see that the triple of classes do not generate the entire group, $M_{12}$.
Best,
Always

A: I looked at this, and to me it seems that what you want to show is false.
Using the online ATLAS, you can construct $G = M_{12}$ with its standard generators $a, b$ in MAGMA or GAP. The ATLAS will also give you representatives for each conjugacy class of $G$ as a word in $a$ and $b$. Thus you can construct representatives $x$, $y$, $z$ for the conjugacy classes $2A$, $4A$, $6A$, say.
With a random search, you will find that most of the time, for $g \in G$ and $h \in H$ the subgroup $\langle x, gyg^{-1}, hzh^{-1} \rangle$ is all of $G$. The same is also true for the triple $(2A, 4A, 8A)$ of conjugacy classes.

EDIT: The above answers the original question. For the modified question, there are indeed character theoretic methods. See for example the following paper, especially pg. 31-32.

Woldar, Andrew J.; Representing $M_{11}$, $M_{12}$, $M_{22}$ and $M_{23}$ on surfaces of least genus. Comm. Algebra 18 (1990), no. 1, 15–86.

The key point is that if $C_1$, $C_2$, $C_3$ are conjugacy classes of $G$, then from the character table of $G$ one can calculate the number of triples $(g_1, g_2, g_3)$ such that $g_i \in C_i$ and $g_1g_2g_3 = 1$.
There are also other methods, for example:

Conder, Marston; The symmetric genus of the Mathieu groups. Bull. London Math. Soc. 23 (1991), no. 5, 445–453.


text:
Q: Charging SLA Battery I currently have a project requiring the use of a battery. My project has to be able to run off the battery power, but when an outside source is connected, the battery should be able to charge off this source, but the source also has to power my project.
I am looking into using an SLA battery such as this one, because in my lack of experience, it seems to be easier to deal with charging than a battery such as a LiPo battery. Since this is the point in which a screw up could result in a destruction of my project, and I am inexperienced in the area of batteries and charging beyond the basics of electronics, I would like an outside opinion from someone knowledgeable in this area, to let me know if it would work or not.
I attached an image of what I think the layout of my charging system would be. The battery would have the ground connection for the project, and the 12V connection. The relay would go on the ground side of the battery, after the connection to the project. This way, the battery can charge/discharge according to the relay. The voltage monitor would determine when the relay needs to be on or off. The relay and voltage monitor would have connections to the Arduino Nano, acting as the controller for the charger. The Nano would supply 5 volts to the voltage monitor. Also, the Arduino Nano is powered from the same charger, via an inline voltage regulator.
Essentially my question is: Will this work before I go and do it and mess something up? Or is there possibly a better way of doing this?

Voltage Monitor
Charger
Regulator to Power Nano

A: It is extremely common to connect a battery charger, a SLA battery, and a load in parallel - millions of cars are wired that way.
If the charging source can supply more current than the load needs, the excess goes to charge the battery.
If the charging source can't supply enough current to supply the load, the battery will discharge to make up the difference.
The battery will switch between charging and discharging automagically as the load or charging source change - no need for any external control.


text:
Q: Disk Device In Bash on Ubuntu on Windows 10 In Windows 10, you can enable Bash on Ubuntu on Windows. I have done this, but I am struggling to figure out how to access the disk devices. For example, in normal Ubuntu, if I wanted to do a low-level copy of one flash drive to another, I might execute dd if=/dev/sdb of=/dev/sdc bs=4K, but the /dev/sd? devices do not seem to exist in Bash on Ubuntu on Windows. lsblk also does not list any devices. Since dd is installed, I would like to believe there must be a way to access disk devices. Can this be done? How?

A: The Windows Subsystem for Linux doesn't install fully featured Linux kernel, only a stub that allows to run certain types on applications compiled for Linux. Btw. the Bash on Windows or any for of this name is incorrect (Microsoft mistake to name the command bash). I don't think Microsoft ever dare to add so low level access to the WSL.
However, from my experience what you want to achieve is available in virtual machine. In my case it was Ubuntu installed in VirtualBox. Then you can map USB devices to be available in guest system. That way dd commands are going to work at lowest possible level exactly like on natively installed Linux Distribution.


text:
Q: How do I replace self compiled packages (php, mysql, memcahed) with yum version in centos6.5 I have at least 5 development servers (dev, QA, staging) that have php and other packages compiled from source. I would like to remove all of them and update those servers with yum packages. If I can do that via puppet or chef that will be great. So:

*

*How do I start looking for packages that are self compiled and remove them ?

*Later install the updated version of the same packages via yum in the server?

*Is puppet/chef is a good option to use to simulate the changes in the servers ?

A:
How do I start looking for packages that are self compiled

There isn't really a good way to guarantee you'll get them all

*

*Consult your config documentation.

*Consult your build documentation.

*Look in the usual places (/usr/bin, /usr/local/bin etc)

but there isn't really a good way to guarantee you'll get them all

and remove them

This is non trivial unless the package came with a way to remove itself.
You could try recompiling the packages and then reinstalling them using a chroot or if a DESTDIR= drective
mkdir /tmp/package
make && make install DESTDIR=/tmp/package

Then look at the contents of the /tmp/package or chroot tree to get a filelist which can then be used to delete the files from the main filesystem tree. This is though dependent on you knowing the options you used to configure the build.

Later install the updated version of the same packages via yum in the server?

yum install packagename

Is puppet/chef is a good option to use to simulate the changes in the servers ?

Your best solution at this point is to start again. Choose a config management solution and use it to build consistent systems
Install your base OS then

*

*Use your config management solution to add and configure packages

*Run your tests

*If tests fail

*

*Work out why

*update configuration management

*rinse and repeat until tests pass

A: Provided you have the compiled sources still around (I tend to keep them myself) a lot of today's packages support the uninstall target. Just make uninstall and hopefully the right files will be deleted. If you don't have them around, recompile them and install, then uninstall. Just make sure you have the same version.
If this does not work, you might want to try installing the distros packages, and use rpm to manually hunt for files, that do not belong to any package. Just make sure all previous files get overwritten.

A: unfortunately it is not very easy to clean such a situation. Anyway, to the following:

*

*do a list of what you think was manually installed, it will be useful

*self-compiled packages generally are in /usr/local, /opt and other non-default directories. Have a look on these directory to see what was manually installed

*after manual installation discovery, install via yum/rpm the official packages. They will be installed in /bin, /usr/bin and other default directories, so they should be the preferred program when invoking the executable (eg: /usr/bin/php should be preferred to /usr/local/bin/php). Anyway, check you PATH variable

*remember that the official packages will install different (probably older) version of the affected software. If your applications depend on specific package version, they can have problems (eg: if you use a recent Joomla installation, be aware that it need at least PHP 5.3.10+, while the CentOS-provided one is at 5.3.3)

*I would not use automatic configuration script/methods to execute this activity. It really need manual intervention, at least of the first servers.


text:
Q: How to get information from xml file's child node with PowerShell I have a xml file with nodes like this:
<xml>
  <n n="GUID1" t="folder">

  </n>
  <n n="GUID2" t="folder">

  </n>
</xml>

I need to get GUIDs from the first node, but only if path node does not have "QWERTY" in it.
I'm getting all guids with this script:
$Files_xml = [System.Xml.XmlDocument](Get-Content "C:\Files.xml")
[System.Collections.ArrayList] $Files_links = @()
select-xml -xpath "//n[@t='folder']" -xml $Files_xml |  foreach {$Files_links += $_.Node.Attributes.GetNamedItem('n').Value}

And I'm kinda lost how to select only needed ones

A: You need to filter lower:
$xml = [xml](Get-Content -Path C:\Files.xml)
$links = $xml.SelectNodes(
    '//n[@t="folder" and a[@n="path" and not(contains(@v, "QWERTY"))]]/@n'
)

If you prefer using Select-Xml:
$selectXmlParams = @{
    'XPath'       = '//n[@t="folder" and a[@n="path" and not(contains(@v, "QWERTY"))]]/@n'
    'LiteralPath' = 'C:\Files.xml'
}
$links = Select-Xml @selectXmlParams


text:
Q: Find lines matching a pattern except those containing another pattern In Visual Studio Code's regex syntax, is it possible to find all occurrences of a certain string, for e.g.
&$

except where there's another pattern, say the string function( in the same line, for example
function functionname(&$variable, ...)

?
This does not work for me:
(?!function).*\&\$

It simply yields all results, both lines with function in them, and without, as if I were doing a simple search for &$.
VSCode's Regex help page Visual Studio's help page seems to suggest that that's the way, but I can't seem to get it to work in any constellation in VS Code, so it seems the applications are using different notations.
Neither do a couple other notations work (I suppose from different regex flavours) that I've Googled around for.

A: This regexp may work:
^(?!.*function\().*(\&\$)

The &$ is captured in the first group: $1
For the input:
a &$ b
a &$ function()
a &$ function()
function() &$ a
a function() &$ a

Only the &$ on the first line will be matched using this regular expression.
The regular expression works by using a negative lookahead to ensure the line does not contain the string function(. This lookahead has to be pinned to the start of the line however, which is why the .* is required.. Also, this will only match one occurrence per line


text:
Q: How to separate text images from images that has both text and some figures I am new to OpenCv and I have a problem where I need to separate text only images from images that has text along with some other figure element.
I am using EAST text detection for the same.
 -
.
East text detection is good but it doesn't work well with all the text images and the bounding box regions is also not accurate.
When i applied EAST text detection on this image:

the bounding box i get doesn't cover full text region shown in this image:
.
Is there any better way to do this?
Any help will be appreciated. Thanks in advance.

A: If I am right, this should answer your question.


text:
Q: PHP: get multiple object in json from mysql database get_post.php
<?php
require_once 'database_config/DbOperations.php';

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $location = $_POST['location'];

    $db = new DbOperations();

    $post = $db->getPostByLocation($location);

    $response['id'] = $post['id'];
    $response['name'] = $post['name'];
    $response['gender'] = $post['gender'];
    $response['dob_year'] = $post['dob_year'];
}

echo json_encode($response);

?>

ObOperations.php
public function getPostByLocation($location)
    {
        $stmt = $this->con->prepare("select * from table_post where location = ?");
        $stmt->bind_param("s", $location);
        $stmt->execute();

        return $stmt->get_result()->fetch_array();
    }

Hi, what I am trying to do is to get JSON objects for all data that has a certain location data. When I type New Jersey, then it should get objects for all data that has "New Jersey" location data. But, it only prints one data. How can I get all data in json format. ObOperations has getPostByLocation function and it works correctly.
Thank you!

A: If you do $stmt->get_result()->fetch_array(); you just get the first row, you should use while loop for retrive all the row, e.g.
<?php
public function getPostByLocation($location)
{
    $stmt = $this->con->prepare("select * from table_post where location = ?");
    $stmt->bind_param("s", $location);
    $stmt->execute();

    $data = array();
    $result = $stmt->get_result();
    while($row = $result->fetch_array())
    {
        $data[] = $row;
    }
    return $data;
}


text:
Q: macOS12.x, BLE kCBAdvDataLocalName is empty When I startAdvertising, my localName is long, more than 8 bytes. like @"123456789".
   [_peripheralManager startAdvertising:@{
            CBAdvertisementDataLocalNameKey: @"123456789",
            CBAdvertisementDataServiceUUIDsKey: @[[CBUUID UUIDWithString:@"bbbb14c7-4697-aaaa-b436-d47e3d4ed187"]]
            }];

When running on macOS 11.x though localName exceeds 8 bytes. But it can still be scanned.
{
  kCBAdvDataIsConnectable = 1;
  kCBAdvDataLocalName = 123456789;
  kCBAdvDataRxPrimaryPHY = 0;
  kCBAdvDataRxSecondaryPHY = 0;
  kCBAdvDataServiceUUIDs =   (
    "BBBB14C7-4697-AAAA-B436-D47E3D4ED187"
  );
  kCBAdvDataTimestamp = "680712553.800874";
  kCBAdvDataTxPowerLevel = 12;
}

But running after macOS 12.x, if localName exceeds 8 bytes, it will be completely ignored. In the scanned data, localName is empty.
{
  kCBAdvDataIsConnectable = 1;
  kCBAdvDataRxPrimaryPHY = 0;
  kCBAdvDataRxSecondaryPHY = 0;
  kCBAdvDataServiceUUIDs =   (
    "BBBB14C7-4697-AAAA-B436-D47E3D4ED187"
  );
  kCBAdvDataTimestamp = "680712744.108894";
  kCBAdvDataTxPowerLevel = 12;
}

On macOS11.x, SCAN_RSP is utilized if localName exceeds 8 bytes,

while on macOS12.x, SCAN_RSP is always empty.

*

*Why are there differences between macOS11.x and macos12.x, is there any documentation?

*What is the maximum limit for localName? (On macOS 11.x, I verified it was 29 bytes

*Are there other ways to broadcast longer data?

Does anyone know why? This has bothered me for a long time...


text:
Q: Calculate Power of Double with Double exponent in C# I need to calculate x^y where both x and y are Doubles.
I tried using Math.Pow:
  Double result = Math.Pow(24.69, 2/3);

The value of result is 1 where it should be 8.4790 ...
Any idea why?

A: For the exponent you are passing in 2 ints which is do integer division. So it is doing:
Math.Pow(24.69, 0)

To fix this use doubles like this:
Double result = Math.Pow(24.69, 2.0/3.0);


text:
Q: Loading large amounts of data from SQL Server database in C# I'm using csvhelper to create a .csv file.
This is my code:
    public async Task LoadLargeDataToCsvFile(string pFileName, string pSql)
    {
        SqlCommand cmd = new SqlCommand(pSql, GetSqlConnection);
        cmd.CommandType = CommandType.Text;
        cmd.CommandTimeout = 0;

        using (StreamWriter writer = new StreamWriter(pFileName, false, Encoding.UTF8))
        {
            using (CsvWriter csvWriter = new CsvWriter(writer))
            {
                    csvWriter.Configuration.Delimiter = ";";
                    csvWriter.Configuration.RegisterClassMap<CChevalPropertiesMap>();

                using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                                csvWriter.WriteField(reader[i]);
                        }

                        await csvWriter.NextRecordAsync();
                    }

                    reader.Close();
                }
            }
        }
    }

This code takes a long time to execute and yet I think it is well done.
This is the call:
await Task.Run(()=> cConnection.LoadLargeDataFromSqlToCsvFile(args[0], args[1]));

or
IAsyncResult result;

result = Task.Run(()=> cConnection.LoadLargeDataFromSqlToCsvFile(args[0], args[1]));

while (!result.IsCompleted)
{
    Application.DoEvents();
}

I have 60000 rows in the table and 10 columns.