text:
Q: Knockout: Complex binding with observable arrays and checkboxes I have an observable array of Services that might be provided by a company (i.e. Sales, Service, Consulting). Each of these services may be performed by the company in zero or more US States, and for each state there is an optional certification number. Thus, the Service has an observable array of Locations, and a Location is a combination of State and Cert Number.
function Service(name) {
    var self = this;

    self.Name = ko.observable(name);
    self.Locations = ko.observableArray();
}

function Location(state) {
    var self = this;

    self.State = ko.observable(state);
    self.CertNum = ko.observable();
}

In the user interface, I want to display a single list of all the US States. The user would tick the checkbox next to each state the in which the company operates, making a "master list" of states. This master list, in turn, drives the choices that appear under each of the possible services.
For example, the user ticks "Alabama" and "Arizona" in the master list. The UI then renders a separate Location for each Service as a combination of a checkbox and textbox. Here's the master view model:
function viewModel() {
    var self = this;

    self.AllStates = [
        { name: "Alabama", abbrev: "AL" },
        { name: "Alaska", abbrev: "AK" },
        { name: "Arizona", abbrev: "AZ" },
        { name: "Arkansas", abbrev: "AR" }
    ];

    self.BusinessStates = ko.observableArray();

    self.AllSelectedStates = ko.computed( function() {
        return ko.utils.arrayFilter( self.AllStates, function(item) {
            return self.BusinessStates.indexOf(item.abbrev) >= 0;
        });
    });

    self.Services = ko.observableArray([
        new Service("Sales"),
        new Service("Service"),
        new Service("Consulting")
    ]);
}

A simple view would look like:

Master List

        <input type="checkbox" data-bind="value: abbrev, checked: $root.BusinessStates"/>

Services

             <input type="checkbox" data-bind="value: abbrev, checked: $parent.Locations" />

           <input type="text" placeholder="Cert. Number" data-bind="value: ??" />

That view at least gets me a state entered into the Service's Locations array, but I don't know how to bind the CertNum property.
Let's say the user has selected Alabama and Arizona in the master list. Now, for the "Sales" service, the user ticks "Arizona" and enters a certification number of "98765". Under the "Consulting" service, the user ticks "Alabama" and does not enter a cert number. Ideally I'd like the resulting JSON snippet to look like:
"Services": [
    {
        "Name": "Sales",
        "Locations": [
            {
                "State": { "name": "Arizona", "abbrev": "AZ" },
                "CertNum": "98765"
            }
        ]
    },
    {
        "Name": "Service",
        "Locations": []
    },
    {
        "Name": "Consulting",
        "Locations": [
            {
                "State": { "name": "Alabama", "abbrev": "AL" },
                "CertNum": null
            }
        ]
    }
]

I can render and bind the "master list" of US States. I can iterate over the services and render a UI that provides controls for each available service location (i.e. checkbox for the state, textbox for the cert. number). What I haven't been able to is bind the service location controls to control membership of the location in the appropriate Locations array, AND affect the value of the certification number at the same time.
The closest attempt I've made is pretty complicated and hacky, where I'm using the knockout-postBox plugin to link the viewModel.AllSelectedStates property to a similar property on each Service model, and then push new Locations into each Service.Locations array. It almost works, except it wipes out changes to the Services whenever a state is checked or unchecked in the master list. Also, I have to push every available location into the Locations array for each Service, and rely on an IsSelected boolean flag on the location to determine whether it's been selected (I'd rather put just the locations in the array that were selected).
You can see the attempt in this JSFiddle: http://jsfiddle.net/cbono/PU6Sq/23/
The nice thing about it is it demonstrates how the UI should behave. But I think this is possible without the postBox plugin, I'm just not looking at the problem the right way to work out the answer. I've spent several days working through this and can't come up with a solution that works 100%.

A: It is easier to use the visible-binding, than to manage the collection events.

http://jsfiddle.net/MizardX/XTkpb/

If you really need to handle them, you could cache the StateAndCert objects in the Services objects:
var self = this,
    cache = {};

self.Locations = ko.computed(function () {
    return ko.utils.arrayMap(states(), function (item) {
        var key = item.Abbrev();
        if (cache[key] === undefined) {
            cache[key] = new StateAndCert(item);
        }
        return cache[key];
    });
});

http://jsfiddle.net/MizardX/HMAtE/

To hide certain properties from the JSON rendering, you could stuff them inside a function(){} property:
self.Meta = function(){};
self.Meta.IsSelected = ko.observable(false);


text:
Q: Method exist in SQL Server does not work correctly with C# parameters @XPath in a request The method exist for XML object does not work correctly with parameter in SQL request from .NET backend side. In my case, I try to send @XPath parameter to the request and put whole this one through exist method to select all XML items according to this XPath but as result, I get all non-filtered by these XPath XML from a table.
exec sp_executesql N'SELECT TOP(1000) ord.TrackingID, ord.DateCreate, ord.OrderType, ord.Error_Description, ord.Response, ord.Request
                     FROM FilteredByXPath AS ord
                     WHERE (ord.Request.exist(''sql:variable("@XPath")'') = 1)',
                   N'@TrackingID nvarchar(4000),@ShowAutotestCases bit,@DateFrom datetime,@DateTo datetime,@InputOrderSource nvarchar(1),@Agency int, @XPath nvarchar(max)',
                     @TrackingID=NULL,@ShowAutotestCases=0,@DateFrom='1753-01-01 00:00:00',@DateTo='9999-12-31 23:59:59.997',@InputOrderSource=N'%',@Agency=0, @XPath=N'//*[text() = "10:33:34.9375000-05:00"]'

Following the exist description I think the ''sql:variable("@XPath")'' returns all time nonempty result and all XML is suitable.
The variants which work well are
WHERE ord.Request.exist(''//*[text() = sql:variable("@XPath")]'') = 1

or
WHERE ord.Request.exist(''//*[text() = "10:33:34.9375000-05:00"]'') = 1

As we see the two variants well when we use XPath as a string directly or @XPath parameter into XQuery.
The question how can I use @XPath parameter as a full XQuery expression like in first variant that does not work.
WHERE (ord.Request.exist(''sql:variable("@XPath")'') = 1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call function of Context in react class component I have following Code in my Context.js:
import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Now I want to use the Context in a class component and especially call the dispatch function, here a minimal example:
export default class Register extends Component {
  static contextType = Context;

  componentDidMount() {
    const { dispatch } = this.context;
    dispatch({ type: "LOGIN_START" });
  }

  render() {
    return (

    )
  }
}

The Problem now is that dispatch is undefined, when I want to call it inside my class. Before I used the same context with const { dispatch, isFetching } = useContext(Context); inside a functional component and everything worked fine, what is the problem?

A: As suggested in one of the comments above, my ContextProvider has to be an ancestor of my Register component in the component tree. I simply added it inside my index.js:
...
import { ContextProvider } from "./context/Context";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ContextProvider>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </ContextProvider>
);


text:
Q: IIS HTTP Response Header unique to each server using Shared Configuration I am running a web farm using shared config and would like to add something to every response to identify which node in the farm it has come from.
I was of the understanding that the inheritance of IIS configurations would mean that I could add my section in the machine.config files since they are unique to each node in the farm and it would cascade down.
   <system.webServer>
     <httpProtocol>
       <customHeaders>
         <add name="X-Machine-Name" value="SERVER1" />
       </customHeaders>
     </httpProtocol>
   </system.webServer>

I also removed the <clear /> out of the applicationHost.config customHeaders section but my custom X-Machine-Name does not appear on responses served by machines in my farm.
I would like to identify which machine the content is coming from, it doesn't need to be anything identifying to the machine, a simple 1,2,3 or a,b,c would do to keep it secure. I want to make it fairly easy if a colleague has to add a new node to the farm to be able to reproduce.


text:
Q: Can't boot ubuntu anymore after Windows 10 update I used to be able to select either the Windows Boot Manager or Ubuntu when booting my ASUS laptop.
Since Windows 10 has updated, it now automatically chooses the windows boot manager. Ubuntu is the first in the boot priority list, and even if I press escape during startup to manually choose a boot device, and then choose ubuntu, it still loads up the windows boot manager.
I have disabled secure boot, fast boot, and hibernation. This all used to work until the latest Windows 10 update. Any ideas?

A: During the Windows 10 update process, Windows 10 decided to overwrite your MBR bootloader. Which in the case before the update, was GRUB.
But after the update, Windows 10 replaced GRUB with BOOTMGR, Windows 10's bootloader.
1. Getting a boot-repair disk
boot-repair is a program that can:

*

*send computer info to Pastebin

*install GRUB on the bootloader

*configure grub

*and more!

If you run a 64-bit system, go here
If you run a 32-bit system, go here
2. Etching the image to a disk
Ironically, we will be using the popular image writer, Etcher.
To download Etcher, go here
Basically, just select your downloaded boot-repair-disk .iso
 file and select a USB device.
WARNING: THIS CAN ERASE ALL DATA FROM YOUR USB. USE THIS PROGRAM WITH CAUTION.
3. Booting up.
To boot up to boot-repair, attach your USB disk, power on your computer, then start pressing the 'boot from...' key.
Select your disk.
You should start to boot up.
When you see a window that is titled, boot-repair or something similar...
Select Automated fix or the 1st option.
Only select "more options" if you are an experienced Linux user or have a friend to help!
It should start reinstalling and configuring GRUB (should be the latest one depending on your disk version).
When it is done, reboot if it asks you to. If it does not, open the power menu, and select reboot.
This time, select your boot disk (hard drive, SSD, etc.)\
You should see a menu. (GRUB!)
Select Windows or Ubuntu.
You should boot to said OS!
Follow this guide whenever you update Windows 10.
I hope this guide helped!


text:
Q: Keep an element at the centre of a div I am creating a web page that needs to be responsive.
Here is an image of it:

Here is the HTML:

                WHEN?

and the CSS:
.smallBoxes{
    display:block;
    margin-left:25%;
    margin-right:20%;
    width:auto;
}

.leftHomeBox{
    width:100%;
    float:left;
    margin-bottom:10px;
    padding:10px;
    padding-bottom:0;
    height:65px;
}

.Description{
    border:5px solid #ffffff;
    padding:5px;
}

I am trying to keep the "when" box in the centre of the div, for all screen sizes. AS things are now, both margins will change, but at different rates eg they do not stay consistent relative to each other and so the "when" box doe s not stay central.
I have looked at other websites and have not been able to find a working example.
I have tried using
margin-left:20%;
margin-right:20%;
width:auto;

but this does not work. I have been working on this all day and I have read all I can find but I cannot seem to get this to work. I have tried every possible thing I can think of.
Surely this is something that is required often and cannot be very difficult to achieve, but I am not able to find a clear answer to how to achieve this, or what I am doing wrong.
If someone could provide a fiddle of a working solution I would be very grateful.

A: use
CSS
.leftHomeBox{
text-align:center
}

DEMO

A: .Description
{
 display:block;
 margin-left:auto;
 margin-right:auto;
}

This should be work.

A: You can apply a text-align: center on an  tag.
.leftHomeBox{
  text-align:center
}

It will center the link without using margins


text:
Q: JQuery Mobile site works in Browser but not in Mobile Browser I've created a JQuery Mobile Site which picks the data from CSE webservice. I released teh source also at github.
My problem is site works fine when loaded via browser but when I try to load it via Mobile Browser it keeps on loading....!
can someon eplease enlight me? Does it something to do with the XML file size that receive from webservice??

*

*Live

*Source
Thanks for your time in advance.

A: Depending on your connection (3G, LTE, Wifi) it could certainly be the latency in loading the XML file, but it is only ~130kb which isn't that huge.  It took my browser 2.75 seconds to load.
Have you already profiled this web app with something like Google Chrome?  If you run a profile and load the page, you'll find that over 60% of your load time is lost in a jquery filter selector.  This means that you could really benefit from tuning your endCallService function.
Because of the size of the xml document, if you could reduce the amount of time you traverse it than your code will work a lot better.  The xmlHttpRequest object can be traversed as an array so I think you could speed things with something like this:
listStr = listStr +  .... xmlHttpRequest[0][j][i]

The first [0] is the first table element. The next position, [j] is the row.  Then the [i] is your column still.
Could you try that and see if that performs better?  I was unable to test in jsfiddle because I was getting server errors trying to access your proxy.php script.
This should work and when it does, you will be able to squeeze the same performance out of the other objects you are loading in the next nested loop. (var shareName, shareVolume, etc).
Cheers!


text:
Q: How to launch view controllers before UITabBarController? I have an app/game where I would like to display a series of view controllers (ie: Start game, load game, etc) before displaying any form of UITabBarController.
The process would be:

*

*Launch app delegate

*Launch my series of view controllers

*Only when Start game has been pressed launch/show the UITabBarController.

My UITabBarController is tied to the app delegate, and my current code is as such:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    SplashScreenVC *splashScreenVC = [[SplashScreenVC alloc] initWithNibName:@"SplashScreenVC" bundle:[NSBundle mainBundle]];

    UINavigationController *firstView = [[UINavigationController alloc] init];
    [firstView presentModalViewController:splashScreenVC animated:NO];
    [firstView release];

    [splashScreenVC release];
    [self.window addSubview:[tabController view]];
    return YES;
}

I try to launch the splash screen as a modal view controller, but this does not appear to work.
I've also tried launching it as initWithRootViewController -- but regardless what I do the UITabBar still gets launched and I never see the modal view.
So, how do I launch stuff, views, etc before the tabBarController view?
Many thanks

A: Why not put the tabbar hidden?

A: Do you know the iOS responder chain ?  If you want to show the UI , the UI must be added on the  window .
so the splash should be added on the window( the first index on top just "tabbar hidden"), you will see the display effect, then after showing Splash , you will see the normal tabbar.
note:

*

*[self.window bringSubviewToFront:self.splashView];  // on the top

*[self performSelector:@selector(removeSplashView) withObject:nil afterDelay:5]; // after 5s the splash will disappear automatically


text:
Q: How to generate certificate - UWP, BouncyCastle I've got problem with generating certificate. I use Portable-BouncyCastle on Universal Windows Platform. It's 1.7 version. I can't create SecureRandom and ISignatureFactory because in this verion of library there is problem with: CryptoApiRandomGenerator, ISignatureFactory and Asn1SignatureFactory. Do anyone knows how to generate certificate without them? Here is my function:
                DateTime startDate = DateTime.Now;
                DateTime expiryDate = startDate.AddDays(365);
                SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator());
                ISignatureFactory signatureAlgorithm = new Asn1SignatureFactory("SHA256WITHRSA", _caPrivateKey.GetKey, random);
                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
                certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Millisecond));
                certGen.SetIssuerDN(_caCertificate.CertificateProp.SubjectDN);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(_subjectInfo);
                certGen.SetPublicKey(_subjectPublicKey.GetKey);
                X509Certificate newCertificate = certGen.Generate(signatureAlgorithm);

A: I found answer to my question. The solution is:
                DateTime startDate = DateTime.Now;
                DateTime expiryDate = startDate.AddDays(365);
                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
                certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Millisecond));
                certGen.SetIssuerDN(_caCertificate.CertificateProp.SubjectDN);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(_subjectInfo);
                certGen.SetPublicKey(_subjectPublicKey.GetKey);
                certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");
                X509Certificate newCertificate = certGen.Generate(_caPrivateKey.GetKey);


text:
Q: reactjs - validate enddate is 30 days older How do I validate that the end date is not a date in the past and at least 30 days from the start date?
<TextField
                      id="startdate"
                      name="startdate"
                      label="Start Date"
                      type="datetime-local"
                      defaultValue={dateNow}
                      className={classes.textField}
                      variant="outlined"
                      inputRef={register({ required: true })}
                      InputLabelProps={{
                        shrink: true,
                      }}
                    />

                    <TextField
                      id="enddate"
                      name="enddate"
                      label="End Date"
                      type="datetime-local"
                      defaultValue={dateNext}
                      className={classes.textField}
                      variant="outlined"
                      inputRef={register({ required: true })}
                      InputLabelProps={{
                        shrink: true,
                      }}
                    />

Ideally I want to do it on change if possible.
The date format:
enddate: "2020-10-28T13:03"

I have not tried to build the validation yet, due to I have never done form validation so not sure where to start.
what i know is i'll need a function like
  const validateDate = () => {
    if(document.getElementByName("startdate").value < document.getElementByName("enddate").value){
    return(error)
}

  };

 onChange={validateDate()}

A: You code is pretty far away from idiomatic react style of doing things. So first let's fix this part. The react way of accessing value is via react internal state, not via DOM API.
const [startDate, setStartDate] = useState(dateNow)
const [endDate, setEndDate] = useState(dateNext)

// let's skip this part, it's a placeholder for now, will come back to it later.
const validate = () => { … }

// for simplicity I omitted other props
<TextField name="startdate" value={startDate} onChange={e => setStartDate(e.target.value)} />
<TextField name="enddate" value={endDate} onChange={e => setEndDate(e.target.value)} />

Now you can access startDate and endDate directly inside validate() function. No need to call document.getElementByName whatsoever. Remember, this is NOT just-another-way of doing things. React update cycle is async, value change will not reflect onto DOM instantly, using DOM API will bring you a lot of headache.
Back to validate function. My preferred way of calling validate() is not inside onChange callback, but instead inside useEffect callback.

useEffect(() => {
  // do validation here.
}, [startDate, endDate])

The trailing [startDate, endDate] array is called dep-list. It tell useEffect to run the callback ONLY when value of any element in the dep-list has changed. It's kinda like onChange event, but this event is emitted only AFTER the change of state has been committed (remember react state change is async!). Exactly what we want.
Fill-in the validation code:
useEffect(() => {
  // do validation here.
  const s = new Date(startDate)
  const d = new Date(endDate)
  const deltaMs = d.valueOf() - s.valueOf()

  const _30_DAYS_IN_MS = 30 * 24 * 60 * 60 * 1000
  if (deltaMs < _30_DAYS_IN_MS) {
    // notify user of the result:
    alert("Invalid Input!")
  }
}, [startDate, endDate])

Finally put everything together, it looks like:
import React, { useState, useEffect } from "react"

// …

const [startDate, setStartDate] = useState(dateNow)
const [endDate, setEndDate] = useState(dateNext)

useEffect(() => {
  // do validation here.
  const s = new Date(startDate)
  const d = new Date(endDate)
  const deltaMs = d.valueOf() - s.valueOf()

  const _30_DAYS_IN_MS = 30 * 24 * 60 * 60 * 1000
  if (deltaMs < _30_DAYS_IN_MS) {
    // notify user of the result:
    alert("Invalid Input!")
  }
}, [startDate, endDate])

// for simplicity I omitted other props
<TextField name="startdate" value={startDate} onChange={e => setStartDate(e.target.value)} />
<TextField name="enddate" value={endDate} onChange={e => setEndDate(e.target.value)} />

// …

A: With uncontrolled inputs it is recommended to use react refs to get the inputs versus using a document query.

*

*Create and attach refs to the inputRef props of each input

*Create a datetime object and get the timestamp of start and end dates and now

*Do comparisons in validateEndDate set any error state, alert/log, etc... whatever your app needs to do

Code
const THIRTY_DAYS = 1000 * 60 * 60 * 24 * 30;

...

const startRef = useRef();
const endRef = useRef();

...

const validateEndDate = () => {
  const start = new Date(startRef.current.value).getTime();
  const end = new Date(endRef.current.value).getTime();
  const now = new Date().getTime();

  if (end < now) {
    console.error('End date in past!');
  }

  if (end - start < THIRTY_DAYS) {
    console.error('End date not at least 30 days from start date!')
  }
}

...

<TextField
  inputRef={startRef}
  id="startdate"
  name="startdate"
  label="Start Date"
  type="datetime-local"
  defaultValue={dateNow}
  className={classes.textField}
  variant="outlined"
  InputLabelProps={{
    shrink: true
  }}
/>

<TextField
inputRef={endRef}
  id="enddate"
  name="enddate"
  label="End Date"
  type="datetime-local"
  defaultValue={dateNext}
  className={classes.textField}
  variant="outlined"
  InputLabelProps={{
    shrink: true
  }}
  onChange={validateEndDate}
/>


text:
Q: prove that for $G$ a multiplicative nonabelian group of order $pq$, where $p$ and $q$ are prime numbers, any proper subgroup of $G$ is abelian I need to prove that for $G$ a multiplicative nonabelian group of order $pq$, where $p$ and $q$ are prime numbers, any proper subgroup of $G$ is abelian. I use that, from Lagrange's theorem, the order of the proper subgroups must divide the order of the group and so the subgroups have the orders $p,q$. If $(p,q)=1$, then there exist $k,l\in\mathbb{Z}$ such that $pk+gl=1$ and so, for an $x$ of a subgroup of order $p$ we obtain $x=x^{lq}$ and similarly, for an $y$ of order $q$ $y=y^{pk}$. Also, $p|lq-1$ and $q|pk-1$. This are the only valuable information I obtained. How can I prove this?

A: Hint: use Lagrange's Theorem, the order of a subgroup divides the order of the whole group. And, a group of prime order must be cyclic (also follows from Lagrange).

A: By Lagrange's theorem we can say that order of any proper subgroup of $G$ is either of order $p$ or of order $q.$ Since $p$ and $q$ are primes and we know that any group of prime order is cyclic so any proper subgroup of the group $G$ is cyclic and hence abelian.


text:
Q: Unit testing EJB and remote interface with EjbEmbedded Conatiner I have this EJB
@Stateless
public class HelloBean{

    public String sayHello(){
        return "hello";
    }

}

When I test with this unit test:
    @Test
    public void testEmbeddedPersistence() throws NamingException {
        assertTrue(true);

        Map<String, Object> props = new HashMap<String, Object>();

        props.put(EJBContainer.MODULES,  new File("target/classes"));
        props.put("org.glassfish.ejb.embedded.glassfish.instance.root",    "./src/test/resources/glassfish-testing-domain");

    ec = EJBContainer.createEJBContainer(props);
    ctx = ec.getContext();

    String s = "java:global/classes/HelloBean";
    HelloBean helloBean = (HelloBean) ctx.lookup(s);
    assertNotNull(helloBean);

    assertABunchOfStuff();

    ec.close();
}

everything works fine.
But when I change it to
@Stateless
public class HelloBean implements RemoteHello{

    public String sayHello(){
            return "hello";
    }
}

@Remote
public interface RemoteHello{
    public String sayHello();
}

@Test
    public void testEmbeddedPersistence() throws NamingException {
        assertTrue(true);

        Map<String, Object> props = new HashMap<String, Object>();

        props.put(EJBContainer.MODULES,  new File("target/classes"));
        props.put("org.glassfish.ejb.embedded.glassfish.instance.root", "./src/test/resources/glassfish-testing-domain");

        ec = EJBContainer.createEJBContainer(props);
        ctx = ec.getContext();

        String s = "java:global/classes/HelloBean!com.mycompany.remoteInterface.RemoteHello";
        RemoteHello remoteHello = (RemoteHello) ctx.lookup(s);
        assertNotNull(remoteHello);

        assertABunchOfStuff();

        ec.close();
    }

I get a javax.naming.NamingException
the weirdest thing is, When the EJBContainer is intializing it says:
INFO: EJB5181:Portable JNDI names for EJB HelloBean: [java:global/classes/HelloBean!com.mycompany.remoteInterface.RemoteHello, java:global/classes/HelloBean]
Feb 10, 2012 3:55:22 PM com.sun.ejb.containers.BaseContainer initializeHome
followed shortly after:
Tests in error:
  testEmbeddedPersistence(com.mycompaony.HelloBean): Lookup failed for 'java:global/classes/HelloBean!com.mycompany.remoteInterface.RemoteHello' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
How can I get a successful jndi lookup with a remote interface.
Thanks

A: Remote interfaces are not part of EJB lite (EJB 3.1 specification, table 27), and embeddable containers are only required to provide EJB lite (EJB 3.1 specification, section 22.3.1).


text:
Q: Express Routing HTML5 Style CatchAll Conundrum no HASHBangs - Angular JS, Yeoman Hi I'm at the very beginning stages of a new project.
I am going to be using yeomans modern workflow tools for the front end, angular js work.
Backend written in node.js using express. I do not want to create any html on the server, it is all to be served to the client statically and then accessible via a RESTful service written in express where the magic of the angular js application will create the dynamic content. The app is to be one-page. As its one page there will need to be a catchall rule for views.
Currently I have the typical structure of:
app.js
public < dir containing the static html, js, css etc.
 index.html
 scripts
 styles
 views

I have found that most people render html server side and then have angular or whatever framework to provide further content. People typically use jade templating on the server to serve content, I do not see the need for this as all content is going to be very dynamic.
Yeoman's workflow is so simple and powerful I do not want to disturb this. For many reasons when you add a new route yeoman adds the js reference to the bottom of the index.html, due to templating being a different syntax I cannot use yeoman for this.
I also like the seperation of concerns in this architecture as well. The express installation primarily focuses on the RESTful service and has no control over the presentation and then the /public folder serves the presentation which is provided by using express.static(PATH).
I can happily use hashbangs for routing but its not so trivial for html5 pushstate.
My issue is with the routing on catch all. The trouble I'm finding is to effectively redirect all traffic that is not under the /api resource url. Whilst not interrupting assets being replaced with the index.html.
app.get(url('/person/lesson/:id'), api.getLesson);

app.all('*', routes.index);

I have tried:
routes.index = function(req,res){
res.sendfile('./public/dist/index.html');
};

routes.index = function(req,res){
res.redirect('/');
};

A: By putting static routes and other predefined routes ahead of your catchall code below, this will work.
app.get('*', function(req, res){
  res.sendFile(__dirname + '/public/index.html');
});

Note however that if you are using static routes, say for a /public/ folder mapped to /, those routes need to be referenced in your HTML using absolute references (i.e. "/css/styles.css" not "css/styles.css").  If you use relative URLs (without the /), then the reference will be based off of the URI and fall into the catchall because of that relative URL not being defined.

A: Put your API routes (get, post, delete, etc.) before the catch. There's no need to redirect.
app.get('*', function(req, res){
  res.sendfile('public/index.html');
});

There's nothing else to it.


text:
Q: How to restore a svn reverted file in Ubuntu I did some changes to some of the files checked out from a svn repo and mistakenly did a svn revert and all my changes was gone. Is there a way to restore my changes back?

A: No, absolutely NO.
If you say to Subversion it should revert a file, all changes are gone by the wind.
Only your memory can get them back.
Exception: New files you had added, will only lose their status "added", but the file will remain in this directory, only status is unknown("?")
Source


text:
Q: Randomly Replacing Values in a Data Frame I am working with the R programming language. Suppose I have the following data frame:
a = rnorm(100,10,1)
b = rnorm(100,10,5)
c = rnorm(100,10,10)
d = as.factor(sample( LETTERS[1:3], 100, replace=TRUE, prob=c(0.5, 0.3, 0.2) ))

my_data = data.frame(a,b,c,d)

 head(my_data)
          a         b          c d
1 12.433326 10.573004   2.586044 A
2  9.985524  8.903590  25.806358 C
3  9.538077 13.875609 -11.572231 C
4  9.342444  6.483715   4.056420 B
5  8.825197  8.633457   6.357470 A
6  9.121292  7.988194  15.999959 B

My Question : For any row

*

*Where "d = A", I want to randomly replace column "a" with 0 20% of the time, column "b" with 0 30% of the time and column "c" with 0 50% of the time

*Where "d = B", I want to randomly replace column "a" with 0 50% of the time, column "b" with 0 60% of the time and column "c" with 0 50% of the time

*Where "d = C", I want to randomly replace column "a" with 0 20% of the time, column "b" with 0 15% of the time and column "c" with 0 20% of the time
I could do this using base R in a very ineffective way:
A <- my_data[which(my_data$d == "A"), ]
B <- my_data[which(my_data$d == "B"), ]
C <- my_data[which(my_data$d == "C"), ]

A$a_new <- sample( LETTERS[1:2], nrow(A), replace=TRUE, prob=c(0.2, 0.8) )
A$b_new <- sample( LETTERS[1:2], nrow(A), replace=TRUE, prob=c(0.3, 0.7) )
A$c_new <- sample( LETTERS[1:2], nrow(A), replace=TRUE, prob=c(0.5, 0.5) )

A$a_new2 = ifelse(A$a_new == "A", A$a, 0)
A$b_new2 = ifelse(A$b_new == "B", A$b, 0)
A$c_new2 = ifelse(A$b_new == "C", A$c, 0)

B$a_new <- sample( LETTERS[1:2], nrow(B), replace=TRUE, prob=c(0.5, 0.5) )
B$b_new <- sample( LETTERS[1:2], nrow(B), replace=TRUE, prob=c(0.6, 0.4) )
B$c_new <- sample( LETTERS[1:2], nrow(B), replace=TRUE, prob=c(0.5, 0.5) )

B$a_new2 = ifelse(B$a_new == "A", B$a, 0)
B$b_new2 = ifelse(B$b_new == "B", B$b, 0)
B$c_new2 = ifelse(B$b_new == "C", B$c, 0)

C$a_new <- sample( LETTERS[1:2], nrow(C), replace=TRUE, prob=c(0.2, 0.8) )
C$b_new <- sample( LETTERS[1:2], nrow(C), replace=TRUE, prob=c(0.15, 0.85) )
C$c_new <- sample( LETTERS[1:2], nrow(C), replace=TRUE, prob=c(0.8, 0.2) )

C$a_new2 = ifelse(C$a_new == "A", C$a, 0)
C$b_new2 = ifelse(C$b_new == "B", C$b, 0)
C$c_new2 = ifelse(C$b_new == "C", C$c, 0)

final = rbind(A,B,C)

head(final)
           a         b         c d a_new b_new c_new   a_new2    b_new2 c_new2
1  12.433326 10.573004  2.586044 A     A     B     B 12.43333 10.573004      0
5   8.825197  8.633457  6.357470 A     B     B     B  0.00000  8.633457      0
7   9.594164 10.600787 27.190108 A     B     A     B  0.00000  0.000000      0
10  8.441369  1.944389 11.250866 A     B     A     B  0.00000  0.000000      0
11  9.192280 13.970166 -2.829124 A     B     B     A  0.00000 13.970166      0
12  9.916996 12.970319  3.472191 A     B     A     A  0.00000  0.000000      0

Does anyone know if there is a more efficient way to solve this problem? Perhaps it could be done with the DPLYR library and the mutate() function?
Thanks!

A: Here is a solution using the tidyverse (in particular, purrr and dplyr). My strategy:

*

*Define the replacement probabilities for each value of d.

*Split the data based on the value of d.

*Use purrr::map2() to iterate over each sub-data-frame and replacement probability vector, and do the appropriate replacements. Caution: you must make sure the order of everything is consistent - that is, the order of a, b, and c with relation to the replacement probabilities, and also the order of the split data in step 2 to the order of the probability vectors in step 1.

*Merge the results back into a single data frame.
library(tidyverse)

replacement_probs = list(
  A = c(0.2, 0.4, 0.5),
  B = c(0.5, 0.6, 0.5),
  C = c(0.2, 0.15, 0.2)
)

updated_data = my_data %>%
  split(.$d) %>%
  map2(replacement_probs, function(sub_data, probs) {
    d = sub_data$d
    map2_df(
      select(sub_data, a, b, c),
      probs,
      function(x, p) {
        x[sample(length(x), length(x) * p)] = 0
        x
      }
    ) %>%
      mutate(d = d)
  }) %>%
  reduce(bind_rows)

The output:
# A tibble: 1,000 x 4
       a     b     c d
   <dbl> <dbl> <dbl> <fct>
 1  9.05  0     0    A
 2 11.6   7.15  0    A
 3  8.65  7.31  0    A
 4  0     0     8.26 A
 5  0     4.61  0    A
 6 10.3   0    21.4  A
 7 11.9  19.1   0    A
 8  9.19  9.42  0    A
 9  9.54 13.5   0    A
10  9.34  7.08  0    A
# ... with 990 more rows

We could verify our work by splitting the data by d again and counting the number of zeros. Note that I changed the sample size to 1000 to make it clear that it worked.
updated_data %>%
  split(.$d) %>%
  map(~ map_dbl(.x, ~ sum(.x == 0) / length(.x)))

# Output
$A
        a         b         c         d
0.1983806 0.3987854 0.5000000 0.0000000

$B
        a         b         c         d
0.4983389 0.5980066 0.4983389 0.0000000

$C
        a         b         c         d
0.2000000 0.1463415 0.2000000 0.0000000

A: This is similar but without nesting or the need for mapping.
Reproducible random data:
set.seed(42)
my_data <- local({
  a = rnorm(100,10,1)
  b = rnorm(100,10,5)
  c = rnorm(100,10,10)
  d = as.factor(sample( LETTERS[1:3], 100, replace=TRUE, prob=c(0.5, 0.3, 0.2) ))
  data.frame(a,b,c,d)
})
head(my_data)
#           a         b          c d
# 1 11.370958 16.004827 -10.009292 A
# 2  9.435302 15.223755  13.337772 A
# 3 10.363128  4.983957  21.713251 B
# 4 10.632863 19.242410  30.595392 A
# 5 10.404268  6.666133  -3.768616 B
# 6  9.893875 10.527569  -1.508556 A

Produce another frame with probabilities per-column/per-group:
otherframe <- data.frame(d = c("A", "B", "C"), prob_a = c(0.2, 0.5, 0.2), prob_b = c(0.3, 0.6, 0.15), prob_c = c(0.5, 0.5, 0.2))
otherframe
#   d prob_a prob_b prob_c
# 1 A    0.2   0.30    0.5
# 2 B    0.5   0.60    0.5
# 3 C    0.2   0.15    0.2

Its use. First, I'll (re)use a function from another answer:
# adapted from https://stackoverflow.com/a/70402493/3358272
my_func2 <- function(x, prop, def = 0) replace(x, sample(length(x), size = ceiling(prop * length(x)), replace = FALSE), def)

out <- left_join(my_data, otherframe, by = "d") %>%
  group_by(d) %>%
  mutate(
    a = my_func2(a, prob_a[1]),
    b = my_func2(b, prob_b[1]),
    c = my_func2(c, prob_c[1])
  ) %>%
  ungroup() %>%
  select(-prob_a, -prob_b, -prob_c)
out
# # A tibble: 100 x 7
#        a     b     c d
#    <dbl> <dbl> <dbl> <chr>
#  1 11.4   0     0    A
#  2  9.44 15.2   0    A
#  3 10.4   4.98 21.7  B
#  4 10.6   0     0    A
#  5  0     0     0    B
#  6  0    10.5   0    A
#  7  0     7.89  2.94 B
#  8  9.91  9.39  0    A
#  9 12.0  10.9   3.54 A
# 10  9.94 10.6   0    B
# # ... with 90 more rows

And validation that the proportion of 0s makes sense.
out %>%
  group_by(d) %>%
  summarize(across(a:c, ~ sum(abs(.) < 1e-12) / n()))
# # A tibble: 3 x 4
#   d         a     b     c
#   <chr> <dbl> <dbl> <dbl>
# 1 A     0.208 0.302 0.509
# 2 B     0.517 0.621 0.517
# 3 C     0.222 0.167 0.222


text:
Q: numpy change array values when mask is one i'm new to numpy and i'm running into trouble.
I've got two numpy arrays, img and thr:
>>>img.shape
(2448, 3264, 3)
>>>thr.shape
(2448, 3264)

And i want to do something like this: set img[x,y] = [255,255,255] only when thr[x,y] is not 0
I tried iterating over the array and do it myself but it takes a long time, so i really need the C underneath numpy. I also took a look to masked arrays but i didn't understand how to use them.
Thanks!

A: Using NumPy assignment to an indexed array:
img[thr != 0] = [255,255,255]


text:
Q: MySQL INSERT after JOIN I have two tables as shown below.
table1

site | Link type
-----+----------
 A   | pdf
 B   | html
 C   | NULL
 D   | NULL

Table2

site | link type
-----+----------
 C   | htm
 D   | doc

This is the result I want:
site | link type
-----+----------
 A   | pdf
 B   | html
 C   | htm
 D   | doc

I want an insert query to insert the values of link type from table 2 to table 1
where link type is null joined with the condition with of table1.site = table2.site.
I tried:
INSERT INTO table1(linktype)
SELECT linktype FROM table1 t1
JOIN table2 t2
ON t1.site=t2.site

I want a insert query. as update query is working and want to know how a insert can be done?

A: Edit: Completely edited after clarification:
Creation of table1:
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `table1`;
CREATE TABLE `table1` (
  `site` varchar(250) DEFAULT NULL,
  `linktype` varchar(250) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table1` VALUES ('A', 'pdf');
INSERT INTO `table1` VALUES ('B', 'html');
INSERT INTO `table1` VALUES ('C', null);
INSERT INTO `table1` VALUES ('D', null);

Creation of table2:
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `table2`;
CREATE TABLE `table2` (
  `site` varchar(250) DEFAULT NULL,
  `linktype` varchar(250) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table2` VALUES ('C', 'htm');
INSERT INTO `table2` VALUES ('D', 'doc');

Insert query:
INSERT INTO
    table1
    (site, linktype)
    (
       SELECT
           table2.site,
           table2.linktype
       FROM
           table2
       JOIN
           table1
       ON
           table1.site = table2.site
   )
;

Table1 after insert query:


text:
Q: botones dinamicos - obtener el Id del boton presionado desde javascript Tengo un vista, que de manera dinámica, crea varios elementos del tipo Button de la siguiente manera:
@foreach (PacienteSeleccionDispensarDto paciente in @Model)
{
<input type="button" name="btnPaciente"             id="btn_@paciente.IdPaciente"
value="@paciente.NombrePaciente" onclick="fnProcesaPaciente()" />
}

en el evento onclick, puse la función fnProcesaPaciente, en la cual necesito rescatar el id del boton que presiono el usuario, y estaba intentando de la siguiente manera
 var PacienteId = $(this.data("id"));

pero al parecer esto no sirve, porque los botones se crean en una vista parcial, no en la vista principal (no se si esto tendrá alguna incidencia).
como puedo saber el Id del boton presionado?
Saludos

A: Si añade una función al evento onClick del Botón envíele por parámetro dicho botón así será más fácil capturar el valor desde la función haciendo uso de la palabra reservada this
<input type="button" name="btnPaciente"         id="btn_@paciente.IdPaciente"
value="@paciente.NombrePaciente" onclick="fnProcesaPaciente(this)" />

Para luego desde su función capturar el valor , accediendo al atributo id de comp que sería el botón que se dio click
function fnProcesaPaciente(comp){
  let id = comp.id;
  console.log(id);
}

JQUERY
Haciendo uso del método on(evento,componente,function) para que escuché el evento click que se realice en todos los controles Input de type=button, si se da el evento accedemos al id del elemento mediante la palabra reservada this que hace referencia al control que se dio click y a la propiedad id.

$(function() {
 $(document).on('click', 'input[type="button"]', function(event) {
    let id = this.id;
 console.log("Se presionó el Boton con Id :"+ id)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" name="e" value="e" id="idn1">
<input type="button" name="e" value="e" id="idn2">
<input type="button" name="e" value="e" id="idn3">
<input type="button" name="e" value="e" id="idn4">


text:
Q: ERROR: admin.E108 and admin.E116 Django Framework Python I got the these two errors below:

<class 'blog.admin.CommentAdmin'>: (admin.E108) The value of
'list_display[4]' refers to 'active', which is not a callable, an
attribute of 'CommentAdmin', or an attribute or method on
'blog.Comment'.

<class 'blog.admin.CommentAdmin'>: (admin.E116) The value of
'list_filter[0]' refers to 'active', which does not refer to a Field.

This is my models.py code:
from django.contrib.auth.models import User

# Create your models here.

STATUS = (
   (0,"Draft"),
   (1,"Publish")
)

class Post(models.Model):
   title = models.CharField(max_length=200, unique=True)
   slug = models.SlugField(max_length=200, unique=True)
   author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
   updatedOn = models.DateTimeField(auto_now= True)
   content = models.TextField()
   createdOn = models.DateTimeField(auto_now_add=True)
   status = models.IntegerField(choices=STATUS, default=0)

   class Meta:
       ordering = ['-createdOn']

   def __str__(self):
       return self.title

class Comment(models.Model):
   post = models.ForeignKey(
       Post, on_delete=models.CASCADE, related_name='comments')
   name = models.CharField(max_length=80)
   email = models.EmailField()
   body = models.TextField()
   createdOn = models.DateTimeField(auto_now_add=True)
   status = models.BooleanField(default=False)

   class Meta:
       ordering = ['createdOn']

   def __str__(self):
       return 'Comment {} by {}'.format(self.body, self.name)

This is my admin.py code:
from django.contrib import admin
from .models import Post, Comment

# Register your models here.

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'status','createdOn')
    list_filter = ("status", 'createdOn')
    search_fields = ['title', 'content']
    prepopulated_fields = {'slug': ('title',)}

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('name', 'body', 'post', 'createdOn', 'active')
    list_filter = ('active', 'createdOn')
    search_fields = ('name', 'email', 'body')
    actions = ['approveComments']

    def approveComments(self, request, queryset):
        queryset.update(active=True)

admin.site.register(Post, PostAdmin)

This is my forms.py code:
from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

Any help is greatly appreciated.

A: status = models.IntegerField(choices=STATUS, default=0)

should be:
active = models.IntegerField(choices=STATUS, default=0)

A: The message is clear 'active' is not a field
class Comment(models.Model):
   post = models.ForeignKey(
       Post, on_delete=models.CASCADE, related_name='comments')
   name = models.CharField(max_length=80)
   email = models.EmailField()
   body = models.TextField()
   createdOn = models.DateTimeField(auto_now_add=True)
   status = models.BooleanField(default=False)

your fields are: post, name, email, createdOn, status
Therefore create a field named active or suppress active in list_display &
list_filter

A: I got the same error below:

ERRORS: <class 'store.admin.PersonAdmin'>: (admin.E116) The value of
'list_filter[0]' refers to 'PersonAgeFilter', which does not refer to
a Field.

When assigning the custom filter PersonAgeFilter to list_filter() with parentheses as shown below:
# "store/admin.py"

from django.contrib import admin
from .models import Person

class PersonAgeFilter(admin.SimpleListFilter):
    # ...

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_filter = ("PersonAgeFilter",)
                 # ↑  Parentheses  ↑

So, I removed the parentheses from "PersonAgeFilter" as shown below then the error was solved.
# "store/admin.py"

from django.contrib import admin
from .models import Person

class PersonAgeFilter(admin.SimpleListFilter):
    # ...

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_filter = (PersonAgeFilter,)
                 # Without parentheses


text:
Q: JAXB - an element with unbounded maxOccurs inside an xsd:all Suppose I have the following java class that maps to the request-body of my REST service to search users.
@XmlRootElement(name = "SearchParams")
@XmlType(propOrder = {})
public class SearchParams {

  private String firstname;
  private String lastname;
  private List<String> role;

  ...
}

Note the propOrder parameter of the @XmlType annotation - it declares that the order in which representing individual attributes appear in an XML file does not matter and thus an xsd:all should be used instead of xsd:sequence in the generated XSD schema.
However, as you can see, one of the attributes (the role attribute) is a list and thus corresponds to an element with an unbounded maxOccurs.
It seems that an element with an unbounded maxOccurs is not allowed within an xsd:all complexType. How do I avoid this problem?
Note that, unlike role, the firstname and lastname have maxOccurs of 1. I therefore cannot use an unbounded xsd:choice instead of xsd:all either.

A: Assuming you can still modify this model, you could just wrap the role list in its own type, so you would end up with a <roles> element with a list of <role>s
<SearchParams>
    <firstname>firstname</firstname>
    <lastname>lastname</lastname>
    <roles>
        <role>role</role>
    </roles>
</SearchParams>

xsd would just be
<xsd:schema ... >

    <xsd:element name="SearchParams">
        <xsd:complexType>
            <xsd:all>
                <xsd:element name="firstname" type="xsd:string" />
                <xsd:element name="lastname" type="xsd:string" />
                <xsd:element name="roles" type="Roles" />
            </xsd:all>
        </xsd:complexType>
    </xsd:element>

    <xsd:complexType name="Roles">
        <xsd:sequence>
            <xsd:element name="role" type="xsd:string" maxOccurs="unbounded" />
        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>

And you'd have two classes. The Roles class containing the list. IMO, this is a cleaner approach. (you could just make Roles anonymous, but then you'd be stuck with a static inner class)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {

})
@XmlRootElement(name = "SearchParams")
public class SearchParams {

    @XmlElement(required = true)
    protected String firstname;
    @XmlElement(required = true)
    protected String lastname;
    @XmlElement(required = true)
    protected Roles roles;
    ...
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Roles", propOrder = {
    "role"
})
public class Roles {

    @XmlElement(required = true)
    protected List<String> role;
    ...
}

UPDATE

"If I could change the model class this way than this would look like a great way to solve this issue. Unfortunately I am only allowed to change the annotations"

You could use @XmlList.
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {

})
@XmlRootElement(name = "SearchParams")
public class SearchParams {

    @XmlElement(required = true)
    protected String firstname;
    @XmlElement(required = true)
    protected String lastname;
    @XmlList
    @XmlElement(required = true)
    protected List<String> role;
    ...
}

xsd would look like
<xsd:element name="SearchParams">
    <xsd:complexType>
        <xsd:all>
            <xsd:element name="firstname" type="xsd:string" />
            <xsd:element name="lastname" type="xsd:string" />
            <xsd:element name="role">
                <xsd:simpleType>
                    <xsd:list itemType="xsd:string" />
                </xsd:simpleType>
            </xsd:element>
        </xsd:all>
    </xsd:complexType>
</xsd:element>

Note: As noted here, this method is a "dangerous", the solution in the beginning of my post is preferred over using a list of string types. But in your specific case, not sure if I see another way


text:
Q: Mean of every nth element of swift array I have an array, where I want the mean of every nth element, starting from a specific element (in this case every 4th, starting at 1). What's the fastest way to do this?
My current method is a for loop with a looping switch statement, but I want to know if there's a quicker way.
I wondered if something like this could work:
let num_array = [1,2,3,4,5,6,7,8]
let mean4th = num_array[Array(stride(from: 1, to: num_array.count, by: 4))].reduce(0, +) / (num_array.count / 4)

Hoping to get mean4th = 3 (i.e. (1 + 5)/2)
This returns the error
Cannot subscript a value of type 'Array<UInt8>' with an index of type 'Array<Int>'

..which I'm struggling to get around

A: I don't understand what you meant by Hz in your comments but one way to do it is to generate the indices of all the elements you are going to visit and iterate from there:
let num_array = [1,2,3,4,5,6,7,8]
let indices = Array(stride(from: 0, to: num_array.count, by: 4))

let mean = Double(indices.reduce(0) { $0 + num_array[$1] }) / Double(indices.count)

A: The array cannot use a sequence as its subscript but you could write it differently
  let mean4th = stride(from: 0, to: num_array.count-1, by: 4).reduce(0) {$0 + num_array[$1] } / (num_array.count / 4)

The idea of using indices (Code Different) is on the right track, but on very large arrays, building the temporary indices array is adding to the processing time ( 5 times longer on a 500K element array )
The times I get on a MacBook Pro for 500K (in the playground) is 0.41 ms which is well below the 16.7 ms needed for 60Hz. You probably are doing more that just this average computation though so the faster the better.


text:
Q: Locating row in DataView using primary key How to locate index of DataViewRow in DataView using primary key
WITHOUT disturbing current sort order (which is not primary key) ?
I have grid control that displays contents of DataView. One row in this
grid is selected. When I have to change sort I wish to retain selected
row under new sort order. So, idea is to get primary key of selected
DataViewRow before new sort order is set and locate that same primary
key under new sort order.
Currently, I have to search DataView manually for specific primary key.
Is there a better way to do this ?
Solution with index positions instead of primary keys will do also.

A: I think I found most appropriate way to solve this, so if
anyone is interested here it is:
DataView's Find method locates row fast using current sort order.
Problem with that is that sort key generally does not identify
every row with unique sort key. So this to work we have to
adapt sort key to be unique for every row. This could be simply
accomplished by adding primary key to end of sort expression.
That way all sort keys that are not unique will be additionally
sorted by their primary key and that will make sort key unique
and preserve sort order at the same time. Here's an example:
Let's say we have loaded DataTable:
id  last_name  first_name  date_of_birth
----------------------------------------
11  Rogers     Samuel      1968-08-17
12  Smith      John        1952-12-25
13  Johnson    Bob         1981-03-29
14  Smith      John        1977-02-08
15  Adams      David       1971-09-15
----------------------------------------

// set primary key for DataTable

table.PrimaryKey = new DataColumn[] { table.Columns[ "id" ] };

// create first sorting order by last and first name
// but make sort unique by adding primary key at end

DataView view1 = new DataView( table );
view1.Sort = "last_name, first_name, id";

// create second sorting order by date of birth and again
// make sort unique by adding primary key at end

DataView view2 = new DataView( table );
view2.Sort = "date_of_birth, id";

// get DataRow of DataTable with primary key 14

DataRow row = table.Rows.Find( 14 );

// using data from DataRow find matching sort key

// be aware that Find method of DataView could return -1
// if DataView has filter set that hides row you search

int index_in_view1 = view1.Find( new Object[] { row[ "last_name" ],
                                                row[ "first_name" ],
                                                row[ "id" ] } );

int index_in_view2 = view2.Find( new Object[] { row[ "date_of_birth" ],
                                                row[ "id" ] } );

If anyone has any objection to this solution I would really be
interested to hear.


text:
Q: Why does getting a firestore collection work correctly in a vuex action, but the updated data is not passed to the getter? I have a collection of products stored in Firestore, each of which has a subcollection of product prices (the documents of this collection are generated through the Stripe for Firebase plugin, as an aside).
I am attempting to retrieve this list of products through a Vuex action, like so:
export default createStore({
  state: {
    productList: [],
  },
  mutations: {
    setProductList(state, value) {
      state.productList = value;
    },
  },
  actions: {
    async retrieveProducts({ commit }) {
      let productList = []; //init empty list
      //query all active products
      const q = query(collection(db, "products"), where("active", "==", true));
      const querySnapshot = await getDocs(q); //get product documents
      querySnapshot.forEach(async (doc) => {
        // for each document, map data in a useful way to productList
        let product = doc.data();
        product.id = doc.id;

        product.priceList = []; // init empty pricelist

        const priceSnap = collection(db, "products/", doc.id, "/prices"); //prepare to get all documents in the price subcollection

        let priceDocs = await getDocs(priceSnap); // retrieve the pricelist
        priceDocs.forEach((doc) => {
          // format each document's data
          let price = doc.data();
          price.id = doc.id;
          // add price data to product PriceList
          product.priceList.push(price);
        });

        productList.push(product);
        // add finished product object to product List
      });
      commit("setProductList", productList); // send productList to requester
      console.log("Product List: ", productList); //verify productList integrity
    },
  },
  getters: {
    getProductList(state) {
      return state.productList;
    },
  },
});

When the action is run, the final console.log shows the correctly formatted productList variable. However, on the Vue side, where this request takes place, it returns with an empty Array.
The request looks like this:
 async mounted() {
    await this.$store.dispatch({
      type: "retrieveProducts",
    });

    this.pList = this.$store.getters.getProductList;
    console.log("pList length: ", this.pList.length)
    console.log("Pricing.Vue: ",this.pList)
    if (this.pList.length > 0) {
      console.log("great success");
    } else {
      console.log("error loading product list.");
    }
  }

The especially confusing part is that if I omit the second getDocs and not query the sub-collection, this code functions correctly.
I'm at a total loss for what is not working correctly here.


text:
Q: ssh localhost without password not working for Mac OS X 10.9.1 I am trying to setup hadoop on my mac and a pre requisite for that is to be able to ssh into local host without password. Here are the steps that i took
osxltrsingh:~ rsingh$ rm -rf .ssh/
osxltrsingh:~ rsingh$ sudo systemsetup -setremotelogin on
Password:
setremotelogin: remote login is already On.
osxltrsingh:~ rsingh$ ssh-keygen -t rsa -P ""
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/rsingh/.ssh/id_rsa):
Created directory '/Users/rsingh/.ssh'.
Your identification has been saved in /Users/rsingh/.ssh/id_rsa.
Your public key has been saved in /Users/rsingh/.ssh/id_rsa.pub.
The key fingerprint is:
5e:24:e9:f7:de:bc:73:29:63:da:8d:f2:00:0b:07:f1 rsingh@osxltrsingh.corp.appdynamics.com
The key's randomart image is:
+--[ RSA 2048]----+
|       .         |
|        o.       |
|       .oE.      |
|       ..o       |
|       .Soo      |
|       .ooo.     |
|        .. ..   .|
|           oo*+..|
|           .*+*= |
+-----------------+
osxltrsingh:~ rsingh$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
osxltrsingh:~ rsingh$ ssh localhost
The authenticity of host 'localhost (::1)' can't be established.
RSA key fingerprint is d2:c2:ed:68:d9:7c:d0:11:de:72:51:ff:49:4f:aa:23.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (RSA) to the list of known hosts.
Password:

As you can see, it still asks for a password. Is there anything i am missing here. I tried to find the problem on google but i don't see what am i doing wrong. Any help is deeply appreciated.
The verbose output for ssh is
osxltrsingh:~ rsingh$ ssh -v localhost
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.
debug1: identity file /Users/rsingh/.ssh/id_rsa type 1
debug1: identity file /Users/rsingh/.ssh/id_rsa-cert type -1
debug1: identity file /Users/rsingh/.ssh/id_dsa type -1
debug1: identity file /Users/rsingh/.ssh/id_dsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.2
debug1: match: OpenSSH_6.2 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA d2:c2:ed:68:d9:7c:d0:11:de:72:51:ff:49:4f:aa:23
debug1: Host 'localhost' is known and matches the RSA host key.
debug1: Found key in /Users/rsingh/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/rsingh/.ssh/id_rsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Trying private key: /Users/rsingh/.ssh/id_dsa
debug1: Next authentication method: keyboard-interactive
Password:


text:
Q: spring-boot configure non exposed properties I am using spring-boot to configure jms and activemq connectivity. Due to a defect in activemq I need to set the idle timeout on the PooledConnectionFactory. This configuration is not exposed by spring-boot. How do I set it?
I have a @Bean to create a messageListenerContainer which has the connectionFactory as an argument. I can instanceof check the factory and configure it here but this seems not the correct way.

A: Downcasting to PooledConnectionFactory and calling setIdleTimeout is a perfectly reasonable approach, in my opinion.
If you'd prefer not to do it as part of the creation of the message listener container, you could declare your own ConnectionFactory bean while still making use of ActiveMQProperties. Something like this:
@Configuration
@EnableConfigurationProperties(ActiveMQProperties.class)
class CustomActiveMQConnectionFactoryConfiguration {

    @Autowired
    private ActiveMQProperties properties;

    @Bean
    public ConnectionFactory jmsConnectionFactory() {
        ConnectionFactory connectionFactory = this.properties.createConnectionFactory();
        if (connectionFactory instanceof PooledConnectionFactory) {
            ((PooledConnectionFactory) connectionFactory).setIdleTimeout(1000);
        }
        return connectionFactory;
    }
}


text:
Q: Biblatex: "reading" style is showing the "references in source" of my bib entries As i'm about to make an annotated bibliography, I'm using the "reading" style of Biblatex to show it, and the output is pretty good but there is one problem left : the output shows the reference in source of my bib entries.
For instance, if I have in my bib file something like that :
@book{ReferenceInSource1,
   author="Doe, John",
   title="Original title",
}

The output will show "Doe: Original title" as heading of the entry in the bibliography (that's ok), but also "ReferenceInSource1".
Is there a way to hide the "ReferenceInSource1" ?

A: Use the entrykey=false option:
\usepackage[backend=biber,style=reading,entrykey=false]{biblatex}


text:
Q: Null Pointer Exception, Works on Windows Computers I am creating a very basic 2D game in java, and I wrote it on my desktop which is running Windows 7. I then exported my project to my Macbook and got the following error:
Exception in thread "Thread-0" java.lang.NullPointerException
at java.awt.Component$FlipBufferStrategy.getDrawGraphics(Component.java:4115)
at scripps.rpg.Game.render(Game.java:86)
at scripps.rpg.Game.run(Game.java:107)
at java.lang.Thread.run(Thread.java:722)

I uploaded the exact same code onto a laptop running Windows 7 and it works there, so I know its not localized onto my computer. Here is the code that's relevant to the Stack-trace.
The error is g = buffer.getDrawGraphics(); , in the code I put >>>> <<<<<< around it
package scripps.rpg;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import scripps.states.GameState;
import scripps.states.MenuState;
import scripps.states.State;

//A separate instance of the game, Runnable allows it to be on a new thread
public class Game implements Runnable {

private Display display;

private int width;
private int height;
public String title;

private boolean running = false; //Used to control the game update
private Thread thread;  //Creates a new thread object

private BufferStrategy buffer;
private Graphics g;

private BufferedImage test;
private SpriteSheet sheet;

//States of the game
private State gameState;
private State menuState;

//Input
public KeyManager keyManager;

//Camera
private GameCamera gameCamera;

//Handler
private Handler handler;

//Gives the game the height, width, and title
public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
}

//initializes everything in the game
private void init(){

    display = new Display(title,width, height);
    display.getFrame().addKeyListener(keyManager);
    Assets.init();

    //Sets the camera with the default x and y values of 0,0

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0,0);
    handler = new Handler(this);

    menuState = new MenuState(handler);
    gameState = new GameState(handler);
    State.setSate(gameState); //sets the state to the game state
}

//Updates the gameworld but does NOT render it
private void tick(){
    keyManager.tick();
    if(State.getState() != null){
        State.getState().tick();
    }
}

//Renders all the objects on the screen
private void render(){

        buffer = display.getCanvas().getBufferStrategy(); //sets the display to the image set in the display
        //Checks to see if there is already a way to determine the buffer, if not it creates one with 3 'screens'
        if(buffer == null){
            display.getCanvas().createBufferStrategy(3);
            return;
        }

        // >>>>>>>>>>>>>>>> HERE <<<<<<<<<<<<<<<
        g = buffer.getDrawGraphics();  // <<<<<<<<<<
        // >>>>>>>>>>>>>>>> HERE <<<<<<<<<<<<<<<

        //Clears the screen of any previous drawings
        g.clearRect(0, 0, width, height);

        //Ensures that there is currently a state to the game
        if(State.getState() != null){
            State.getState().render(g);
        }
        //Shows the screen and empties anything saved in the graphics variable
        buffer.show();
        g.dispose();
    }

//Method required to allow the game to take place in a separate thread
public void run() {
    init();

    while(running == true){
        tick();
        render();
        try { Thread.sleep(1000/60); } catch (InterruptedException e) {}
    }
    stop(); //Stops the thread
}

//Getter for the KeyManager class
public KeyManager getKeyManager(){
    return keyManager;
}

public GameCamera getGameCamera(){
    return gameCamera;
}

//Getters for the height and width
public int getWidth(){
    return width;
}

public int getHeight(){
    return height;
}

//Starts the new thread
public synchronized void start(){

    //Doesn't execute code below as game is already running
    if(running == true){
        return;
    }
    running = true;
    thread = new Thread(this);
    thread.start();
}

//closes the new thread
public synchronized void stop(){
    //Doesn't execute code below as game is not running
    if(running ==false){
        return;
    }
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

Display Class:
    //Manages all the displays and windows
package scripps.rpg;

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Display {

private JFrame frame;
private Canvas canvas;

private String title;
private int width ;
private int height;
public  Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
}

//Creates the JFrame display and sets up the specs of it
public void createDisplay(){
    frame = new JFrame(title);
    frame.setSize(width,height); //sets display to the height declared previously
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null); //puts display at center of screen
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width, height));
    canvas.setMaximumSize(new Dimension(width, height));
    canvas.setMinimumSize(new Dimension(width, height));
    canvas.setFocusable(false);

    frame.add(canvas);
    frame.pack();

}

//Getter to get the private variables in this class, could also have made the variables public
public Canvas getCanvas(){
    return canvas;
}

//Getter for JFrame
public JFrame getFrame(){
    return frame;

}
}

If anyone would be able to help that would be greatly appreciated!


text:
Q: How to call two different functions after one click of an onClick button I trying to get two different functions to be called when an onClick button is clicked.
<button id="button" type="button" onClick={write, message}>
    RESERVE ROOM
  </button>

my write function looks like:
const write = () => {
var AWS = require("aws-sdk");
let awsConfig = {
    "region": "us-west-2",
    "endpoint": "http://dynamodb.us-west-2.amazonaws.com",
    "accessKeyId": "AKIATXDQF3UYRZVGEAEG", "secretAccessKey": "4azvTl67U8QW1id0j8***/rAOqmEp4ajnKFb9***"
};
AWS.config.update(awsConfig);

let docClient = new AWS.DynamoDB.DocumentClient();

let save = function () {

  var fullname = document.getElementById('name').value;
  var cap = document.getElementById('selectcap').value;
  var date = document.getElementById('meetingdate').value;
  var time = document.getElementById('selecttime').value;
  var room = document.getElementById('selectroom').value;
  var duration = document.getElementById('selectduration').value;

    var input = {
      "resID": 2, "Capacity": cap, "Date": date, "Duration": duration, "roomID": room, "Time": time, "FullName": fullname
    };
    var params = {
        TableName: "Reservations",
        Item:  input
    };
    docClient.put(params, function (err, data) {

        if (err) {
            console.log("users::save::error - " + JSON.stringify(err, null, 2));
        } else {
            console.log("users::save::success" );
        }
    });
}

save();
};

The message function:
const message = () => {
document.getElementById("bodyid").innerHTML = "ROOM HAS BEEN
RESERVED!";
 };

The write function writes data inputted into a form in my data table. message just displays a message after the button is clicked.

A: Just encapsulate them in a single callback:
<button id="button" type="button" onclick="reserveRoom()">
    RESERVE ROOM
</button>

function reserveRoom() {
  [write, message].forEach(x => x());
}


text:
Q: Executing dynamic SQL with return value as a column value for each rows I have a rather simple query that I started to modify in order to remove temp table as we have concurrency issues over many different systems and clients.
Right now the simple solution was to break up the query in multiple separate queries to replicate what SQL was doing before.
I am trying to figure out a way to return the result of a dynamic SQL query as a column value. The new query is quite simple, it look in the system objects for all table with specific format and output. What i am missing is that for each record i need to output the result of a dynamic query on each of those table.
The query :
SELECT [name] as 'TableName'
FROM SYSOBJECTS WHERE xtype = 'U'
AND (CHARINDEX('_PCT', [name]) <> 0
OR CHARINDEX('_WHT', [name]) <> 0)

All these table have a common column called Result which is a float. What i am trying to do is return the count of this column under some WHERE clause that is generic and will work will all tables as well.
A desired query (i know it's not valid) would be :
SELECT [name] as 'TableName',
sp_executesql 'SELECT COUNT(*) FROM ' + [name] + ' WHERE Result > 0 OR (Result < 139 AND CurrentIndex < 15)' as 'ResultValue'
FROM SYSOBJECTS WHERE xtype = 'U'
AND (CHARINDEX('_PCT', [name]) <> 0
OR CHARINDEX('_WHT', [name]) <> 0)

Before it used to be easy. We had a temp table with 2 columns and were filling the table name first. Then we iterate on the temp table and execute the dynamic sql and return the value in an OUTPUT variable and simply update the record of the temp table and finally return the table.
I have tried a scalar function but it doesn't support dynamic SQL so it doesn't work. I would rather not create the 13,000~ different queries for the 13,000~ tables.
I have tried using a reference table and use trigger to update the status but it slow the system way to much. The average tables insert and delete 28 millions records. The original temp table query only took 5-6 minutes to execute due to very good indexing and now we are reaching 25-30 minutes.
Is there any other solution available than Querying the table list then the Client query each table one by one to know it status ?
We are using SQL Server 2017 if some new features are available now

A: You can use this script for your purpose (tested in SQL Server 2016).
Updated: It should work now as the results are a single set now.
EXEC sp_msforeachtable
@precommand = 'CREATE TABLE ##Statistics
    (TableName varchar(128) NOT NULL,
    NumOfRows int)',
@command1 ='INSERT INTO ##Statistics (TableName, NumOfRows)
    SELECT ''?'' Table_Name, COUNT(*) Row_Count FROM ? WHERE Result > 0 OR (Result < 139 AND CurrentIndex < 15)',
@postcommand = 'SELECT TableName, NumOfRows FROM ##Statistics;
    DROP TABLE ##Statistics'
,@whereand = ' And Object_id In (Select Object_id From sys.objects
    Where name like ''%_PCT%'' OR name like ''%_WHT%'')'

For more details on sp_msforeachtable Please visit this link


text:
Q: jQuery's draggable() function isn't working Here's a JSFiddle I have: http://jsfiddle.net/o5tupLcb/.
My problem is, why isn't the div dragging? Even if I make $(".drag").draggable(); its own statement outside of the switch statements, it doesn't work.
Here's some jQuery:
$(document).ready(function() {
    $(".drag").mousedown(function(e) {
        switch (e.which) {
        case 1:
            $(this).toggleClass("mousedown");
            $(this).draggable(); /* This probably shouldn't be here */
        case 2:
            break;
        case 3:
            break;
        default:
            break;
        }
    });

    $(".drag").mouseup(function(e) {
        switch (e.which) {
        case 1:
            $(this).toggleClass("mousedown");
            $(this).draggable(); /* This probably shouldn't be here */
        case 2:
            break;
        case 3:
            break;
        default:
            break;
        }
    });
});

Please note that I already tried to import jQuery UI and nothing happened.
Edit: Turns out I was importing the wrong thing. Also, the draggable() function works better when I take it out of the switch statements and just put it below.

A: Cleaned up your code on jsfiddle, included jQuery and jQuery UI.  Also changed html to be only:

Hello

Now works (after first click).  This makes sense since the event is fired after you first click (and again after you release).
http://jsfiddle.net/o5tupLcb/1/


text:
Q: how to call the function in array? I'm trying to call the function
int Even( int a[][MAX_COLUMNS], int length, int width)

inside the main to print the output to the user.
After running the program, i got the following error

`int Even(int,int,int) connot convert argument 1 from int [3][2] to int

Here's the code,
Thank you for taking the time to help me.
#include <iostream>
#define MAX_ROWS 3
#define MAX_COLUMNS 2

using namespace std;

int  Even(int A, int length, int width);

int main(){

    int A[MAX_ROWS][MAX_COLUMNS] = { { 3, 2 }, { 4, 5 }, { 2, 2 } };

    cout << "There are " << Even(A,MAX_ROWS,MAX_COLUMNS) << " even numbers in the matrix." << endl;
        cout << "Goodbye :-)" << endl;

    system("PAUSE");
    return 0;

}

int Even( int a[][MAX_COLUMNS], int length, int width){

    int sum = 0;
    int i;
    int j;

    for (i = 0; i < length, i++;){

        for (j = 0; j < width, j++;){

            if (a[i][j]  % 2 == 0){

                sum++;
            }
        }

    }

    return sum;

}

A: You should alwais avoid forward declaration (except special cases).  At your Q it leaded you to error. Full code:
#include <iostream>
#define MAX_ROWS 3
#define MAX_COLUMNS 2

using namespace std;

int Even( int a[][MAX_COLUMNS], int length, int width){

    int sum = 0;
    int i;
    int j;

    for (i = 0; i < length, i++;){

        for (j = 0; j < width, j++;){

            if (a[i][j]  % 2 == 0){

                sum++;
            }
        }

    }

    return sum;

}

int main(){

    int A[MAX_ROWS][MAX_COLUMNS] = { { 3, 2 }, { 4, 5 }, { 2, 2 } };

    cout << "There are " << Even(A,MAX_ROWS,MAX_COLUMNS) << " even numbers in the matrix." << endl;
    cout << "Goodbye :-)" << endl;

    system("PAUSE");
    return 0;

}


text:
Q: AppleScript - Expected end of line etc. But found classname (-2741) I am new to Mac application development and our existing Mac application contains an AppleScript that handles all the Microsoft Word operations. When i build the solution via XCode in Catalina MacOS that do not have Microsoft Word installed in it, it is throwing a build error as "Expected end of line etc. But found classname (-2741)" .
The error is thrown exactly in the line of code shown below

When i build the same solution in Mojave MacOS that has Microsoft Installed in it then it is working fine without any build errorsand the build is getting succeeded.
Can you please suggest on how to handle the AppleScript such that the solution gets build without any errors irrespective of Microsoft Word installed or not? This is of high priority and needs to be fixed at the earliest.


text:
Q: Jeresy List of Object[] response There is a way to return POJO conatins List of array of objects from jersey web service as a response?
If this is my POJO:
@xmlRootElement
Public class Test implements Serializable {

    private List<Object[]> entities;

    public List<Object[]> getEntities() {
        return entities;
    }

    public void setEntities(List<Object[]> entities){
         this.entities = entities;
    }

}

It seems that jersey is able to marshall the response but unable to unmarshall it back at the client side.
This is the Exception Im getting at the client side:
java.lang.NullPointerException: null
at com.sun.org.apache.xalan.internal.xsltc.trax.SAX2DOM.startElement(SAX2DOM.java:200) ~[na:1.6.0_45]
at com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler.closeStartTag(ToXMLSAXHandler.java:204) ~[na:1.6.0_45]
at com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler.characters(ToXMLSAXHandler.java:524) ~[na:1.6.0_45]
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerHandlerImpl.characters(TransformerHandlerImpl.java:168) ~[na:1.6.0_45]
at com.sun.xml.bind.v2.runtime.unmarshaller.DomLoader.text(DomLoader.java:143) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.text(UnmarshallingContext.java:499) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.text(InterningXmlVisitor.java:93) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.processText(StAXStreamConnector.java:339) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleEndElement(StAXStreamConnector.java:217) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:186) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:366) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:345) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalJAXBElementFromJSON(BaseJSONUnmarshaller.java:108) ~[jersey-json-1.12.jar:1.12]
at com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalFromJSON(BaseJSONUnmarshaller.java:97) ~[jersey-json-1.12.jar:1.12]
at com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.readFrom(JSONRootElementProvider.java:129) ~[jersey-json-1.12.jar:1.12]
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:111) ~[jersey-core-1.12.jar:1.12]
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:554) ~[jersey-client-1.12.jar:1.12]
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:506) ~[jersey-client-1.12.jar:1.12]
at com.audiocodes.ms.control.strategy.cms.CMSStrategy.getSystemInfo(CMSStrategy.java:172) ~[bin/:na]
at com.audiocodes.ms.control.actors.SystemActor.getSystemInfo(SystemActor.java:69) [bin/:na]
at com.audiocodes.ms.control.actors.SystemActor.onReceive(SystemActor.java:33) [bin/:na]
at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:159) [akka-actor_2.10-2.1.2.jar:na]
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:425) [akka-actor_2.10-2.1.2.jar:na]
at akka.actor.ActorCell.invoke(ActorCell.scala:386) [akka-actor_2.10-2.1.2.jar:na]
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:230) [akka-actor_2.10-2.1.2.jar:na]
at akka.dispatch.Mailbox.run(Mailbox.scala:212) [akka-actor_2.10-2.1.2.jar:na]
at akka.dispatch.ForkJoinExecutorConfigurator$MailboxExecutionTask.exec(AbstractDispatcher.scala:506) [akka-actor_2.10-2.1.2.jar:na]
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:262) [scala-library-2.10.1.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:975) [scala-library-2.10.1.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1478) [scala-library-2.10.1.jar:na]
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104) [scala-library-2.10.1.jar:na]

Im using jersey 1.12.
Does anyone know where is my problem?
Thanks.


text:
Q: Release apk install/update app from google play The following is the situation:
I have an app, that I have published to the Google Play store (version code: 100, version name 1.100).
I want to add feature allow people to update the app using an apk(release) from a website instead of from the Play Store.
BUT during testing I found the following problem:

*

*Download current app from store(v - 100)

*after that try to install(update) using the APK I compile

*result - "App not installed."

But if I

*

*install a hand created old APK (exactly the same as was uploaded to the Store)

*try to install a handcreated APK update that was uploaded to the store

*everything works fine

CAN you please describe there're some limits additional checkers for security or something wrong on my side ?

A: You are probably signed into Google Play App Signing.
Every Android app is signed with a key. When the phone tries to install an update, the update must be signed with the same key as the original app. This is for the security of the user. This stops a fake version of WhatsApp or Facebook (or your app) being created and users tricked into installing it. A bad developer can create an app with the same package name, but doesn't have access to the key, so this protects the users.
When you deliver through Google Play App Signing, Google removes the signature with your key (the "upload key") and signs it with a new Google Play key. This is a good thing. It protects you if you lose your upload key, without this there would be nothing Google could do to help you.
But this is why the upgrade doesn't happen. The app you hand create is signed with your upload key, so it won't update the app installed from Google Play.
This is a good thing. You don't want users who installed from one source (eg Google Play) to update from another source, like a download from a website. It would put them at serious risk of harmful fake apps.
However, if you really want to do this, you need to not use Google Play App Signing.

A: An alternative solution:
You can upload your signed apk on google play console then download the new signed apk and put it on your website or anywhere else.


text:
Q: Genexus Ev2 Stored procedure I'm trying to call a stored procedure on my iSeries System (RPG program) but I'm not able to activate the corresponding menu under "tools"->"Java Generator".
The RPG program that I want to call (we'll name it RPG00) has 5 input parameters and 1 output value.
I performed the following operations:

*

*Create an "external object" (type: stored procedure) whose name is "RPG00"

*Create a method named "RPG00" as well in the external object above and set the "external name" property to "RPG00"

*Create a Web Panel with a variable &test (type: external object RPG00) and call it with the right parameters

*Change the following settings in iSeries datastore configuration:

*

*"access technology to set" --> JDBC

*"list of external stored procedure" --> RPG00

At this point if i try to build the KB, it ends up always in error. In the project folder i can't find the "crtjdccalls.java" file and the corresponding "class" file that stores the instructions for the stored procedure..
What's going wrong? Any idea? Any suggestion?
The appropriate element in the "Java generator" menu never appears!!
My Configuration:

*

*Gx Ev2 U5

*Environment: Web\Java

*DB: iSeries 6.1

A: I think you forgot set the data store property (JDBC) 'Library list' with the name of the library in which the RPG progrma RPG00 is found.
Check this and make a rebuild all.
Regards, Luis.

A: Thanks to the Genuxs development team I found a solution!
The problem is related to the way parameters are passed to the stored procedure.
REMEBER:

*

*You can't use SDT elements as input parameters

*You can't use direct values as input parameters

*YOU CAN USE ONLY VARIABLES!!!
E.G.
SDT.value1, SDT.value2
&variable1 = SDT.value1
&variable2 = SDT.value2
&RPG00.RPG00(SDT.value1, SDT.value2, ecc) --> ERROR
&RPG00.RPG00(&variable1, XXX, ecc) --> ERROR where XXX is for example an integer value
&RPG00.RPG00(&variable1, &variable2, ecc) --> ONLY VARIABLES WORK FINE!!

Hope this help someone else


text:
Q: put random position set of number with conditional repeat I have this set of number a=[1 2 3]. And I want to put this number randomly into matrix 7 x 1, and number 1 must have 2 times, number 2 must have 3 times and number 3 must have 2 times.
The sequence is not necessary. The answer look like.
b=[1 2 2 2 1 3 3]'

A: Try randperm:
a=[1 2 3];
samps = [1 1 2 2 2 3 3]; % specify your desired repeats
samps = samps(randperm(numel(samps))); % shuffle them
b = a(samps)

Or, instead of specifying samps explicitly, you can specify the number of repetitions for each element of a and use arrayfun to compute samps:
reps = [2 3 2];
sampC = arrayfun(@(x,y)x*ones(1,y),a,reps,'uni',0);
samps = [sampC{:}];
samps = samps(randperm(numel(samps))); % shuffle them
b = a(samps)

A: %how often each value should occure
quantity=[2,2,3]
%values
a=[1,2,3]
l=[]
%get list of all values
for idx=1:numel(a)
 l=[l,ones(1,quantity(idx))*v(idx)]
end
%shuffle l
l=l(randperm(numel(l)))


text:
Q: Calculate average for column value within a time interval I have dataframe
                        id      timestamp               data    gradient        Start
timestamp
2020-01-15 06:12:49.213 40250   2020-01-15 06:12:49.213 20.0    0.00373         NaN
2020-01-15 06:12:49.313 40251   2020-01-15 06:12:49.313 19.5    0.00354         0.0
2020-01-15 08:05:10.083 40256   2020-01-15 08:05:10.083 20.0    0.00020         1.0
2020-01-15 08:05:10.183 40257   2020-01-15 08:05:10.183 20.5    -0.00440        0.0
                            ...
2020-01-31 09:01:50.993 40310   2020-01-31 09:01:50.993 21.0    0.55473         1.0
2020-01-31 09:01:51.093 40311   2020-01-31 09:01:51.093 21.5    0.00589         0.0
                            ...

I want to find the average of data that lie between start_time ==1 and 30 seconds later.
Reproducible example:
d = {'timestamp':["2020-01-15 06:12:49.213", "2020-01-15 06:12:49.313", "2020-01-15 08:05:10.083", "2020-01-15 08:05:10.183", "2020-01-15 09:01:50.993", "2020-01-15 09:01:51.093", "2020-01-15 09:51:01.890", "2020-01-15 09:51:01.990", "2020-01-15 10:40:59.657", "2020-01-15 10:40:59.757", "2020-01-15 10:42:55.693", "2020-01-15 10:42:55.793", "2020-01-15 10:45:35.767", "2020-01-15 10:45:35.867", "2020-01-15 10:45:46.770", "2020-01-15 10:45:46.870", "2020-01-15 10:47:19.783", "2020-01-15 10:47:19.883", "2020-01-15 10:47:22.787"],
'data': [20.0, 19.5, 20.0, 20.5, 21.0, 21.5, 22.0, 22.5, 23.0, 23.5, 23.0, 22.5, 23.0, 23.5, 24.0, 24.5, 25.0, 25.5, 26],
'gradient': [NaN, NaN, 0.000000, 0.000148, 0.000294, 0.000294, 0.000339, 0.000339, 0.000334, 0.000334, 0.000000, -0.008618, 0.000000, 0.006247, 0.090884, 0.090884, 0.010751, 0.010751, 0.332889],
'Start': [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,]
}

df = pd.DataFrame(d)

Expected output:
start_time               end_time                   Average
2020-01-15 08:05:10.083  2020-01-15 09:01:51.093    20.25  = average of (20.0, 20.5)
2020-01-15 10:45:35.767  2020-01-15 10:45:35.767    23.75  = average of (23.0, 23.5, 24.0, 24.5)

Edit:
Using @jezrael's code:
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['g'] = df['Start'].cumsum()

df1 = df[df['g'].ne(0)].copy()
#
s = df1.groupby('g')['timestamp'].transform('first')
df1 = df1[df1['timestamp'].between(s, s + pd.Timedelta(30, 's'))]
#
df2 = df1.groupby('g').agg(start_time=('timestamp','first'),
                           end_time=('timestamp','last'),
                           Average=('data','mean')).reset_index(drop=True)
print (df2)

I obtained output

It seems that some start and end time are very close, around 0.1second difference. This is a fault in the data collecting device which recorded 2 data points every time, instead of 1, and the data points have a 0.5 difference for data. In addition, there are very few data points, which caused the the start and end time to be very close for a 30 seconds time interval. My question is, is it possible if we forward fill the sample? So that there is more data to measure.

A: Get first timestamp per groups by GroupBy.transform and GroupBy.first then compare by Series.between:
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['g'] = df['Start'].cumsum()

df1 = df[df['g'].ne(0)].copy()
#
s = df1.groupby('g')['timestamp'].transform('first')
df1 = df1[df1['timestamp'].between(s, s + pd.Timedelta(30, 's'))]
#
df2 = df1.groupby('g').agg(start_time=('timestamp','first'),
                           end_time=('timestamp','last'),
                           Average=('data','mean')).reset_index(drop=True)
print (df2)
               start_time                end_time  Average
0 2020-01-15 08:05:10.083 2020-01-15 08:05:10.183    20.25
1 2020-01-15 10:45:35.767 2020-01-15 10:45:46.870    23.75

A: Try this code.
df['timestamp'] = pd.to_datetime(df['timestamp'])

start_time_list = []
end_time_list = []
average_list = []

for start_ind in df[df['Start'] == 1].index:
    end_ind = np.where(df['timestamp'] <= df.iloc[start_ind]['timestamp'] + pd.to_timedelta(30, unit = 's'))[0][-1] + 1
    average = df['data'].iloc[start_ind:end_ind].mean()

    start_time_list.append(df.iloc[start_ind]['timestamp'])
    end_time_list.append(df.iloc[end_ind]['timestamp'])
    average_list.append(average)

output = pd.DataFrame({"start_time":start_time_list,
                       "end_time":end_time_list,
                       "average":average_list})


text:
Q: React BrowserRouter routes with a parameter are not loading the CSS files I have a BrowserRouter set up in my main.js file and it switches between the desired pages when I visit the respective URLs
index.html
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/main.css" />

main.js
return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        <BrowserRouter>
          <Header />
          <Switch>
            <Route path="/ingredient">
              <IngredientPage />
            </Route>
            <Route path="/ingredientsList/:id" exact>
              <IngredientListPage />
            </Route>
            <Route path="/create-recipe">
              <CreateRecipe />
            </Route>
            <Route path="/list-recipes">
              <ListRecipes />
            </Route>
            <Route>
              <NotFound />
            </Route>
          </Switch>
          <Footer />
        </BrowserRouter>
      </DispatchContext.Provider>
    </StateContext.Provider>
  );

My issue is that the CSS files are loaded with the wrong URL whenever I visit a route that has a parameter.
Example 1 (expected)
I visit a route URL without a parameter http://localhost:3000/ingredient
The CSS files are successfully loaded e.g. http://localhost:3000/css/style.css and styling applied to the page
Example 2 (unexpected)
I visit a URL with a parameter http://localhost:3000/ingredientsList/1
The page loads but no styling is applied. CSS files are requested from the URL up to where the parameter is added e.g. http://localhost:3000/ingredientsList/css/style.css
Any idea what's causing the URL to change here and how it can be fixed?
EDIT:
Ok, I have it working now by hardcodeing the URL in the index.html
<link rel="stylesheet" href="http://localhost:3000/css/style.css" />
<link rel="stylesheet" href="http://localhost:3000/css/main.css" />

Not exactly ideal though as the base URL is now hardcoded

A: So the issue here is just that your css was being accessed from a relative path instead of the root path.
I bet your link looked like this:
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/main.css" />

Which will start at the current directory and then look for the css directory, so when you're in a deeper file path it's looking at the wrong place.
What you need is something like this:
<link rel="stylesheet" href="/css/style.css" />
<link rel="stylesheet" href="/css/main.css" />

The leading / says to go back to the root directory and then access the css directory from there.
The fact that it happened when you were on a parameter page might mean that your css href was "../css/main.css" or "./css/main.css" or something. In any case, changing it to what I've suggested should fix your problem without hardcoding the base url.


text:
Q: The proper AWS managed policy to attach an IAM Role to execute Lambda Functions So, I have created a role via AWS IAM service. Initially, it only has the AWS managed policy AWSAppSyncPushToCloudWatchLogs.
Now I want to make this role capable of executing Lambda functions and nothing more (You know, a good security structure should not permit a bit more from what is needed).
To do that which AWS managed policy(-ies) should I attach to the IAM Role?
PS: The role will be used by AWS AppSync, if this information is crucial.

A: You can attach managed policy, AWSLambdaRole. This grants permissions for your role to invoke any Lambda function.
policy statement
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "lambda:InvokeFunction"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

Please refer https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html#access-policy-examples-aws-managed for more details.


text:
Q: How to call ajax function on submitting form through javascript in android, phonegap and jquerymobile I have html form with two input fileds and submit button.
When i click on submit button it goes in my javascript function...but it does not call the ajax function written in it.
Instead of calling ajax function the page gets reloaded

A: You not only have to use event.preventDefault() (or return false) in your event handler but you have to specifically disable the AJAX navigation for the form so jQuery Mobile doesn't do it's own form submission:
Here is one way using data-ajax (recommended):
<form data-ajax="false">

You can also do this by changing a default of jQuery Mobile when the mobileinit event fires:
<script src="jQuery-Core.js"></script>
<script>
$(document).bind("mobileinit", function(){
   $.mobile.ajaxEnabled = false;
});
</script>
<script src="jQuery-Mobile.js"></script>

Notice the order of the <script> tags. The downside to this method is that it disables AJAX navigation for all elements, not just the single form you're dealing with, that's why I recommend using the data attribute: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/globalconfig.html

A: have you disabled your form submit action using
e.preventDefaults()

can you show some of your code ?