text:
Q: How to delete from a joined table in hibernate? Here's the code and what I'm trying to achieve is to remove a registration object from the registration table on delete. When I delete I want to remove it's corresponding certificate values in certificatesChosen table(which has primary keys id(from registration) and cid(from certificates)and the address objects.
Registration.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Registration" table="registrations">
        <meta attribute="class-description">
            This class contains the employee detail.
        </meta>
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="username" column="username" type="string" />
        <property name="password" column="password" type="string" />
        <property name="dob" column="dob" type="string" />
        <property name="email" column="email" type="string" />
        <property name="phone" column="phone" type="string" />
        <property name="registered" column="registered" type="string" />
        <set name="certifications" table="certificatesChosen" cascade="all">
            <key column="id" not-null="true" />
            <many-to-many column="certificationId" class="com.global.manager.Certifications"
                unique="true" />
        </set>
        <set name="address" table="address" cascade="all">
            <key column="id" not-null="true" />
            <one-to-many class="com.global.manager.Address" />
        </set>
    </class>
</hibernate-mapping>

Address.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Address" table="address">
        <meta attribute="class-description">
            This class contains the courses opted by student
        </meta>
        <id name="aid" type="int" column="aid">
            <generator class="native" />
        </id>
        <property name="type" column="type" type="string" />
        <property name="street" column="street" type="string" />
        <property name="city" column="city" type="string" />
        <property name="state" column="state" type="string" />
        <property name="country" column="country" type="string" />
        <property name="pin" column="pin" type="int" />

        <many-to-one name="registration" class="com.global.manager.Registration"
            fetch="select" insert="false" update="false">
            <column name="id" not-null="true" />
        </many-to-one>
        <!-- <many-to-one name="student" class="com.global.hibernate.Student" column="regnId"
            not-null="true" /> -->

    </class>
</hibernate-mapping>

Certifications.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Certifications" table="certifications">
        <meta attribute="class-description">
            This class contains the courses opted by student
        </meta>
        <id name="cid" type="int" column="certificationId">
        </id>
        <property name="name" column="certificationName" type="string" />
        <join table="certificatesChosen" inverse="true">
            <key column="certificationId" />
            <many-to-one name="registrations" column="id" not-null="true" />
        </join>
    </class>
</hibernate-mapping>

deleteUser.java(where I actually delete a registration object)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username =request.getParameter("username");
        DBHelper.deleteStudent(username);

    }

DBHelper.java
public class DBHelper
{
    public static void deleteStudent(String username) {
    System.out.println("inside dbhelper");
        try {

            Configuration cfg = new Configuration().configure();
            SessionFactory sf = cfg.buildSessionFactory();

            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Registration.class).add(Restrictions.eq("username", new String(username)));
            List <Registration> details = criteria.list();
            session.delete(details.get(0));
            tx.commit();
            session.close();
        }catch(HibernateException e) {
            e.printStackTrace();
        }
    }
}

I'm sending the username from a jsp page and on execution this is the error log:
2017-12-15T18:46:01.902+0530|Severe: [http-thread-pool(5)] ERROR org.hibernate.util.JDBCExceptionReporter - Cannot delete or update a parent row: a foreign key constraint fails (`Jpa`.`certificatesChosen`, CONSTRAINT `certificatesChosen_ibfk_2` FOREIGN KEY (`certificationId`) REFERENCES `certifications` (`certificationId`))
2017-12-15T18:46:01.903+0530|Severe: [http-thread-pool(5)] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
2017-12-15T18:46:01.905+0530|Severe: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
    at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2650)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2895)
    at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at com.global.manager.DBHelper.deleteStudent(DBHelper.java:90)
    at com.global.manager.deleteUser.doGet(deleteUser.java:36)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1693)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)

Please let me know if the mappings are right and if it's a rigth way to delete in a DBHelper. Would greatly appreciate your help. Thanks!


text:
Q: cannot create cluster plugin did not respond vsphere_compute_cluster.compute_cluster_create\[0\]: Creating...
vsphere_compute_cluster.compute_cluster_create\[1\]: Creating...
╷
│ Error: Plugin did not respond
│
│   with vsphere_compute_cluster.compute_cluster_create\[0\],
│   on main.tf line 102, in resource "vsphere_compute_cluster" "compute_cluster_create":
│  102: resource "vsphere_compute_cluster" "compute_cluster_create" {
│
│ The plugin encountered an error, and failed to respond to the plugin.(\*GRPCProvider).ApplyResourceChange call. The plugin logs may contain more details.
╵
╷
│ Error: Plugin did not respond
│
│   with vsphere_compute_cluster.compute_cluster_create\[1\],
│   on main.tf line 102, in resource "vsphere_compute_cluster" "compute_cluster_create":
│  102: resource "vsphere_compute_cluster" "compute_cluster_create" {
│
│ The plugin encountered an error, and failed to respond to the plugin.(\*GRPCProvider).ApplyResourceChange call. The plugin logs may contain more details.
╵

Stack trace from the terraform-provider-vsphere_v2.1.0_x5 plugin:

panic: interface conversion: interface {} is \*schema.Set, not \[\]interface {}

goroutine 57 \[running\]:
github.com/hashicorp/terraform-provider-vsphere/vsphere.updateVsanDisks(0xc000284e80, 0xc000283100, 0x14542e0, 0xc000777d60, 0x0, 0x0)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vsphere/resource_vsphere_compute_cluster.go:1264 +0x1945
github.com/hashicorp/terraform-provider-vsphere/vsphere.resourceVSphereComputeClusterApplyCreate(0xc000284e80, 0x14542e0, 0xc000777d60, 0x1, 0x1, 0x2d)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vsphere/resource_vsphere_compute_cluster.go:726 +0x549
github.com/hashicorp/terraform-provider-vsphere/vsphere.resourceVSphereComputeClusterCreate(0xc000284e80, 0x14542e0, 0xc000777d60, 0x5, 0xffffffffffffffff)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vsphere/resource_vsphere_compute_cluster.go:513 +0xdd
github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.(\*Resource).create(0xc000202620, 0x1a0ed68, 0xc0004c4a40, 0xc000284e80, 0x14542e0, 0xc000777d60, 0x0, 0x0, 0x0)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go:318 +0x1ee
github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.(\*Resource).Apply(0xc000202620, 0x1a0ed68, 0xc0004c4a40, 0xc0007fbd50, 0xc00007aa00, 0x14542e0, 0xc000777d60, 0x0, 0x0, 0x0, ...)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go:456 +0x67b
github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.(\*GRPCProviderServer).ApplyResourceChange(0xc0000b23f0, 0x1a0ed68, 0xc0004c4a40, 0xc00072fa90, 0xc0004c4a40, 0x16dd420, 0xc000550500)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/grpc_provider.go:955 +0x8ef
github.com/hashicorp/terraform-plugin-go/tfprotov5/server.(\*server).ApplyResourceChange(0xc00062dac0, 0x1a0ee10, 0xc0004c4a40, 0xc0007fbb20, 0xc00062dac0, 0xc000550570, 0xc000681ba0)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/server/server.go:332 +0xb5
github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5.\_Provider_ApplyResourceChange_Handler(0x16dd420, 0xc00062dac0, 0x1a0ee10, 0xc000550570, 0xc0004b1e00, 0x0, 0x1a0ee10, 0xc000550570, 0xc000574d80, 0xd23)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5_grpc.pb.go:380 +0x214
google.golang.org/grpc.(\*Server).processUnaryRPC(0xc0001aefc0, 0x1a18db8, 0xc000001980, 0xc0000e4e00, 0xc000344750, 0x238a480, 0x0, 0x0, 0x0)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/google.golang.org/grpc/server.go:1194 +0x52b
google.golang.org/grpc.(\*Server).handleStream(0xc0001aefc0, 0x1a18db8, 0xc000001980, 0xc0000e4e00, 0x0)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/google.golang.org/grpc/server.go:1517 +0xd0c
google.golang.org/grpc.(\*Server).serveStreams.func1.2(0xc00009e420, 0xc0001aefc0, 0x1a18db8, 0xc000001980, 0xc0000e4e00)
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/google.golang.org/grpc/server.go:859 +0xab
created by google.golang.org/grpc.(\*Server).serveStreams.func1
/opt/teamcity-agent/work/5d79fe75d4460a2f/src/github.com/hashicorp/terraform-provider-vsphere/vendor/google.golang.org/grpc/server.go:857 +0x1fd

Error: The terraform-provider-vsphere_v2.1.0_x5 plugin crashed!

This is always indicative of a bug within the plugin. It would be immensely
helpful if you could report the crash with the plugin's maintainers so that it
can be fixed. The output above should help diagnose the issue.
hello, i try to create a cluster in Vsphere, and it fails with error above
cluster is created in vsphere UI,
2022-04-05T09:34:01.248Z \[TRACE\] maybeTainted: vsphere_compute_cluster.compute_cluster_create\[0\] encountered an error during creation, so it is now marked as tainted

when i try to destroy, it destroys nothing

redpajama_set_name: RedPajamaStackExchange


text:
Q: Incapable of catching error in if clause (updated with answer) In this code below, $alb->error has an error message in it. I can verify this with echo, no problem.
The issue arises when I want to catch that error in an if clause. First, the code:
    if($action == "add")
    {
        //PUT CODE TO SAVE A NEW ALBUM HERE
        //SHOULD RETURN ALBUM ID
        $alb = new album();
        //fill object album with properties to be saved
        $alb->date = checkNull($_POST['alb_date']);
        $alb->name = checkNull($_POST['alb_name']);
        $alb->desc = checkNull($_POST['alb_desc']);
        $alb->cat_id = $_POST['categories'];
        //call save method of album
        $alb->create_album();

        //catch error
        if($alb->error <> "")
        {
            header("Location: add_album.php?error='$alb->error'");
        }

        //set album id to pass it along to add_pictures
        $alb_id = $alb->id;
    }
    elseif($action == "edit")
    {
        //PUT CODE TO SAVE EDITED ALBUM HERE
        //SHOULD RETURN ALBUM ID
    }

        header("Location: add_pictures.html?alb_id='$alb_id'");

After $alb->create_album(), $alb's error property is filled by omitting a required field in the input form. This is what I want. But then, I need to catch that error, and redirect the user to the previous page, where the error will be displayed.
Here's what I've tried so far:
    //catch error
    if(isset($alb->error))
    {
        header("Location: add_album.php?error='$alb->error'");
    }

Didn't work.
    //catch error
    if(!is_null($alb->error))
    {
    header("Location: add_album.php?error='$alb->error'");
    }

No cigar.
    //catch error
    if($alb->error <> "")
    {
        header("Location: add_album.php?error='$alb->error'");
    }

still, zero joy.
The if clause never gets processed. What am I missing?
Thank you for your time.

A: So the problem was that I had a header redirect after my outer if clause for the type of action: if action=add or edit. When I wrapped it in an else clause, it worked:
    }
    elseif($action == "edit")
    {
        //PUT CODE TO SAVE EDITED ALBUM HERE
        //SHOULD RETURN ALBUM ID
    }
    else
    {
        header("Location: add_pictures.html?alb_id='$alb_id'");
    }

Thanks for your help!!


text:
Q: Jaspersoft Studio complains class cast exception when using JRBeanCollectionDataSource I have a weird problem with Jaspersoft Studio and custom JRBeanCollectionDataSource.
Every time I try to access child object of parent object, I get exception like this:
net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : $F{test}.getFirst() + " " + $F{test}.getSecond()
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:466)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:441)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:333)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : $F{test}.getFirst() + " " + $F{test}.getSecond()
    at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:263)
    at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:611)
    at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:579)
    at net.sf.jasperreports.engine.fill.JRFillElement.evaluateExpression(JRFillElement.java:1016)
    at net.sf.jasperreports.engine.fill.JRFillTextField.evaluateText(JRFillTextField.java:504)
    at net.sf.jasperreports.engine.fill.JRFillTextField.evaluate(JRFillTextField.java:488)
    at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:259)
    at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:456)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillBandNoOverflow(JRVerticalFiller.java:467)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnHeader(JRVerticalFiller.java:512)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:294)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:152)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:963)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFiller.run(BaseFillHandle.java:120)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: mypacket.Test cannot be cast to mypacket.Test
    at Blank_A4_1403082997789_739077.evaluate(Blank_A4_1403082997789_739077:169)
    at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:250)
    ... 14 more

Here is relevant classes:
public class RootFactory {

    public static JRBeanCollectionDataSource get() {
        return new JRBeanCollectionDataSource(Arrays.asList(new RootClass(new Test())));
    }
}

public class RootClass {
    private Test test;

    public RootClass(Test test) {
        this.test = test;
    }

    public Test getTest() {
        return test;
    }

    public void setTest(Test test) {
        this.test = test;
    }
}

public class Test {

    private String first = "first";
    private String second = "second";

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getSecond() {
        return second;
    }

    public void setSecond(String second) {
        this.second = second;
    }
}

I've added classes to Jaspersoft Studio and added data adapter to use RootFactory.get() method and that seems to be working.
Field expression in jasper is $F{test}.getFirst() + " " + $F{test}.getSecond()
Weird thing is that jasper can't cast mypacket.Test to mypacket.Test.
Any clues how to solve this?

- Jaspersoft studio 5.6.0
- Java 1.7.0_11

Edit 1
Here is jrxml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version last-->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a333429d-13c8-4db0-849e-9ed3fa97af6e">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="TempFactory"/>
<queryString>
    <![CDATA[]]>
</queryString>
<field name="test" class="mypacket.Test"/>
<background>
    <band splitType="Stretch"/>
</background>
<title>
    <band height="79" splitType="Stretch"/>
</title>
<pageHeader>
    <band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
    <band height="61" splitType="Stretch">
        <textField>
            <reportElement x="0" y="0" width="555" height="61" uuid="0ca07834-5483-4ad5-a7fc-b415c2cce367"/>
            <textFieldExpression><![CDATA[$F{test}.getFirst() + " " + $F{test}.getSecond()]]></textFieldExpression>
        </textField>
    </band>
</columnHeader>
<detail>
    <band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
    <band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
    <band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
    <band height="42" splitType="Stretch"/>
</summary>
</jasperReport>

And if it does matter: I use osx 10.9.2.

A: I have faced similar exceptions in both 5.5.2 and 5.6, like ...cannot cast from T to T... where T always was a) the exact same type b) an own pojo derived fr JRAbstractBeanDataSource
I know this is not really a solution and think this probably should be filed to the Jasper guys... but just plain "restarting jasper studio" always helped :-/
One of many little things in studio...
Hope it kinda helps nonetheless

A: Restarting Jasper Studio did not work for me.
I think this is still a bug in Jasper Studio 6.0.4 standalone version. But when I install Studio software as an Eclipse plugin and preview the report from the Java project, it works fine without any problems.
The good thing is I can set the report to be backward compatible with Jasper Reports version 4.5.0 so it does not create the UUID elements all over the report every time I preview the report and the eclipse plugin also works with Java 8 SDK

A: For anyone coming to this thread and and still having the issue,
I managed to solve it in my case, by doing so:

*

*Right-click on the project -> "Build Path" -> "Configure Build path..."

*Navigate to "Order and Export" tab

*Uncheck "Jaspersoft Server Library" ("JRE System Library" must be checked though)

*Apply and close

*Restart Jasperstudio

*Go back to "Preview" and rerun the generation of the report

*Enjoy!

In fact, the problem was that different classes loaders were used to load the same class T:

*

*The default classloader from "JRE System Library"

*The one from "Jaspersoft Server Library"
You can confirm this by looking the error stacktrace in full (notice the different instances of the classloader, in bold):

Caused by: java.lang.ClassCastException: class <full.package.to.class.T> cannot be cast to class <full.package.to.class.T>(<full.package.to.class.T> is in unnamed module of loader java.net.FactoryURLClassLoader @7fe379ab; <full.package.to.class.T> is in unnamed module of loader java.net.FactoryURLClassLoader @4b9b57d9)


text:
Q: execute aws command using php I want to run a powershell script which contains a aws command, the command is for getting the ip address of currently running instances of aws. Via cmd I can get the currently running instances ip address by executing the executer.ps1 file.But ,through php the command is not get executed.In the executer.ps1 file I am calling python files also those are working fine.
this command is not working via UI,
aws ec2 describe-instances --instance-ids $id --query Reservations[].Instances[].PublicIpAddress

How to do this one ?
executer.ps1 file is,
Clear-Host
Clear-History
$Username = "**"
$Password = "***"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
$ips = @()

Write-Host "----------------------------------"

Try
{
    echo "Creating Instances will start now..."
    python C:\AWS\Distributed-setup-3\CreateInstance.py
}
Catch
{
    echo "Instance not created"
    exit
}

Write-Host "----------------------------------"

echo "Creating setup...."
Start-Sleep -Seconds 60

python C:\AWS\Distributed-setup-3\statusCheck.py

Start-Sleep -Seconds 60

$content = Get-Content C:\AWS\Distributed-setup-3\InstanceId.txt
echo $content

Write-Host "----------------------------------"

ForEach ($id In $content){
    echo "execute.ps1 id"
    echo $id
    $instances = aws ec2 describe-instances --instance-ids $id --query Reservations[].Instances[].PublicIpAddress
    $instance = $instances[1]
    $instance = $instance -replace '"' , ""
    $instance =  $instance.Trim()
    $ips = $ips+$instance
}

Write-Host "----------------------------------"

Clear-Content 'C:\AWS\Distributed-setup-3\ipconfig.txt'

ForEach ($i In $ips){
    #echo $i
    if($i -eq ($ips[0])){
        Write-Host "Master is "$i
    }
    else
    {
        Write-Host "Client "$i
        $index = [array]::indexof($ips,$i)
        $index = $index+1
        if($ips[$index] -eq $null){
            $i | Add-Content 'C:\AWS\Distributed-setup-3\ipconfig.txt'
        }
        else{
            $i = $i+","
            $i | Add-Content 'C:\AWS\Distributed-setup-3\ipconfig.txt'
        }
    }
}

Write-Host "----------------------------------"

aws s3 cp C://AWS/Distributed-setup-3/ipconfig.txt s3://s3merahkee
aws s3 cp C://AWS/Distributed-setup-3/Input.yaml s3://s3merahkee

Write-Host "----------------------------------"

Write-Host "Executing jmeter distributed test on remote system" $ips

Write-Host "----------------------------------"

ForEach ($ip In $ips){
   if($ip -eq ($ips[0])){
        #echo "Executing hub"
        Write-Host "Master ip is "$ip
   }
   else
   {
        #Write-Host "Executing slave "$ip
        Start-Job "C:\AWS\Distributed-setup-3\instance_2.ps1" -ArgumentList $ip
   }
}

Start-Sleep -Seconds 60

Write-Host "----------------------------------"

Get-job | Receive-Job

Write-Host "----------------------------------"

$hub = $ips[0]
echo -n "Executing Master :"$hub

Start-Sleep -Seconds 10
Invoke-Command -ComputerName $hub -ScriptBlock { cmd.exe /c C:\Users\Administrator\Desktop\gitclone.bat } -credential $Cred

Write-Host "----------------------------------"

ForEach ($ip In $ips){
    echo -n "Executing on remote system for reports " $ip
    Try
    {
        Invoke-Command -ComputerName $ip -ScriptBlock { cmd.exe /c C:\Users\Administrator\Desktop\report.bat } -credential $Cred
    }
    Catch{
        echo "Unable to connect check the remote connection permission"
    }
}

Write-Host "----------------------------------"

ForEach ($id In $content){
    $instances = aws ec2 describe-instances --instance-ids $id --query 'Reservations[].Instances[].PrivateIpAddress'
    $instance = $instances[1]
    $instance = $instance -replace '"' , ""
    $i =  $instance.Trim()
    #echo $i
    aws s3 cp  s3://s3merahkee/Logs/$i C:\AWS\Distributed-setup-3\Reports --recursive
    cd C:\AWS\Distributed-setup-3\Reports
    Rename-Item jmeter-server.log jmeter-server_$i.log
}

Write-Host "----------------------------------"

echo "Terminating instance"
ForEach ($id In $content){
   aws ec2 terminate-instances --instance-ids $id
}

Write-Host "----------------------------------"
Write-Host "Execution completed"

In trail.php, I am calling the executer.ps1 powershell script
<?php
        ini_set('max_execution_time', 500);
        $output= shell_exec('powershell -command C:/AWS/Distributed-setup-3/executer.ps1');

        echo( '<pre>' );
        echo( $output );
        echo( '</pre>' );
 ?>


text:
Q: JQuery - Toggling divs with only selectors If I have html such as:

        Toggle

Content1

        Toggle

Content2

How can I write a JQuery select/click event such that each link toggles the div below it?
$('#tags li a').click(function(){
    $('#tags '+this.parent()+' div').slideToggle();
});

Tried something like that but its not giving me the results. Any help?

A: $('#tags li a').click(function(){
    $(this).siblings("div").slideToggle();
});

or
$('#tags li a').click(function(){
    $(this).next("div").slideToggle();
});

A: $('#tags li a').click(function(){
  $(this).next('div').slideToggle();
});

A: [RE-EDIT]:

        toggle

Content1

        toggle

Content2

[OLD]:

Content1

Content2

Toggle


text:
Q: Lua print(table) em string (pegando todos seus valores) Criei um sistema rapidinho pra testar uma nova variável, mas não sei como faço pra ele imprimir os usuários inseridos na tabela, e quando vou dar print ele mostra isto: table: 0035AE18
Meu código:
Conta = {balance = 0}
Contas = {}
Senhas = {}
Inicial = 5000
function Conta:withdraw (v)
Conta.Balance = Conta.Balance - v
end

function Login()
io.write("Digite seu Usuario\n")
usuariol = io.read()
io.write("Digite sua senha\n")
senhal = io.read()

for i=0, #Contas do
for j=0, #Senhas do
if usuariol == Contas[i] and senhal == Senhas[j] then
io.write("Logado com sucesso!")
Cadastro()
end
end
end
end

function Cadastro()
io.write("Ola, seja bem vindo ao sistema de Banco 1.0 By Charles \n")
io.write("Deseja criar uma conta? \n")
resposta = io.read()

if resposta == "sim" or resposta == "Sim" then
io.write("Ok, informe seu nome de usuario \n")
usuario = io.read()
io.write("Informe sua senha \n")
senha = io.read()
io.write("Aguarde um instante!\n")
if #Contas == 0 and #Senhas == 0 then
table.insert(Contas, 1, usuario)
table.insert(Senhas, 1, senha)
else
table.insert(Contas, usuario)
table.insert(Senhas, senha)
end
Login()

elseif resposta == "tabela" then
print(#Contas)
print(#Senhas)
end
end

Cadastro()

O sistema funciona assim: ele cria a conta, depois você loga nele volta pra criação de conta.
Vamos supor criei 3 contas e depois na parte "você deseja criar conta" eu digitar "tabela" ele vai me mostrar o número de contas e senhas criadas.
Mas eu quero exibi-las não em tamanho capacidade e sim por string. Ex:
t = {'teste'}
print(t)

Console:

table: teste

A: Acho que é isto que você quer:
Conta = {balance = 0}
Contas = {}
Senhas = {}
Inicial = 5000
function Conta:withdraw (v)
    Conta.Balance = Conta.Balance - v
end

function Login()
    io.write("Digite seu Usuario\n")
    usuariol = io.read()
    io.write("Digite sua senha\n")
    senhal = io.read()

    for i=0, #Contas do
        for j=0, #Senhas do
            if usuariol == Contas[i] and senhal == Senhas[j] then
                io.write("Logado com sucesso!")
                Cadastro()
            end
        end
    end
end

function Cadastro()
    io.write("Ola, seja bem vindo ao sistema de Banco 1.0 By Charles \n")
    io.write("Deseja criar uma conta? \n")
    resposta = io.read()

    if resposta == "sim" or resposta == "Sim" then
        io.write("Ok, informe seu nome de usuario \n")
        usuario = io.read()
        io.write("Informe sua senha \n")
        senha = io.read()
        io.write("Aguarde um instante!\n")
        if #Contas == 0 and #Senhas == 0 then
            table.insert(Contas, 1, usuario)
            table.insert(Senhas, 1, senha)
        else
            table.insert(Contas, usuario)
            table.insert(Senhas, senha)
        end
        Login()

    elseif resposta == "tabela" then
        for i,v in ipairs(Contas) do
            print(v)
        end
        for i,v in ipairs(Senhas) do
            print(v)
        end
    end
end

Cadastro()

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Eu usei a técnica mais recomendada para varrer todo array mas você poderia usar a mesma que usou para verificar se usuário e senha estão cadastrados.
Acho que deveria rever a forma como estes dados estão armazenados.
Seu código vai trazer problemas de memória (falando a grosso modo) na forma como ele está organizado.
Existem alguns outros problemas mas acho que você ainda vai mexer bastante nele.


text:
Q: Android ViewGroup ticker I am developing an Android component that has the same functionality as a news Ticker. It's a ViewGroup that takes an array of Views and animate them to create the effect of a Ticker.
I have implemented the onMeasure and onLayout methods, and I have a timer that calls a method every X time to refresh the position of every View. It basically moves the position of every child by 5 pixels lets say.
Everything is working great so far, but the problem is that a few seconds after the Views start moving, they start to overlap on each others, as if some of them are going faster than others. I am moving all the Views with the same amount of pixels so they should be moving at the same speed. This problem only occurs on some devices (like the Galaxy SIII) and just works fine on others.
Any idea why this is happening?


text:
Q: Real Analysis: Given $A_1$, $A_2$, $A_3$, which set is open, which is closed? a. $A_1 = \{x: \sin(1/x) =0\}$
Clearly $\sin(1/x) = 0$ for $x = \frac{1}{n\pi}$, what can we say about this set?
b. $A_2 = \{x: x\sin(1/x)= 0 \}$
Again $\sin(1/x) = 0$ for $x = \frac{1}{n\pi}$, is there any difference between this set and $A_1$?
c. $A_3 = \{x: \sin(1/x) > 0 \}$
$\sin(\frac{1}{x}) > 0$ if $\frac{1}{x} > \sin^{-1} (0) $, so $x > 0$ is an open set. Am I correct?

A: The maps $f(x) =\sin(1/x)$ and $g(x)= x\sin(1/x)$ are continuous. Note that: $$A_1 = f^{-1}(\{0\}), \quad A_2 = g^{-1}(\{0\}), \quad A_3 = f^{-1}(\left[0,+\infty\right[).$$We have that $\{0\}$ is closed and $\left[0,+\infty\right[$ is open, so...


text:
Q: issue after pulling code [Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException] I just pulled some code on my prod environment. The changes is very little (I have added a {{ form_widget(meeting.text) }} in one of my html.twig page.
Nothing else.
Know when my server is down and the error I get when I load the page app_dev.php is the following:
ParameterNotFoundException in ParameterBag.php line 84:
You have requested a non-existent parameter "kernel.bundles_metadata".

I do not use any parameterbag.php in my code. I can't even find it! Same thing for the kernel.bundles_metadata. I cannot find it in my code.
Here is the full error:

in ParameterBag.php line 84
at ParameterBag->get('kernel.bundles_metadata') in bootstrap.php.cache line 1897
at Container->getParameter('kernel.bundles_metadata') in FrameworkExtension.php line 713
at FrameworkExtension->getValidatorMappingFiles(object(ContainerBuilder)) in FrameworkExtension.php line 665
at FrameworkExtension->registerValidationConfiguration(array('enable_annotations' => true, 'enabled' => true, 'static_method' => array('loadValidatorMetadata'), 'translation_domain' => 'validators', 'strict_email' => false), object(ContainerBuilder), object(XmlFileLoader)) in FrameworkExtension.php line 114
at FrameworkExtension->load(array(array('translator' => array('fallback' => 'en'), 'secret' => '******', 'router' => array('resource' => '/var/www/html/BDLCapital-v3/app/config/routing.yml', 'strict_requirements' => null), 'form' => null, 'csrf_protection' => null, 'validation' => array('enable_annotations' => true), 'templating' => array('engines' => array('twig')), 'default_locale' => 'en', 'trusted_proxies' => null, 'session' => null, 'fragments' => null, 'http_method_override' => true), array('router' => array('resource' => '/var/www/html/myAPP/app/config/routing_dev.yml', 'strict_requirements' => true), 'profiler' => array('only_exceptions' => false))), object(ContainerBuilder)) in MergeExtensionConfigurationPass.php line 59
at MergeExtensionConfigurationPass->process(object(ContainerBuilder)) in MergeExtensionConfigurationPass.php line 39
at MergeExtensionConfigurationPass->process(object(ContainerBuilder)) in Compiler.php line 102
at Compiler->compile(object(ContainerBuilder)) in ContainerBuilder.php line 568
at ContainerBuilder->compile() in bootstrap.php.cache line 2436
at Kernel->initializeContainer() in bootstrap.php.cache line 2215
at Kernel->boot() in bootstrap.php.cache line 2246
at Kernel->handle(object(Request)) in app_dev.php line 22

If you have any idea that would help me a lot!
I am using symfony 2.7.
EDIT: when I try to do sudo php app/console cache:clear I get the following message:
  [Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]
  You have requested a non-existent parameter "kernel.bundles_metadata".

thanks for your help


text:
Q: Storing the each output into a variable I have script here that will list the date that the user will enter and output the date  5 days ago.
#!/bin/bash
echo "What month?"
            echo "1 - January"
            echo "2 - February"
            echo "3 - March"
            echo "4 - April"
            echo "5 - May"
            echo "6 - June"
            echo "7 - July"
            echo "8 - August"
            echo "9 - September"
            echo "10 - October"
            echo "11 - November"
            echo "12 - December"
            echo ""
            echo -n "What month?  "
            read m

            if [ "$m" == "1" ]
            then
            mn="Jan "
            elif [ "$m" == "2" ]
            then
            mn="Feb "
            elif [ "$m" == "3" ]
            then
            mn="Mar "
            elif [ "$m" == "4" ]
            then
            mn="Apr "
            elif [ "$m" == "5" ]
            then
            mn="May "
            elif [ "$m" == "6" ]
            then
            mn="Jun "
            elif [ "$m" == "7" ]
            then
            mn="Jul "
            elif [ "$m" == "8" ]
            then
            mn="Aug "
            elif [ "$m" == "9" ]
            then
            mn="Sep "
            elif [ "$m" == "10" ]
            then
            mn="Oct "
            elif [ "$m" == "11" ]
            then
            mn="Nov "
            elif [ "$m" == "12" ]
            then
            mn="Dec "
            else
            echo "Invalid month"
            fi
            echo ""

            #DAY
            echo -n "What day? "
            read d
            if [ "$d" -lt "9" ]
            then
                    mnd="$mn"" ""$d"
            elif [ "$d"  -gt "31" ]
            then
                    mnd="1"
            else
                    mnd="$mn""$d"
            fi

 for dy in {0..4}; do
    date -d "$mn $d - $dy days" +'%b %_d'
 done

Output:
What month?
8
What day?
1

Aug  1
Jul 31
Jul 30
Jul 29
Jul 28

What I want now is to store each date in to variable for example
the first line must Aug 1 must be stored on variable x1
Jul 31 must be stored on variable x2 etc.. What I mean whatever output on the first list must be stored on x1 and so on.

A: Use an array instead of trying to create separate variables.
declare -a x

for dy in {0..4}; do
  x+=( "$( date -d "$mn $d - $dy days" +'%b %_d' )" )
done

You may then access the four values in ${x[0]} through to ${x[3]}.
For the first part of your script, have you considered using a select statement?
select mn in "Jan" "Feb" "Mar" "Apr" "May" "Jun" \
             "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
do
  if [[ -z "$mn" ]]; then
    echo "Invalid choice" >&2
  else
    break
  fi
done

printf "You selected '%s'\n" "$mn"

This does the following:
1) Jan    3) Mar   5) May   7) Jul   9) Sep  11) Nov
2) Feb    4) Apr   6) Jun   8) Aug  10) Oct  12) Dec
#? 56
Invalid choice
#? 5
You selected 'May'

The value of $mn will be the selected string (May for example).


text:
Q: PHP print problems hi I'm currently using a script to scan a directory for mp3 files and print the results with some other information surrounding each item found so i can populate a app that works fine however if i try to print something with <>  it doesn't show these
<?php
// *** requires PHP5 ***
// search for jpg files

$filter = ".mp3";
// url to be added to the path *** NO TRAILING SLASH ***
$url = 'http://********';
// path to the directory you want to scan
$directory = './';
$it = new RecursiveDirectoryIterator("$directory");
foreach(new

RecursiveIteratorIterator($it) as $file)
{
  if (!((strpos(strtolower($file), $filter)) === false))
  {
    $items[] = preg_replace(array("#\\\#", "#./#"), array("/", "/"), $file);
  }
}
sort($items);

print <<<END
<music>
END;

foreach($items as $item)
{
  $title_array = explode('/', $item);
  $title = substr(end($title_array), 0, (strlen(end($title_array)) - 4));
  print <<<END

new AudioTrack(new Uri("$url$item",UriKind.Absolute), "$title", null, null, null),

END;
}

print <<<END
</music>

END;

?>

the code that I'm now wanting it to print is the same except in the print section I'm after
<print ><item>
<title>$title</title>
<link>$url$item</link>
<description>album name</description>
<guid isPermaLink="false">$url$item</guid>
<enclosure type="audio/mpeg" url="$url$item" />
</item>

thanks in advance


text:
Q: Passing wrong type data to component's attributes in React? I'm using type alias with ReactJS and creating a component declared bellow
type PropsType = {
  viewModel: CalendarViewModel,
  onPressDate: void,
  text: string
};
class Calendar extends React.Component<PropsType> { }

The problem occurred when i started passing data to render this component. It still renders well when the "text" attribute receives both String and Number data type, but it's just declared to accept only string datatype. So what can i do to fix this?

A: You could pass either string or number
type PropsType = {
  text: string | number,
};


text:
Q: Php variable into a XML request string I have the below code wich is extracting the Artist name from a XML file with the ref asrist code.
<?php
    $dom = new DOMDocument();
    $dom->load('http://www.bookingassist.ro/test.xml');
    $xpath = new DOMXPath($dom);
    echo $xpath->evaluate('string(//Artist[ArtistCode = "COD Artist"] /ArtistName)');
    ?>

The code that is pulling the artistcode based on a search
<?php echo $Artist->artistCode ?>

My question :
Can i insert the variable generated by the php code into the xml request string ?
If so could you please advise where i start reading ...
Thanks

A: You mean the XPath expression. Yes you can - it is "just a string".
$expression = 'string(//Artist[ArtistCode = "'.$Artist->artistCode.'"]/ArtistName)'
echo $xpath->evaluate($expression);

But you have to make sure that the result is valid XPath and your value does not break the string literal. I wrote a function for a library some time ago that prepares a string this way.
The problem in XPath 1.0 is that here is no way to escape any special character. If you string contains the quotes you're using in XPath it breaks the expression. The function uses the quotes not used in the string or, if both are used, splits the string and puts the parts into a concat() call.
public function quoteXPathLiteral($string) {
  $string = str_replace("\x00", '', $string);
  $hasSingleQuote = FALSE !== strpos($string, "'");
  if ($hasSingleQuote) {
    $hasDoubleQuote = FALSE !== strpos($string, '"');
    if ($hasDoubleQuote) {
      $result = '';
      preg_match_all('("[^\']*|[^"]+)', $string, $matches);
      foreach ($matches[0] as $part) {
        $quoteChar = (substr($part, 0, 1) == '"') ? "'" : '"';
        $result .= ", ".$quoteChar.$part.$quoteChar;
      }
      return 'concat('.substr($result, 2).')';
    } else {
      return '"'.$string.'"';
    }
  } else {
    return "'".$string."'";
  }
}

The function generates the needed XPath.
$expression = 'string(//Artist[ArtistCode = '.quoteXPathLiteral($Artist->artistCode).']/ArtistName)'
echo $xpath->evaluate($expression);


text:
Q: How should I fix it? Only size-1 arrays can be converted to Python scalars I am making the following graph:
import matplotlib.pyplot as plt
import numpy as np
import math

def g(x):
    return np.exp(-10)*pow(10,x)/math.factorial(x)

x=np.linspace(0,100,100)
plt.plot(x,g(x))
plt.show()

I have the error when taking the factorial. When running the code it throws me the following error:
TypeError: only size-1 arrays can be converted to Python scalars

How should I fix it?
Thank you.

A: Math functions can't be called on numpy arrays, only on numpy scalars. To calculate the element-wise factorial of an array, scipy.special.factorial is needed.
As mentioned in the comments, np.linspace(0, 100, 100) aren't integers. You'd need np.linspace(0, 100, 101) to get the integers from 0 to 100. As scipy.special.factorial falls back on the gamma function, non-integers aren't necessarily a problem. Note, however, that these types of values aren't very precise.
To show your curve, you might want to use a log scale:
import matplotlib.pyplot as plt
import numpy as np
import scipy.special

def g(x):
    return np.exp(-10) * pow(10, x) / scipy.special.factorial(x)

x = np.linspace(0, 100, 100)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
ax1.plot(x, g(x))
ax1.set_title('linear plot')
ax2.plot(x, g(x))
ax2.set_yscale('log')
ax2.set_title('log plot')
plt.show()

A: I have fixed the error with from scipy.special import factorial

import matplotlib.pyplot as plt
import numpy as np
from scipy.special import factorial

def g(x):
    return np.exp(-10)*pow(10,x)/factorial(x)

x=np.linspace(0,100)
plt.plot(x,g(x))
plt.show()

The Stirling's Approximation is not necessary. Thank you.


text:
Q: Old version (macOS Sierra) for Pages, Keynote and Numbers, iWork I uninstalled my iWork tools - Keynote, Numbers and Pages - from my MacBook Air.

Unfortunately, I don't want to upgrade my MBA to Mojave/Catalina in order to install.
I looking for the working iWork version for 10.12 Sierra.
Is there some repository for old versions of iWork?

A: You need to have an old version of Pages, Keynote and Numbers installed in your Applications folder to be able to update them. If you lack these (either because you deleted them or never had them installed first hand) and never registered the purchase with your Apple ID, you need to work your way up through the missing years of upgrading, including the registration with your Apple ID to be offered an installation on any system that's older than the currently shipped Mojave:

*

*Install an old iWork suite (from your original installation medium, or use the iWork '09 trial suite that can still be downloaded from Apple.

*You now have an iWork 09 folder inside your Applications folder, containing trial versions of Pages, Numbers and Keynote.

*Launch Pages, Numbers and Keynote, then quit each app. (This step was suggested by the instructions based on the 2014 article. It doesn't seem to be necessary any more - I had only launced one of the programs.)

*The trial suite can be upgraded to iWork 9.3 with a downloader available at Apple - Support - Downloads. I cannot verify if this step is necessary since I had installed that upgrade. I suspect it can be skipped.

*You still have an iWork 09 folder inside your Applications folder, containing trial versions of Pages (v4.3), Numbers (v2.3) and Keynote (v5.3).

*Launch the Mac App Store, go to the updates tab, and activate show incompatible updates. Selecting one of those apps will take you to the app's page. There, select update. The store asks for purchase confirmation and your password (if required by your settings). Then it will attempt to update the application, and fail, telling you that they require 10.14. Repeat for all three (five, if you installed iMovie and Garageband from your original DVDs) applications anyway, since from then on this application will appear in your Purchased tab. (Note: The Purchased tab disappeared with MacOS 10.14 - High Sierra might be the last OS to handle this step)

*Now your purchase is linked to your account, and you may reinstall those applications if they ever should get lost. So let's loose them: delete the iWork09 folder from Applications (or move it to the Thrash).

*Go to the purchased tab in App Store. The applications are listed at the top of the purchased list. Upon selecting install, you will be prompted if you want to install the last supported version for your OS release.

*You now have Pages (v8.1), Numbers (v6.1) and Keynote (v9.1) directly in your Applications folder. (Version numbers applying to High Sierra as of January 2020)
Alternative route
If you have access to another Mac running a version of MacOS currently supported by the App Store (As of Jan 2020, that would be 10.14 (Mojave) or 10.15), you could associate your AppleID with an account on that Mac, download (and thus register) the Applications you want to install on your older Mac there, and then use the Purchased tab on the older Mac to reinstall older versions of those apps on the older Mac.
Sources:

*

*2014 Redmondpie article

*2014 Cult of Mac article

*2018 osxdaily article "Where to Download Old Mac OS Software"

*MacWorld article about missing purchases tab in Mojave App Store

A: If you go to the Mac App Store and try to install the iWork apps, it should offer you the appropriate versions.

*

*Pages

*Numbers

*Keynote
Are you looking for the older version of iWork before the Mac App Store? I think it was iWork '09? I'm not sure that is still available.
This article from December 2014 might help:
How To Get iWork Apps On OS X Yosemite For Free On Older Macs | Redmond Pie

A: The root of this problem is that you need to have the app in your App Store storage (you must have "bought" it) in order to get a compatible version for your OSX. But you cannot buy it because your OSX version is to low.
If by any chance you are able to borrow or log into a newer MAC, with the appropriate OS you can "purchase" the application and download it there.
Next time you open App Store on your old Mac, you will be given the option to download the last supported version of the app. Since it is registered on your account that you now own the program.
Also, having a friend with an Apple ID from which the suite has been downloaded can help. Let him log into App Store on your Mac with his ID. He can then install the program on your Mac. Afterwords you can login yourself. And the app is still yours.

A: I suggest you upgrade to High Sierra. I'm using Pages, Numbers, and KeyNote and have very recent versions that work fine. Much of the new software will not run on systems earlier that High Sierra. The apps I've mention should be loaded when you do this upgrade.


text:
Q: Open file Error permission denied on macOS hi I use bridging header include a hpp
but always output "Error permission denied"
My Derived Data is relative
I tried to key "chmod -R 777 ./" in Debug-iPhonesimulator
show the code:
bool CheckPath()
{
    FILE *pfile = fopen("./__viewtest.txt","w");
    if(pfile){
        fclose(pfile);
        return true;
    }
    printf("Error %s\n",strerror(errno));
    return false;
}

it is always output "Error permission denied"
thanks a lot

A: I solved it
#include <unistd.h>
#include<iostream>

std::string GetCurrentWorkingDir( void ) {
    char buff[FILENAME_MAX];
    getcwd( buff, FILENAME_MAX );
    std::string current_working_dir(buff);
    return current_working_dir;
}

bool CheckPath()
{
    std::string sPath = GetCurrentWorkingDir();
    sPath += "Users/My/Desktop/WorkSpace/View/DerivedData/View/Build/Products/Debug-iphonesimulator/__viewtest.txt";
    FILE *pfile = fopen(sPath.c_str(),"w");
    if(pfile){
        fclose(pfile);
        return true;
    }
    printf(" %s, Path %s\n",strerror(errno), GetCurrentWorkingDir().c_str());
    return false;
}


text:
Q: C# Frequency Distribution Associative Container Initialization-way to avoid hashing twice Some background. There is a class Card, it has an enum called RANK, and a member Rank of type RANK. The goal is to take an IEnumerable<Card>, and produce a dictionary like object, Keyed by RANK and Valued by the number of such rank in the argued sequence.
eg. in the context of Poker, a five card sequence with quad Aces would yield an order-variant {(ACE,4),(someOtherRank,1)} dictionary. Below is the function that I have.
static IReadOnlyDictionary<Card.RANK, int> GetRankDistribution(IEnumerable<Card> hand)

    {
        var distribution = new Dictionary<Card.RANK, int>(13);

        foreach (Card.RANK rank in hand.Select(card => card.Rank))
        {
            distribution.TryGetValue(rank, out var valueBuffer);
            distribution[rank] = valueBuffer + 1;
        }

        return distribution;
    }

My problem is this function is called an inordinate amount of times, and allthough the dictionary is optimally sized for the domain, I cannot conceive of a way to avoid hashing twice to build the object(once in the TryGet, and once to apply the value, whether incremented off int() or a functional ++).
In C++, I could ++dictionary[rank]; in the loop body. If the Key is absent, it is inserted, with the default Valueconstructed in situ, and its reference returned(the eventual operand of the precrement™).
In Python, I could just return Counter(hand), and who knows what happens, but it is at least syntactically elegant.
Is there any way in C#, given the most primitive of value types, to effectively achieve what the C++ map operator[](for better or worse) does?
If inheriting and refactoring are involved in the answer, I personally do not consider it 'effective' as I define it.

A: Sure:
var dictionary = hand.GroupBy(x => x.Rank).ToDictionary(x => x.Key, x => x.Count());


text:
Q: Java Multi threaded socket client/server: sending and receiving Enummap objects To begin with, it is a JavaFX application with classical MVC architecture. This application roll dices and display them. The goal is to display them to several clients. I am using a multi threaded "echo" server with sockets to deal with clients. Since in JavaFX we can't directly send nodes through socket, i decided to send arguments wich are generated by the client, then the client sends them to the server so it can echo the arguments to all connected clients.
Here is how it works :
First, the main server thread is created. It creates a ServerSocket and a while loop creates a new thread that will handle connected client. This main server thread has 3 methods : 2 that will keep track of connected client, and 1 that sends incoming arguments to all connected clients.
public class DiceRollServerThread implements Runnable
{
    private Server _server;
    private Server_C controller;
    private Vector<ObjectOutputStream> tabClients = new Vector<ObjectOutputStream>(); // Contain all outpput streams to connected clients
    private Thread t;
    private ServerSocket diceSS;

    public DiceRollServerThread(Server server) throws IOException
    {
        _server = server;

        controller = _server.getController();

        String port = "2000";
        String ip = "127.0.0.1";

        controller.setConsole("IP : "+ip+"\n"+"Port : "+port);

        diceSS = new ServerSocket(Integer.parseInt(port), 0, InetAddress.getByName(null));

        t = new Thread(this);
        t.start();
    }

    @Override
    public void run()
    {
        while (true) // bloquing on ss.accept
        {
            try
            {
                new DiceRollThread(diceSS.accept(), this);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    synchronized public void sendAll(EnumMap<ARGS, String> arguments) throws IOException
    {
        ObjectOutputStream out;

        for (int i = 0; i < tabClients.size(); i++) // browsing connected clients
        {
            out = (ObjectOutputStream) tabClients.elementAt(i);
            if (out != null)
            {
                out.writeObject(arguments);
                out.flush();
            }
        }
    }

    synchronized public void delClient(int i)
    {
        if (tabClients.elementAt(i) != null) // If element exist ...
        {
            tabClients.removeElementAt(i); // ... delete it
            System.out.println("delClient");
        }
    }

    synchronized public int addClient(ObjectOutputStream out)
    {
        tabClients.addElement(out); // Adding new output stream to vector
        System.out.println("addClient");
        return tabClients.size()-1; // return client number (size-1)
    }

    public Server get_server()
    {
        return _server;
    }
}

Here is the thread handling clients :
public class DiceRollThread implements Runnable
{
    private Thread t;
    private Socket _s;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private DiceRollServerThread _serverThread; // to use main thread methods
    private int numClient=0;
    private Server _server;
    private EnumMap<ARGS,String> _arguments;

    DiceRollThread(Socket s, DiceRollServerThread serverThread)
    {
        _s = s;
        _serverThread = serverThread;
        _server = _serverThread.get_server();

        try
        {
            out = new ObjectOutputStream(_s.getOutputStream());
            in = new ObjectInputStream(_s.getInputStream());
            numClient = _serverThread.addClient(out);
            _server.getController().setConsole("Client n°"+numClient+" connected.");
        }
        catch (IOException e)
        {

        }

        t = new Thread(this);
        t.start();
    }

    @Override
    public void run()
    {
        try
        {
            while(_s.getInputStream().read() != -1) // verifying if connection is still up
            {
                _arguments = (EnumMap<ARGS, String>) in.readObject(); // Problem is here

                if(_arguments != null)
                {
                    System.out.println(_arguments);
                    _serverThread.sendAll(_arguments);
                }
            }
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally // Usually happens when client disconnect
        {
            try
            {
                _server.getController().setConsole("Client n°"+numClient+" disconnected.");
                _serverThread.delClient(numClient); // deleting from the vector
                _s.close(); // Closing socket if not done by upper exception
            }
            catch (IOException e)
            {

            }
        }
    }

Now on client side. The main app has a controller that will get the value of two fields and store them in the following Enummap
public class Arguments
{
    public enum ARGS {Couleur,Valeur};
}

And then sends it to the following thread handling connection to the server.
private void roll()
{
    arguments.put(ARGS.Couleur, box_couleur.getValue().toString());
    arguments.put(ARGS.Valeur, randInt(1,Integer.parseInt(box_de.getValue())));

    diceRollThread.send(arguments); // the thread gives his reference to the controller when created
}

The client thread (wich is connected to the server)
public class DiceRollThread implements Runnable
{
    private DiceRoll_C _controller;
    private Socket s;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private Thread t;
    private EnumMap<ARGS,String> _arguments;

    DiceRollThread(DiceRoll diceroll) throws IOException
    {
        _controller = diceroll.getController();
        _controller.setDiceRollThread(this);

        String port = "2000";
        String ip = "127.0.0.1";

        try
        {
            s = new Socket(InetAddress.getByName(ip),Integer.parseInt(port));
            out = new ObjectOutputStream(s.getOutputStream());
            in = new ObjectInputStream(s.getInputStream());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        t = new Thread();
        t.start();
    }

    @Override
    public void run()
    {
        try
        {
            _arguments = (EnumMap<ARGS, String>) in.readObject();

            if(_arguments != null)
            {
                _controller.addDice(_arguments); // Creating dice from received arguments
            }
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                s.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public void send(EnumMap<ARGS,String> arguments) // arguments received from the controller, sends them to the server
    {
        try
        {
            out.writeObject(arguments);
            out.flush();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

A typical scenario looks like this : Launching server > launching client (connection made successfuly) > user press roll.
When the user press roll, 2 values are stored in an enummap created by the controller, the controller forwards this enummap to the client thread via send() method; and this method writes the enummap to the objectoutput stream.
The problem happens at next step. The thread handling client connection on server side receives the enummap from the stream
_arguments = (EnumMap<ARGS, String>) in.readObject();

But it appears it is unable to cast it to Enummap and throws an exception

java.lang.ClassCastException: java.io.ObjectStreamClass cannot be cast to java.util.EnumMap
at java.lang.Thread.run(Unknown Source)

What am i doing wrong ?

A: while(_s.getInputStream().read() != -1) // verifying if connection is still up

The problem is here. It consumes a byte from the input stream and so puts the serialization out of synchronization with the sender.
It also doesn't accomplish the objective stated in the comment. The correct way to do that is just to catch the IOException: connection reset that will result from sending to a broken connection, or the EOFException that results from reading past end of stream.


text:
Q: How to pull image name from state for file pond When I navigate to a particular page I want the file pond image to be repopulated with an image I have already uploaded and the image name is in the database.
Currently I have the image name hardcoded, The image name is available in the state which is set in componentDidMount but the state is being set for file pond as well which is confusing me a bit to be honest.
So, this is when it is hardcoded:
class HomeBannerForm extends InputForm {
  async componentDidMount() {
    const { data: hero } = await getHero();
    this.setState({ data: this.mapToViewModel(hero) });
  }

      state = {
        data: {
          title: "",
          bgImg: ""
        },
        errors: {},
        files: [
          {
            source: "myImage.jpg",
            options: {
              type: "local"
            }
          }
        ]
      };

  mapToViewModel(hero) {
    return {
      id: hero._id,
      title: hero.title,
      bgImg: hero.bgImg
    };
  }

So, I need to change the myImage.jpg to what is in the state from componentDidMount ie: the name from the database. This obviously does not work.
    files: [
      {
        source: this.state.data.bgImg
        options: {
          type: "local"
        }
      }
    ]

Filepond component code:
            <FilePond
              ref={ref => (this.pond = ref)}
              files={this.state.files}
              allowMultiple={false}
              maxFiles={1}
              instantUpload={false}
              name="bgImg"
              server={{
                process: "http://localhost:8000/api/hero/",
                load: "http://localhost:8000/img/"
              }}
              oninit={() => this.handleInit()}
              onupdatefiles={fileItems => {
                // Set currently active file objects to this.state
                this.setState({
                  files: fileItems.map(fileItem => fileItem.file)
                });
              }}
              // callback for successfully uploaded image
              onprocessfile={() => this.uploadComplete()}
            />

A: Looks like you need to tweak your hero mapping:
mapToState(hero) {
   return {
     data: {
       title: hero.title,
       bgImg: hero.bgImg
     },
     errors: {},
     files: [
       {
         source: hero.bgImg,
         options: {
           type: "local"
        }
      }
    ]
  };
}
async componentDidMount() {
    const { data: hero } = await getHero();
    this.setState(this.mapToState(hero));
}

A: Try this.
class HomeBannerForm extends InputForm {

state = {
        data: {
          title: "",
          bgImg: ""
        },
        errors: {},
        files: [
          {
            source: "myImage.jpg",
            options: {
              type: "local"
            }
          }
        ]
      };

  async componentDidMount() {
    const { data: hero} = await getHero();
this.setState(prevState => ({
      data: this.mapToViewModel(hero),
      files: prevState.files.map(obj => {
        Object.assign(obj, { source: hero.bgImg });
      })
    }));

  }

  mapToViewModel(hero) {
    return {
      id: hero._id,
      title: hero.title,
      bgImg: hero.bgImg
    };
  }


text:
Q: Можно ли в suggestView яндекс карт как-либо автоматически устанавливать выбор на первую подсказку в списке? Поясню, о чем я говорю - допустим, пользователь вводит текст в инпут, к которому привязан suggestView из yandex api. Ему начинают выдаваться подсказки, но если нажать enter, то подсказки просто пропадут, а значение поля не изменится. Но в то же время, если навести мышку на подсказку, или выбрать ее стрелочками, то при нажатии на enter она автоматически выберется.
я попытался сделать некий костыль и отлавливать каждое нажатие клавиш в инпуте и менять значнеие в state у activeIndex. Но это не работало, activeIndex сразу после смены значения заново устанавливается в null. Я решил пойти другим путем и отловить именно enter, сменив значение activeIndex, но и это не сработало, выбор не происходит
я попытался даже стриггерить ивент 'select' после установки значения - все тщетно. Вот примерный код последних моих попыток
input.addEventListener('keydown', function (e) {
  if(e.code === 'Enter') {
    let activeIndex = suggestInput.state.get('activeIndex');
    if (typeof activeIndex !== 'number') {
      suggestInput.state.set('activeIndex', 0);
      suggestInput.events.fire('select')
    }
  }
})

A: Зачем вам эмуляция выбора? Просто получайте значение первой строки саджеста и далее обрабатывайте так, как планировалось. Например копировать в строку инпута:
let input = document.getElementById('suggest')

input.addEventListener('keydown', function (e) {
  if(e.code === 'Enter') {
    input.value = suggestView.state.get('items')[0].value
  }
})


text:
Q: Twisted tcp tunnel/bridge/relay I'd like to know how to write TCP tunnel/relay/bridge/proxy (you name it) using twisted.
I did some research in google, twisted doc/forum etc. etc but couldn't find anwser.
I already done it in pure python using socket, threading and select.
Here is code:
#!/usr/bin/env python

import socket
import sys
import select
import threading
import logging
import time

class Client(threading.Thread):
    def __init__(self, client, address, id_number, dst_ip, dst_port):
        self.log = logging.getLogger(__name__+'.client-%s' % id_number)
        self.running = False
        self.cl_soc = client
        self.cl_adr = address
        self.my_id = id_number
        self.dst_ip = dst_ip
        self.dst_port = dst_port
        threading.Thread.__init__(self)

    def stop(self):
        self.running = 0

    def run(self):
        try:
            self.dst_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.dst_soc.connect((self.dst_ip,self.dst_port))
        except:
            self.log.error('Can\'t connect to %s:%s' % (self.dst_ip, self.dst_port))
        else:
            self.running = True
            self.log.info('Bridge %s <-> %s created' % (
                '%s:%s' % self.dst_soc.getpeername(), '%s:%s' % self.cl_adr))

        try:
            while self.running:
                iRdy = select.select([self.cl_soc, self.dst_soc],[],[], 1)[0]

                if self.cl_soc in iRdy:
                    buf = self.cl_soc.recv(4096)
                    if not buf:
                        info = 'Ended connection: client'
                        self.running = False
                    else:
                        self.dst_soc.send(buf)

                if self.dst_soc in iRdy:
                    buf = self.dst_soc.recv(4096)
                    if not buf:
                        info = 'Ended connection: destination'
                        self.running = False
                    else:
                        self.cl_soc.send(buf)

        except:
            self.log.error('Sth bad happend', exc_info=True)
            self.running = False

        self.log.debug('Closing sockets')
        try:
            self.dst_soc.close()
        except:
            pass

        try:
            self.cl_soc.close()
        except:
            pass

class Server(threading.Thread):
    def __init__(self, l_port=25565, d_ip='127.0.0.1', d_port=None):
        self.log = logging.getLogger(__name__+'.server-%s:%s' % (d_ip,d_port))
        threading.Thread.__init__(self)
        self.d_ip = d_ip
        if d_port == None:
            self.d_port = l_port
        else:
            self.d_port = d_port

        self.port = l_port
        binding = 1
        wait = 30
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET,  socket.SO_REUSEADDR,  1)
        while binding:
            try:
                self.s.bind(('',self.port))
            except:
                self.log.warning('Cant bind. Will wait %s sec' % wait)
                time.sleep(wait)
            else:
                binding = 0
                self.log.info('Server ready for connections - port %s' % d_port)

    def run(self):
        self.s.listen(5)
        input = [self.s, sys.stdin]
        running = 1
        self.cl_threads = []
        id_nr = 0

        while running:
            iRdy = select.select(input, [], [],1)[0]
            if self.s in iRdy:
                c_soc, c_adr = self.s.accept()
                c = Client(c_soc, c_adr, id_nr, self.d_ip, self.d_port)
                c.start()
                self.cl_threads.append(c)
                id_nr += 1

            if sys.stdin in iRdy:
                junk = sys.stdin.readline()
                print junk
                running = 0

        try:
            self.s.close()
        except:
            pass

        for c in self.cl_threads:
            c.stop()
            c.join(5)
            del c

        self.cl_threads = None

        self.log.info('Closing server')

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    s = Server(1424, '192.168.1.6', 1424)
    s.run()

A: this is actually, already built into twisted, from the command line you can type:
$ twistd --nodaemon portforward --port 1424 --host 192.168.1.6

to get the exact behavior you seem to be looking for.
If you'd like to roll your own, you can still use all of the bits, in twisted.protocols.portforward


text:
Q: Ag Grid Set Filter Issue not able to be formatting value with different key one technical question for whom having hands on ag-grid angular, we came in scenario where we have set filter and to display value to user is something descriptive e.g., like a country name, and while applying a filter have to send some code e.g., country code to backend application. we tried couple of ways but didn't get luck in that. any expert help?
expectation is there any way to handle display with different key and sending data with different key to backend application on applying filter


text:
Q: How can I define elements positions in HTML/CSS I'm trying to learn HTML and CSS and I've came across the following question.
I need to insert a vertical gap between the elements of the site::

To be like that:

But I have no idea to get it done without using a lot of
.
Can someone help me to get this done?
Thanks so much!

A: Just add a margin to your html element that contains your 'Header' text, and some margins to the button.
This is a good resource for that: https://www.w3schools.com/css/css_margin.asp

A: gap style property is for display: flex, but you can use margin-bottom for this, here is an example.
HTML

Header

Header

CSS
.header {
 margin-bottom: 50px;
}

A: you can also insert in a line break with the br tag


text:
Q: problems in dynamic craetion of subdomains in php Hello
I am creating subdomains in php by the following code.
function subd($host,$port,$ownername,$passw,$request) {

  $sock = fsockopen('localhost',2082);

  if(!$sock) {

    print('Socket error');

    exit();

  }

  $authstr = "$ownername:$passw";

  $pass = base64_encode($authstr);

  $in = "GET $request\r\n";

  $in .= "HTTP/1.0\r\n";

  $in .= "Host:$host\r\n";

  $in .= "Authorization: Basic $pass\r\n";

  $in .= "\r\n";

  fputs($sock, $in);

  while (!feof($sock)) {

    $result .= fgets ($sock,128);

  }

  fclose( $sock );

  return $result;

}

$domain="memories.mydomain.com";

        $subd="abcdef";

        $request ="frontend/x3/subdomain/doadddomain.html?domain=$subd&rootdomain=$domain&dir=public_html/$subd&go=Create";

        $host="ftp.mydomain.com";

        $port="2083";

        $ownername="ownername";

        $passw="my_PASSWORD";

        $result=subd($host,$port,$ownername,$passw,$request);

        $show = strip_tags($result);

    $d="http://$subdomainname.$domain";

          echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$d.'">';

I am seeing in my cpanel sub-domain is creating but i want to redirect to my sob-domains when creation completed but instead of subdomain i am redirecting to  error page which is
http://abcdef.memories.mydomain.com/cgi-sys/defaultwebpage.cgi. What is the problem behind it.Why am i redirecting to unsupported link.?
Thanks

A: Wow, you're writing an automated front end for an automated front end.  Why don't you just create the subdomain directly in the php script, and skip messing around with cpanel?

A: Are you sure this should be done as a GET request? Doing things on a server via GET that have consequences is NEVER a good idea: http://thedailywtf.com/Articles/The_Spider_of_Doom.aspx

*

*Don't use your own http client. Use curl (good) or something like file_get_contents (not as good)

*Check if CPanel wants this done as a POST instead.

*You pass in a port #2083, but then ignore it completely and use a hardcoded port #2082 in the function.

*Your request URL has no leading /, which makes it an invalid request. You can use such paths in an HTML page, because the browser rewrites the href="" stuff by putting on the address of the page the link is in - but you're not using a browser. You're rolling your own version.


text:
Q: SQLite Command? I am trying to make a login page with xamarin
public bool Login(string Username, string Password)
    {
        Users _user = new Users();
        string mySelectQuery = "SELECT Name, Password FROM Users WHERE Name='" + Username + "' AND Password='" + Password + "'";

        var user = new SQLiteCommand(mySelectQuery);

        if (user != null)
        {
            return true;
        }

        return false;
    }

At SQLiteCommand part it gives an error.
The error is CS1729 Does not contain a constructor that takes 1 arguments
I checked out on the internet but I didn't get it I am new at this.

A: You use SQLiteCommand class, and contain one arguments, it should be SQLiteConnection, here is sample that about this:
public bool Login(string Username, string Password)
    {

        string dbName = "Data Source=searchindex.db";
        string mySelectQuery = "SELECT Count(*) FROM Users WHERE Name='" + Username + "' AND Password='" + Password + "'";

        SQLiteConnection con = new SQLiteConnection(dbName);
        SQLiteCommand cmd = new SQLiteCommand(con);
        cmd.CommandText = mySelectQuery;

        var count = cmd.ExecuteScalar<int>();
        if (count>0)
        {
            return true;
        }

        return false;
    }


text:
Q: Casting URLConnection to HttpUrlConnection in Nashorn I've got some code:
var Base64 = java.util.Base64;
var URL = java.net.URL;
var HttpURLConnection = java.net.HttpURLConnection;
var connectionAddress = new URL("http://twitter.com/");
var httpConnection = Java.to(
        connectionAddress.openConnection(),
        Java.type("java.net.HttpURLConnection")
    );

this throws an exception:
TypeError: sun.net.www.protocol.http.HttpURLConnection:http://twitter.com/ is not an Object
anyone have any ideas how to handle this?

A: Java.to is used to convert a JavaScript object to a Java object. Currently it supports conversion to Java array types, as well as java.util.List and java.util.Deque. It can't be used to "cast" between Java types, and anyway, it's not a meaningful concept in a dynamic language. Your openConnection() invocation gave you back a Java object of type sun.net.www.protocol.http.HttpURLConnection, which sounds like something that is already a subclass of java.net.HttpURLConnection, so you should all be set just by writing
var httpConnection = connectionAddress.openConnection();


text:
Q: the touch control script causes glitech in unity 3d runner In my 3d runner game, the character has free movement (left and right) as they are running forward( this is not a runner game with a three lanes mode). in my player controller script using a keyboard, the character goes left and right easily with no problem. BUT when I added the touch input script to my character I faced some strange problems.
when the character goes left and right as the finger keeps touching the screen and goes left and right (sliding movement), the half body(mostly legs) of the character goes into the platform he is running on it.
the script and photos of the glitch are here and you can see them and what I mean.
I am new to unity and scripting. I don't know how to solve it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveTouch : MonoBehaviour
{
    private Touch touch;
    private float speedmodifier;
    [Range(0.1f, 10f)]
    public float moverange = 4.5f;
    // Start is called before the first frame update
    void Start()
    {
        speedmodifier = 0.01f;
    }

    // Update is called once per frame
    void Update()
    {
        if ( Input.touchCount > 0)
        {
            touch = Input.GetTouch(0);
            if (transform.position.x < moverange && transform.position.x > -moverange && touch.phase == TouchPhase.Moved)
            {
                transform.position = new Vector3(transform.position.x + touch.deltaPosition.x * -speedmodifier, 0, transform.position.x + touch.deltaPosition.x * speedmodifier);

            }
        }
    }
}


text:
Q: Fetch raw e-mail text with EWS (headers, body and encoded attachments) Is there a way to fetch the raw email text using EWS?
I would like to get the whole text including headers, body, and encoded attachments.
Is this possible?

A: I don't know if this is what you are looking for, but it should help.
It downloads the entire message file, including encoded attachments, header, subject, sender, receiver, etc...
try this:

static void Main(string[] args)
{
    try
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
        service.Credentials = new NetworkCredential("USR", "PWD", "Domain");
        service.AutodiscoverUrl("someone@example.com");

        FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));

        Console.WriteLine("Found : " + findResults.TotalCount + " messages");

        foreach (EmailMessage message in findResults.Items)
        {
            try
            {
                message.Load(new PropertySet(ItemSchema.MimeContent));
                MimeContent mc = message.MimeContent;
                // I use this format to rename messages files, you can do whatever you want
                string n = string.Format("-{0:yyyy-MM-dd_HH-mm-ss-ffff}.eml", DateTime.Now);
                string path = @"C:\folder\message" + n;
                FileStream fs = new FileStream(path, FileMode.Create);
                fs.Write(mc.Content, 0, mc.Content.Length);
                fs.Flush();
                fs.Close();

                //message.Delete(DeleteMode.HardDelete);   // It deletes the messages permanently
                //message.Delete(DeleteMode.MoveToDeletedItems);  // It moves the processed messages to "Deleted Items" folder

            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp);
            }
        }
    }
    catch (Exception exp2)
    {
        Console.WriteLine("Error : " + exp2);
    }
}

Hope it helps, cheers.


text:
Q: Problems with OpenCV warpPerspective with transparent images I'm trying to change the perspective of a fake glasses image with OpenCV, but the transparent parts and opacity get lost. Resulting image has no transparencies.
I want to change the perspective in order to stamp the resulting image over another image.
Can I do this with OpenCV?
#!/usr/bin/python
import numpy as np
import cv2

glasses = cv2.imread('fake_glasses.png')

RES_SIZE = (500,640)

pts1 = np.float32([[  0,  0], [599,  0],
                   [  0,208], [599,208]])
pts2 = np.float32([[ 94,231], [354,181],
                   [115,316], [375,281]])

M = cv2.getPerspectiveTransform(pts1,pts2)

rotated = cv2.warpPerspective(glasses, M, RES_SIZE)
cv2.imwrite("rotated_glasses.png", rotated)

A: You are loading the image incorrectly, dropping the transparency layer. This is easy to verify -- print the shape of the image after you load it.
>>> img1 = cv2.imread('fake_glasses.png')
>>> print(img1.shape)
(209, 600, 3)

When not specified, the flags parameter of imread is set to IMREAD_COLOR. According to the documentation this means

If set, always convert image to the 3 channel BGR color image.

Instead, you should use IMREAD_UNCHANGED

If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).

With this change, the image loads correctly, including the alpha plane.
>>> img2 = cv2.imread('fake_glasses.png', cv2.IMREAD_UNCHANGED)
>>> print(img2.shape)
(209, 600, 4)


text:
Q: Suppose $\sum_{n=1}^{\infty} V(f_n - f;a,b) < \infty$, prove that $f_n^{'}$ converges almost everywhere to $f^{'}$ Suppose $f$, $f_n$ $\in$ BV[a,b] and suppose $\sum_{n=1}^{\infty} V(f_n - f;a,b) < \infty$, prove that $f_n^{'}$ converges almost everywhere to $f^{'}$.
I could prove that $f_n^{'}$ converges to $f^{'}$ in $L^p$, so that there is a subsequence of {$f_n^{'}$} which converges almost everywhere to $f^{'}$. Could someone help me to prove the stronger argument? Thanks a lot.

A: Notice (by replacing $f_n - f$ by a new function $g_n$) that it is enough to prove that for a sequence of functions $f_n\in BV[a,b]$ if
$$
\sum\limits_{n=1}^\infty V(f_n; a, b) < \infty
$$
then $f_n' \to 0$ a.e. To this end recall a well-known fact that for $f \in BV[a,b]$ one has $$\tag{1} \int\limits_a^b |f'(x)|dx \leq V(f; a,b).$$
To see $(1)$ define $V(f; a,x)=: T(x)$ where $a\leq x \leq b$ and observe that at points $x\in [a,b]$  where both $f'(x)$ and $T'(x)$ are defined we have $|f'(x)| \leq T'(x)$. The latter is due to the fact that for any $h>0$ small we have
$$
\frac { T(x + h) - T(x) }{h} = \frac 1h V(f; x, x + h)  \geq \frac{1}{h}|f(x + h) - f(x)|,
$$
and the claim follows by taking $h\to 0$.
Since derivatives of $f$ and $T$ exist almost everywhere in $[a,b]$ it follows that $|f'(x)| \leq T'(x)$ a.e. Integrating this over $[a,b]$ we recover $(1)$.
Using $(1)$ we have
$$
\sum\limits_{n=1}^\infty \int\limits_{a}^b |f_n'(x)|dx \leq \sum\limits_{n=1}^\infty V(f_n; a,b) <\infty.
$$
It follows that $\sum\limits_{n=1}^{\infty} |f_n'(x)| < \infty $ a.e. and hence $f_n'(x) \to 0$ a.e. completing the proof.


text:
Q: how to calculate sum of quantite in an object hello I am trying to obtain the total of the quandites for 77777+88888+99999+the others
I have a piece of code in which I would like to calculate items but with different quantities
so I have for example for articles 77777 ----10 under articles
for item 88888 20 sub items
for item 99999 30 sub items
imagine that the user adds 4 items 77777 to his basket, this must make a total of 40
if he adds 2 items 88888 that makes a total of 40
if he adds 3 items 99999 that makes a total of 90
if he adds 18 more items that makes a total of 18
So the absolute total is 40+40+90+18=188 items
My code is not working correctly at the moment
obj.totalpanierpromotion = function() {
    var totalpanierpromotion = 0;
    for(var item in panier) {
        //console.log(panier[item]);
        if (panier[item].nom == 77777) {
            panier[item].quantite = 10 ;
            totalpanierpromotion +=  panier[item].quantite;
        } else if (panier[item].nom == 88888) {
            panier[item].quantite = 20 ;
            totalpanierpromotion +=  panier[item].quantite;
        } else if (panier[item].nom == 99999) {
            panier[item].quantite = 30 ;
            totalpanierpromotion +=  panier[item].quantite;
        }else {
            totalpanierpromotion +=  panier[item].quantite;
        }
    }
    console.log(Number(totalpanierpromotion));
    return Number(totalpanierpromotion);
}

A: If I understand correctly it's simple

var obj = {}
obj.totalpanierpromotion = function() {
  var totalpanierpromotion = 0;
  for (var item in panier) {
    //console.log(panier[item]);
    if (panier[item].nom == 77777) {
      panier[item].quantite = 10;
      totalpanierpromotion += panier[item].quantite;
    } else if (panier[item].nom == 88888) {
      panier[item].quantite = 20;
      totalpanierpromotion += panier[item].quantite;
    } else if (panier[item].nom == 99999) {
      panier[item].quantite = 30;
      totalpanierpromotion += panier[item].quantite;
    } else {
      panier[item].quantite = 1;
      totalpanierpromotion += panier[item].quantite;
    }
  }
  console.log(Number(totalpanierpromotion));
  return Number(totalpanierpromotion);
}
var panier = {
  "1": {
    nom: 77777
  },
  "2": {
    nom: 77777
  },
  "3": {
    nom: 88888
  },
  "4": {
    nom: 00000
  }
}

obj.totalpanierpromotion()
console.log(panier)


text:
Q: trouble retrieving data from firebase in flutter dart application. cannot get a field on a DocumentSnapshotPlatform which does not exist Error im receiving :
StateError (Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist)

Future getUserInterests(userId) async {
    User currentUser = User();

    await _firestore.collection('users').doc(userId).get().then((user) {
      currentUser.photo = user.get('name');
      currentUser.photo = user.get('photoUrl');
      currentUser.gender = user.get('gender');
      currentUser.subject = user.get('subject');

    });
    return currentUser;
  }

the name field does exist in my firebase collection thing
here is an image of my database, ignore how gender says 10th lol

A: You need to do the following:
currentUser.name = user.data()['name'];
currentUser.photo = user.data()['photoUrl'];
currentUser.gender = user.data()['gender'];
currentUser.subject = user.data()['subject'];


text:
Q: jquery setting an attribute to input and textarea with on for newly added elements $("input:text,textarea").attr("autocomplete","off");

What's the twist to have it work when new elements get added to the dom.
Affect input:text and textarea to apply this rule to newly added elements after the rule was executed on $(document).ready
this is the answer, although not that perfect.
$(function() {
$("body").on("focus", "input:text,textarea", function(){
if($(this).attr("autocomplete")!="off"){
$(this).attr("autocomplete","off");
}
});
});

thanks for all the downvotes..

A: I think the problem here is that the autocomplete  is not a valid  attribute for the input field.. It is added by the jQuery plugins .
You need to set the autocomplete to on and off using the plugin syntax for the jquery UI


text:
Q: chrome extension run script after ajax I am new to Javascript, and I am creating a chrome extension where I am trying to inject some HTMLs into the existing public website,
My current code is something like this,
if (document.readyState ==='complete'){
  inject_html();
}

However, on the current website, when a button is pressed, ajax is processed and new HTML DOM is loaded for the same url, so the script doesn't run.
Is there a way to listen to whenever ajax is finished processing? What is the best way in this case, can an expert help me?

A: This is rather hacky, but you can override any property (and thus interpose any method call) of the XMLHttpRequest prototype, as well as the function/constructor itself.
The most convenient thing to do in your case is probably to hook the XMLHttpRequest function itself, and simply add an event listener there:
var originalXHR = XMLHttpRequest;
XMLHttpRequest = function()
{
    var ret = new originalXHR();
    ret.addEventListener('load', function()
    {
        console.log('Ajax request finished!');
    });
    return ret;
};

The control flow here goes like this:

*

*Call original function

*Modify return value

*Return modified value

This takes advantage of the fact that if in JavaScript a constructor returns a value, that value replaces the object created with new.
In action:

// Interface code
var field = document.querySelector('input');
document.querySelector('button').addEventListener('click', function()
{
    var xhr = new XMLHttpRequest();
    // crossorigin.me because we need a CORS proxy for most external URLs
    xhr.open("GET", 'https://crossorigin.me/' + field.value);
    xhr.send(null);
});

// Hooking code
var originalXHR = XMLHttpRequest;
XMLHttpRequest = function()
{
    var ret = new originalXHR();
    ret.addEventListener('load', function(ev)
    {
        // var xhr = ev.target;
        console.log('Ajax request finished!');
    });
    return ret;
};
<!-- Demo page: -->
URL: <input type="text" value="https://google.com"><br>
<button>Load via XHR</button>

Note that this only gives you a method to detect when an XHR has finished loading, and not control over its return value. From within the function that does console.log, you do however have access to the XHR itself, via ev.target.
You could also create hooking points to modify the loaded content before it reaches the code on the page, but that would require a couple more hooks, because listeners can be added in more than one way (.onload, .onreadystatechange, .addEventListener, etc), but it would be doable if necessary.


text:
Q: How unique is MPMediaItemPropertyPersistentID? How unique is MPMediaItemPropertyPersistentID? Will it even work when synching the list of IDs to another device connected to the same iTunes Account?
I want to implement a iCloud synchronized playlist solution which stores the IDs as a list and I need to know if this will be possible.

A: As per the documentation (emphasis mine)...

The value of the MPMediaItemPropertyPersistentID identifier persists
  across application launches and across syncs that do not change the
  sync status of the media item. The value is not guaranteed to
  persist across a sync/unsync/sync cycle.

As such, given that it won't even persist on this basis I'd be surprised if it persisted across devices in a sufficiently robust manner, if at all.

A: In my understanding this is not possible. I think this ID is persistent only for each device. It is no unique identifier for a specific song in the iTunes Store. It is only a ID for your own synced songs.
As you read the documentation, you'll see how fragile this ID could be.

"The value is not guaranteed to persist across a sync/unsync/sync cycle."

So if you sync your song database with iTunes and maybe delete a song from your iOS device and the sync again and put it back to your device, you may not get the same ID again for this song. And for sure not across other devices.
So I think, what you're trying to do will not work, until you get a worldwide identical Identifier for each song of the iTunes catalogue or your own iTunes catalogue on the Mac (where the Mac has to handle the IDs).

A: The other answers are a little big vague, so here is an answer from my own experiences and tests:
1) You can't use MPMediaItemPropertyPersistentID to get an ID that is equal between devices.
2) The MPMediaItemPropertyPersistentID will change when the device is synced with another iTunes library or all music is removed from the device and then synced again.
The ID get's created and stored by iTunes when the song is synced on the device. If it's unsynced, the ID get's deleted.

A: In case somebody else lands here, like me, using a Google search:
I confirmed what middaparka said above after an iOS upgrade of my device, when my music app tried to use persistentIDs from before the upgrade.  The IDs had changed, and I ended up (unwittingly) listening to many songs from my library that I don't normally listen to...
So I took middaparka's advice and constructed a persistentKey by exclusive-oring the hashes from title, artistName, albumTitle and duration.  Building the persistentKey during Core Database initialization will be save time later, by avoiding multiple string comparisons when fetching items in "normal operating code."
The persistentKey strategy worked properly for songs.  However, when I made a hash for albums from title, artist and releaseYear, I ended up with one collision.
I had two self-titled albums by different artists released in 1976.  When the hashes for the album title and the artist were exclusive-ored, they cancelled each other out.  I ended up using the hash for the duration instead of the artist, and that worked.
I may end up refining the algorithm for generating the persistentKeys later...


text:
Q: The right way to pass a input to the typescript file I know about this way to send a input from the user to the typescript (angular) :
    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .
After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.
Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?
For example the user put a size of text and i want to use with the use on another tag on HTML ....

A: If i understand well, you re looking for $event ?
<input #input type="text" [(ngModel)]="inputColor" (input)="sendInput($event)" />

typescript side:
sendInput($event) {
  console.log('input value:', $event.data);
}

But $event.data will only contain the last typed char, is it what you re looking for ?.
EDIT:
With (input), you can have the content of input in $event.target.value:
<input #input type="text" [(ngModel)]="inputColor"
(input)="sendInput($event.target.value)" />

A: First of you you have used ngModel with input, so your inputcolor will have that value, and you can use it. But if you want it passed to a method you can do it like :-
<input type="text" [(ngModel)]="inputColor" (change)="sentInput($event.target.value) />

Change event will be fired as soon as user is done typing and click anywhere else.
then have a sendInput method in ts to copy received value in a property
public sendInput(value) {
  this.data = value;
}

OR
If you don't need two way binding, you can use ngModel for one way binding as well like :-
<input type="text" (ngModel)="inputColor" />

After this typescript value change will not impact, only change in template will be reflected in typescript variable.

A: I think you are trying to use angular input inside a html input tag, which is not possible.
You need to use a keyboard event handler like "keyup", "keydown"...
<input type="text" [(ngModel)]="inputColor" (keyup)="sendInput($event)" />