text:
Q: Heroku: Tomcat deployment issue after dependencies I am deploying application to heroku. I use tomcat 8.0.27 and Java 7 and locally it works fine. My pom.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.app</groupId>
    <artifactId>apiexpotaxi</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>apiexpotaxi</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>br.com.caelum</groupId>
            <artifactId>vraptor</artifactId>
            <version>4.1.4</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.1.0.CR2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.github.jsimone</groupId>
                                    <artifactId>webapp-runner</artifactId>
                                    <version>8.0.30.2</version>
                                    <destFileName>webapp-runner.jar</destFileName>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

My Procfile:
web:    java $JAVA_OPTS -jar target/dependency/webapp-runner.jar --port $PORT target/*.war

This is the logs:
2016-06-14T20:00:43.690335+00:00 app[web.1]: Adding Context  for /app/target/tomcat.22571/webapps/expanded
2016-06-14T20:00:43.690206+00:00 app[web.1]: Expanding apiexpotaxi-1.0-SNAPSHOT.war into /app/target/tomcat.22571/webapps/expanded
2016-06-14T20:00:45.613401+00:00 app[web.1]: Jun 14, 2016 8:00:45 PM org.apache.coyote.AbstractProtocol init
2016-06-14T20:00:45.731190+00:00 app[web.1]: Jun 14, 2016 8:00:45 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
2016-06-14T20:00:45.778319+00:00 app[web.1]: Jun 14, 2016 8:00:45 PM org.apache.catalina.core.StandardEngine startInternal
2016-06-14T20:00:45.778328+00:00 app[web.1]: INFO: Starting Servlet Engine: Apache Tomcat/8.0.30
2016-06-14T20:00:45.613410+00:00 app[web.1]: INFO: Initializing ProtocolHandler ["http-nio-22571"]
2016-06-14T20:00:45.761602+00:00 app[web.1]: INFO: Starting service Tomcat
2016-06-14T20:00:45.731199+00:00 app[web.1]: INFO: Using a shared selector for servlet write/read
2016-06-14T20:00:45.761592+00:00 app[web.1]: Jun 14, 2016 8:00:45 PM org.apache.catalina.core.StandardService startInternal
2016-06-14T20:00:46.322486+00:00 heroku[web.1]: State changed from starting to up
2016-06-14T20:00:46.781935+00:00 app[web.1]: Jun 14, 2016 8:00:46 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
2016-06-14T20:00:46.781946+00:00 app[web.1]: INFO: No global web.xml found
2016-06-14T20:00:49.769814+00:00 app[web.1]: Jun 14, 2016 8:00:49 PM org.apache.catalina.core.ContainerBase startInternal
2016-06-14T20:00:49.769825+00:00 app[web.1]: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
2016-06-14T20:00:49.769830+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
2016-06-14T20:00:49.769829+00:00 app[web.1]:    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
2016-06-14T20:00:49.769831+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
2016-06-14T20:00:49.769831+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2016-06-14T20:00:49.769824+00:00 app[web.1]: SEVERE: A child container failed during start
2016-06-14T20:00:49.769829+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.769839+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:745)
2016-06-14T20:00:49.769840+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
2016-06-14T20:00:49.769836+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
2016-06-14T20:00:49.769839+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
2016-06-14T20:00:49.769842+00:00 app[web.1]:    ... 6 more
2016-06-14T20:00:49.769826+00:00 app[web.1]:    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
2016-06-14T20:00:49.769841+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
2016-06-14T20:00:49.769843+00:00 app[web.1]: Caused by: java.lang.NoClassDefFoundError: Ljavax/enterprise/event/Event;
2016-06-14T20:00:49.769844+00:00 app[web.1]:    at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
2016-06-14T20:00:49.769843+00:00 app[web.1]:    at java.lang.Class.getDeclaredFields0(Native Method)
2016-06-14T20:00:49.769846+00:00 app[web.1]:    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:256)
2016-06-14T20:00:49.769828+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
2016-06-14T20:00:49.769848+00:00 app[web.1]:    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:774)
2016-06-14T20:00:49.769848+00:00 app[web.1]:    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:334)
2016-06-14T20:00:49.769844+00:00 app[web.1]:    at java.lang.Class.getDeclaredFields(Class.java:1916)
2016-06-14T20:00:49.769846+00:00 app[web.1]:    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationFilterAnnotations(WebAnnotationSet.java:105)
2016-06-14T20:00:49.769845+00:00 app[web.1]:    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
2016-06-14T20:00:49.769827+00:00 app[web.1]:    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
2016-06-14T20:00:49.769847+00:00 app[web.1]:    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:64)
2016-06-14T20:00:49.769851+00:00 app[web.1]:    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
2016-06-14T20:00:49.769849+00:00 app[web.1]:    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
2016-06-14T20:00:49.769852+00:00 app[web.1]:    ... 6 more
2016-06-14T20:00:49.769853+00:00 app[web.1]: Caused by: java.lang.ClassNotFoundException: javax.enterprise.event.Event
2016-06-14T20:00:49.769850+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
2016-06-14T20:00:49.769854+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
2016-06-14T20:00:49.769855+00:00 app[web.1]:
2016-06-14T20:00:49.769852+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.771558+00:00 app[web.1]: Jun 14, 2016 8:00:49 PM org.apache.catalina.core.ContainerBase startInternal
2016-06-14T20:00:49.771569+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
2016-06-14T20:00:49.771568+00:00 app[web.1]:    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
2016-06-14T20:00:49.771566+00:00 app[web.1]: SEVERE: A child container failed during start
2016-06-14T20:00:49.771570+00:00 app[web.1]:    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
2016-06-14T20:00:49.771568+00:00 app[web.1]:    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
2016-06-14T20:00:49.769855+00:00 app[web.1]:    ... 20 more
2016-06-14T20:00:49.771567+00:00 app[web.1]: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
2016-06-14T20:00:49.771570+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.769853+00:00 app[web.1]:    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
2016-06-14T20:00:49.769850+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
2016-06-14T20:00:49.771571+00:00 app[web.1]:    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
2016-06-14T20:00:49.771572+00:00 app[web.1]:    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
2016-06-14T20:00:49.771573+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.771574+00:00 app[web.1]:    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:344)
2016-06-14T20:00:49.771575+00:00 app[web.1]:    at webapp.runner.launch.Main.main(Main.java:261)
2016-06-14T20:00:49.771575+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
2016-06-14T20:00:49.771576+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
2016-06-14T20:00:49.771572+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.771580+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
2016-06-14T20:00:49.771582+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:924)
2016-06-14T20:00:49.771580+00:00 app[web.1]:    at java.lang.Thread.run(Thread.java:745)
2016-06-14T20:00:49.771581+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: A child container failed during start
2016-06-14T20:00:49.771577+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
2016-06-14T20:00:49.771579+00:00 app[web.1]:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
2016-06-14T20:00:49.771582+00:00 app[web.1]:    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
2016-06-14T20:00:49.771583+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.771584+00:00 app[web.1]:    ... 6 more
2016-06-14T20:00:49.772589+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Tomcat]]
2016-06-14T20:00:49.772259+00:00 app[web.1]: Exception in thread "main" org.apache.catalina.LifecycleException: Failed to start component [StandardServer[-1]]
2016-06-14T20:00:49.772357+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
2016-06-14T20:00:49.771584+00:00 app[web.1]:
2016-06-14T20:00:49.772665+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
2016-06-14T20:00:49.772420+00:00 app[web.1]:    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:344)
2016-06-14T20:00:49.772486+00:00 app[web.1]:    at webapp.runner.launch.Main.main(Main.java:261)
2016-06-14T20:00:49.771578+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
2016-06-14T20:00:49.772732+00:00 app[web.1]:    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
2016-06-14T20:00:49.771578+00:00 app[web.1]:    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2016-06-14T20:00:49.773065+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
2016-06-14T20:00:49.772797+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.772869+00:00 app[web.1]:    ... 2 more
2016-06-14T20:00:49.773535+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: A child container failed during start
2016-06-14T20:00:49.772991+00:00 app[web.1]: Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat]]
2016-06-14T20:00:49.773298+00:00 app[web.1]:    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
2016-06-14T20:00:49.773365+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.773427+00:00 app[web.1]:    ... 4 more
2016-06-14T20:00:49.773742+00:00 app[web.1]:    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2016-06-14T20:00:49.773610+00:00 app[web.1]:    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:924)
2016-06-14T20:00:49.773679+00:00 app[web.1]:    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
2016-06-14T20:00:49.773800+00:00 app[web.1]:    ... 6 more
2016-06-14T20:00:50.975298+00:00 heroku[web.1]: Process exited with status 1
2016-06-14T20:00:50.990864+00:00 heroku[web.1]: State changed from up to crashed
2016-06-14T20:03:31.360718+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=apiexpotaxi.herokuapp.com request_id=ab5586dd-92e3-480a-bce3-18c9999cf39b fwd="187.19.195.154" dyno= connect= service= status=503 bytes=

Before my depencies was like that and it was working fine:
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>


text:
Q: Find the probability that all nodes are working, knowing that first node is down? We have N nodes each might go down with probability p. What is probability of running 2nd, ..., Nth node while 1st is down?
I thought it should be like:
$p*(1-p)^{N-1}$
but correct one is:
$(1-p)^{N-1}$
sorry for home work question, but I am really confused. Should it be calculated as a joint probability or otherwise.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQLAlchemy ORM select multiple entities from subquery I need to query multiple entities, something like session.query(Entity1, Entity2), only from a subquery rather than directly from the tables. The docs have something about selecting one entity from a subquery but I can't find how to select more than one, either in the docs or by experimentation.
My use case is that I need to filter the tables underlying the mapped classes by a window function, which in PostgreSQL can only be done in a subquery or CTE.
EDIT: The subquery spans a JOIN of both tables so I can't just do aliased(Entity1, subquery).

A: I was trying to do something like the original question: join a filtered table with another filtered table using an outer join. I was struggling because it's not at all obvious how to:

*

*create a SQLAlchemy query that returns entities from both tables. @zzzeek's answer showed me how to do that: get_session().query(A, B).

*use a query as a table in such a query. @zzzeek's answer showed me how to do that too: filtered_a = aliased(A).filter(...).subquery().

*use an OUTER join between the two entities. Using select_from() after outerjoin() destroys the join condition between the tables, resulting in a cross join. From @zzzeek answer I guessed that if a is aliased(), then you can include a in the query() and also .outerjoin(a), and it won't be joined a second time, and that appears to work.

Following either of @zzzeek's suggested approaches directly resulted in a cross join (combinatorial explosion), because one of my models uses inheritance, and SQLAlchemy added the parent tables outside the inner SELECT without any conditions! I think this is a bug in SQLAlchemy. The approach that I adopted in the end was:
filtered_a = aliased(A, A.query().filter(...)).subquery("filtered_a")
filtered_b = aliased(B, B.query().filter(...)).subquery("filtered_b")
query = get_session().query(filtered_a, filtered_b)
query = query.outerjoin(filtered_b, filtered_a.relation_to_b)
query = query.order_by(filtered_a.some_column)

for a, b in query:
    ...

A: from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    bs = relationship("B")

class B(Base):
    __tablename__ = "b"

    id = Column(Integer, primary_key=True)

    a_id = Column(Integer, ForeignKey('a.id'))

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([A(bs=[B(), B()]), A(bs=[B()])])
s.commit()

# with_labels() here is to disambiguate A.id and B.id.
# without it, you'd see a warning
# "Column 'id' on table being replaced by another column with the same key."
subq = s.query(A, B).join(A.bs).with_labels().subquery()

# method 1 - select_from()
print s.query(A, B).select_from(subq).all()

# method 2 - alias them both.  "subq" renders
# once because FROM objects render based on object
# identity.
a_alias = aliased(A, subq)
b_alias = aliased(B, subq)
print s.query(a_alias, b_alias).all()


text:
Q: Using Thymeleaf to set column widths in a table I have a table, where the first column will be of a fixed width, and the remaining column widths will take up the remaining pace equally.  The issue is that the columns are generated using th:each and the number of columns will vary.
How can I set the first column to a fixed width, and divide the remaining space equally between an unknown number of columns?

                Fixed width

                Dynamic width

A: You can calculate the widths like this:

      Dynamic width


text:
Q: Updating Database through c# code :)
I've started with project of creating some program for Library. I mean, it is a simple program which has login form and some features for admin. Also, I've done database (everything is done with Visual Studio 2013), SQL Service-based Database. I followed some Youtube tutorials and now when I added button for adding users in database I run into "problem". This is code for Add button:
private void btnAdd_Click(object sender, EventArgs e)
        {
        string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.KnjiznicaDBConnectionString"].ConnectionString;
            string query = "INSERT INTO User VALUES(@Name,@Surname,@Year,@Mail)";
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand(query, connection);
            {
                connection.Open();
                command.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                command.Parameters.AddWithValue("@Surname", txtSurname.Text.Trim());
                command.Parameters.AddWithValue("@Year", txtYear.Text.Trim());
                command.Parameters.AddWithValue("@Mail", txtMail.Text.Trim());
                command.ExecuteScalar();
            }
        }

Now, I know that user is added into database, because I can see it in DataGridView which is also in Form, but when I check directly in Database (I mean in Server Explorer->Database_name->Tables->User (Show Table Data)), that new user is actually not added there. And no matter if I exit Visual Studio, as long as I don't shut down computer, that new User will be in DataGridView but not in "Database". And when I restart computer and start Visual Studio again, new user won't be even in DataGridView. Only permanent users are those that I add directly through Show Table Data or with New Query also in Server Explorer.
I would like to know what should I correct so all users added through the code and Form are implemented in "real Database" not just DataGridView.
Thanks :)

A: Wrong command
You need SqlCommand.ExecuteNonQuery
And you would be wrapping open and command in Using blocks


text:
Q: How to remove whitespaces in individual list elements in nested lists from a text file? I'm really struggling with this one, any help would be appreciated. Trying to get rid of whitespaces around individual list elements. I have tried putting the strip() in various places but I can't figure out how to get it to work properly. :
DATAFILE = "unit-patterns.txt"

with open (DATAFILE, "r") as file:
    pattern_strings = []
    pattern_lists1 = []
    pattern_lists = []
    ex_whtspc_lst = []

    for line in file:
        pattern_strings.append(line.split("\t"))

for index in pattern_strings:
    pattern_lists1.append(index[0])

for ele in pattern_lists1:
    pattern_lists.append(ele.split("+"))

print(str(pattern_lists[0:5]).strip())

I get whitespaces around each list element like this:
"[-CITS2224-1-]" - dashes to indicate whitespaces
Text file
Expected output

A: The problem you are facing is that the .strip() method "returns a copy of the string with the leading and trailing characters removed".
In your example, in the [ CITS2224 1 ] string, the leading character is [ and the trailing character is ]. This causes a regular .strip() call to return the string unmodified.
If you pass the []  characters to the .strip() call, as suggested by @Tranbi, it will work correctly. Why? This will make python strip any leading and trailing []  characters until a different character is encountered.
Keep in mind that .strip("[] ") won't strip the brackets or whitespaces from inside the string, for example [ foo [] bar ] - you will get foo [] bar instead. Again, this is because .strip() considers only the characters passed in the argument (or whitespace if no arguments). If it encounters a character outside of it's interest, processing is stopped.


text:
Q: publics key between windows 2012 server and aix system I am have problem with my keys generated in both system Windows server 2012 and Aix version 7.20
The sftp or ssh from windows to aix is working (no password require to connect) but the same sftp or ssh from Aix to Windows prompt me for password.  When i ssh_add id_rsa.pub I have this message
Permissions for 'id_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
thanks


text:
Q: TCPDF: Two Independent Columns with page break I want to create a page with 2 independent columns. If the text does not fit in one colum on one page it should be continued on the next page with the same column setup.
I tried using setColumnsArray and selectColumn the problem with this is, that if the first column is full it continues on the next column instead on the next page.
It there a posibility to achive this?
Thank You

A: See Sample10 which is doing exactly what you are asking for:

*

*PHP Source code: http://www.tcpdf.org/examples/example_010.phps

*Final PDF: http://www.tcpdf.org/examples/example_010.pdf
Sample7 might help too but column spreads over multiple pages:

*

*PHP Source code: http://www.tcpdf.org/examples/example_007.phps

*Final PDF: http://www.tcpdf.org/examples/example_007.pdf

A: I solved the problem now without writing everything in html.
I used to following aproache:

*

*Save the top of the columns with getY and getPage.

*Write the first column

*Use setY and setPage to go back to the top of the second column

*Use setX to move the seconds column on the right side.

*Using the following hack to get around the problem with different page borders on right and left pages on the second column:
if ($curPage<>$pdf->getPage())
{
  $curPage=$pdf->getPage();
  if (($curPage % 2)==1)
  {
    $xPos+=15;
  }
  else
  {
    $xPos-=15;
  }
}
$pdf->SetX($xPos);


text:
Q: Get image file names with Python pptx I'm trying to write a script that opens a user specified ppt, reads it and finds image file names. Im using the python pptx package since this lets me actually open ppt files. Im trying to go through each slide and check that slide for images but I have no idea how to do this with the pptx package and the documentation isn't really clear on this imo.
So after a bit more digging into the documentation i've found that this kind of does the job:
file = open(fileName, 'rb')
ppt = Presentation(file)
images = []

for slide in ppt.slides:
    for shape in slide.shapes:
        print(shape.image)
        if shape.image:
            if isCorrectImageType(shape.image):
                print(shape.image.filename)
file.close()

def isCorrectImageType(imageShape):
    imgExtension = imageShape.content_type
    filePattern = '(.jpg$|.jpeg$|.png$|.gif$)'
    image = re.search(filePattern, imgExtension)
    print(image.group(0))

    return image.group(0)

This works however it doesnt return the correct filename. It returns image.png while the filename is myfile.png

A: The image filename is only stored in the XML if the image is inserted from a file. If the image is imported from a binary stream (by a program such as python-pptx) there is no filename available and so the image.{ext} form is used instead. This is also the case when an image is pasted into place using PowerPoint.
So the filename is not necessarily always available.
However, when it has been recorded, it is available in the descr attribute of the picture shape:
from pptx.enum.shapes import MSO_SHAPE_TYPE

for shape in slide.shapes:
    if shape.shape_type != MSO_SHAPE_TYPE.PICTURE:
        continue
    picture = shape
    print(picture._pic.nvPicPr.cNvPr.get('descr'))

This code accesses the XML that looks like this:
<p:pic>
  <p:nvPicPr>
    <p:cNvPr id="6" name="Picture 5" descr="python-logo.gif"/>
    <p:cNvPicPr/>
    <p:nvPr/>
  </p:nvPicPr>
  ...

and should return the value 'python-logo.gif'.


text:
Q: Click on checkboxes that are dynamically growing with in the page I have a query regarding the handling on check boxes in a section. The HTML code is.

Self-Pay

<input id="selectAll" type="checkbox" name="selectAllCheckBox" onclick="stopPayerClick()"/>
 Select All

<input id="AUX01" type="checkbox" name="PayerCheckBox" onclick="stopPayerClick()"/>
 AUXIANT

<input id="52312" type="checkbox" name="PayerCheckBox" onclick="stopPayerClick()"/>
 Arbor Health Plan

<input id="00715" type="checkbox" name="PayerCheckBox" onclick="stopPayerClick()"/>
 BCBS Indiana

Currently there are 4 check boxes in the above code but there are some other check boxes in other parts of page which will be checked if I use the code below
IList<IWebElement> selectElements = driver.FindElements(By.TagName("checkbox"));

Please help me how to check only those 4 check boxes ignoring the rest of the checkboxes in the list

A: I would write a proper selector that only targets those four elements.
By css = By.CssSelector("li#SelfPay input[type='checkbox']");
IList selectElements = driver.FindElements(css);

And, that should only return the four checkboxes under the li element with id='SelfPay'


text:
Q: Parallel between probability,wait time, frequency and period I was reading about the geometric distribution, where $E(X) = 1/p$. This made me think of the classic formula in physics: $t=1/f$. Is there a parallel between both formulas, especially since a probability is often viewed as a frequency, and, on the other side of both equations, I have a time?
Assume we do a Bernoulli trial every second with a probability $p=0.01$. If we assign 1 to a success and zero to a failure, we can create a random time-series, or a signal where the long-term average frequency should be 0.01 Hz. The long-term average period of this signal, $t$ should be $1/f = 100$ seconds.

*

*I can expect, on average, to see a full cycle ($t$) every 100 seconds if $f$=0.01Hz.

*I can expect, on average, my first success after 100 seconds: $E(X)$ of a geometric distribution with p = 0.01, and one draw per second.

Is the resemblance in the two formulas a coincidence, and if so, where is the flaw in the logic? Or is there a parallel across physics and statistics? And if so, how could this be explained more rigorously?


text:
Q: Symfony and PHPUnit with Bitbucket pipelines I am trying to set up a pipeline to automatically execute my test suite using Bitbucket.
Unfortunately I am completely new to Docker and pipelines. I read this article and after a lot of trial and errors I came up with this bitbucket-pipelines.yml configuration:
image: php:7.2.17

pipelines:
  default:
    - step:
        caches:
          - composer
        script:
          - apt-get update && apt-get install -y unzip zlib1g-dev sqlite3 libsqlite3-dev
          - docker-php-ext-install zip && docker-php-ext-install pdo_sqlite && docker-php-ext-install pdo_mysql
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install
          - vendor/bin/simple-phpunit

The problem is that this configuration still displays an error:
  [RuntimeException]
  An error occurred when executing the "'cache:clear --no-warmup'" command:

  In ConnectionFactory.php line 79:

    An exception occured while establishing a connection to figure out your pla
    tform version.
    You can circumvent this by setting a 'server_version' configuration value

    For further information have a look at:
    https://github.com/doctrine/DoctrineBundle/issues/673

  In AbstractMySQLDriver.php line 93:

    An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused

  In PDOConnection.php line 31:

    SQLSTATE[HY000] [2002] Connection refused

  In PDOConnection.php line 27:

    SQLSTATE[HY000] [2002] Connection refused

Why is it trying to connect using MySQL? Shouldn't it be executing tests only? I don't need the project running or a deployable version, I just need the test suite executed using SQLite and unit tests.

A: Doctrine tries to guess your MySQL/PostgreSQL version. It therefore tries to establish a connection to the database when creating the adapter.
This behavior can be circumvented by configuring a concrete version in your configuration.
# config.yaml

doctrine:
  dbal:
    # [..]
    server_version: '5.7' # or mariadb-<version> for MariaDB

You can find more information about this "issue" in the notice below the configuration overview in the documentation chapter Doctrine DBAL Configuration.
Just add server_version to config_test.yaml to resolve your issue.

A: See this example please:
# This is a sample build configuration for PHP.
# Check our guides at https://confluence.atlassian.com/x/e8YWN for more examples.
# Only use spaces to indent your .yml configuration.
# -----
# You can specify a custom docker image from Docker Hub as your build environment.
image: medtrainermx/php:5.6
pipelines:
  branches:
    '**':
      - step:
          name: "Build"
          caches:
            - composer
          script:
            - cp symfony/app/config/local.yml.dist symfony/app/config/local.yml
            - cp symfony/tests/config.local.php.dist symfony/tests/config.local.php
            - cd symfony/tests
            - composer install
          artifacts:
            - build/**
            - symfony/vendor/**
            - symfony/app/config/local.yml
            - symfony/app/cache/**
            - symfony/tests/vendor/**
            - symfony/tests/config.local.php
      - step:
          name: "Coding Standards"
          caches:
            - composer
          script:
            - cd symfony
            - mkdir app/cache
            - ./bin/phpcs --cache=app/cache/.phpcs-cache
      - step:
          name: "Unit Tests"
          services:
            - mysql
          caches:
            - composer
          script:
            - cd symfony
            - ./bin/phpunit --testsuite=unit --debug
definitions:
  services:
    mysql:
      image: mysql:5.7
      environment:
        MYSQL_DATABASE: 'test'
        MYSQL_ROOT_PASSWORD: 'password'

in this configuration i use my own image to uses in bitbucket pipeline


text:
Q: How to use dynamic foreignkey in Django? I want to connect a single ForeignKey to two different models.
For example:
I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic?
class Articles(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

class Casts(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

class Faves(models.Model):
    post = models.ForeignKey(**---CASTS-OR-ARTICLES---**)
    user = models.ForeignKey(User,unique=True)

Is this possible?

A: Here is how I do it:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields

class Photo(models.Model):
    picture = models.ImageField(null=True, upload_to='./images/')
    caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = fields.GenericForeignKey('content_type', 'object_id')

class Article(models.Model):
    ....
    images     = fields.GenericRelation(Photo)

You would add something like
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = fields.GenericForeignKey('content_type', 'object_id')

to Faves
and
    fields.GenericRelation(Faves)

to Article and Cast
contenttypes docs

A: Here's an approach.  (Note that the models are singular, Django automatically pluralizes for you.)
class Article(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

class Cast(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

FAVE_CHOICES = (
    ('A','Article'),
    ('C','Cast'),
)
class Fave(models.Model):
    type_of_fave = models.CharField( max_length=1, choices=FAVE_CHOICES )
    cast = models.ForeignKey(Casts,null=True)
    article= models.ForeigKey(Articles,null=True)
    user = models.ForeignKey(User,unique=True)

This rarely presents profound problems.  It may require some clever class methods, depending on your use cases.


text:
Q: Beta Function: Prove $B(x,y) = B (x, y +1) + B (x+1 , y)$ How can I prove the following $B(x,y) = B (x, y +1) + B (x+1 , y)$? Perhaps I can use Gamma functions to prove it? Does anyone know the proof?

A: $$B(x,y)= {\Gamma{(x)}\Gamma{(y)} \over {\Gamma(x+y)}}, \text{ and }\Gamma(r+1)=r\Gamma(r), \text{therefore,} $$
$$
B(x+1,y)= {\Gamma{(x+1)}\Gamma{(y)} \over {\Gamma(x+y+1)}} = \left({x\over{x+y}} \right){\Gamma{(x)}\Gamma{(y)} \over {\Gamma(x+y)}} = B(x,y)\left({x\over{x+y}} \right)
$$
$$
B(x,y+1)= {\Gamma{(x)}\Gamma{(y+1)} \over {\Gamma(x+y+1)}} = \left({y\over{x+y}} \right){\Gamma{(x)}\Gamma{(y)} \over {\Gamma(x+y)}} = B(x,y)\left({y\over{x+y}} \right)
$$
Therefore,
$$
B(x+1,y)+B(x,y+1)=B(x,y)\left({x\over{x+y}} + {y\over{x+y}}\right)=B(x,y)
$$

A: just write down the RHS explicitly
$$B (x, y +1) + B (x+1 , y) = \int_0^1 t^{x-1}(1-t)^{y} + t^{x}(1-t)^{y-1}\,dt = \int_0^1 t^{x-1}(1-t)^{y-1}(1-t+t)\,dt = \int_0^1 t^{x-1}(1-t)^{y-1} = B (x, y) $$

A: $$\begin{align*}\operatorname{B}(x,y) & =\int\limits_0^1dt\, t^{x-1}(1-t)^{y-1}\\ & =\int\limits_0^1dt\, t^{x-1}(1-t)^{y-1}(1-t+t)\\ & =\int\limits_0^1dt\, t^{x-1}(1-t)^y+\int\limits_0^1dt\, t^x(1-t)^{y-1}\\ & =\operatorname{B}(x,y+1)+\operatorname{B}(x+1,y)\end{align*}$$


text:
Q: Create only objects used in Java EE Given the EJB below, will the container be intelligent enough to only create the object that is used?
@Stateless
public class MyBean {

   @EJB
   Clazz1 obj1;

   @EJB
   Clazz2 obj2;

   public void run(int x) {

     if (x == 1)
         obj1.printCode();
     else
         obj2.printCode();

   }
 }

A: The container will have to resolve all dependencies of the bean (instantiate them first) before instantiating the bean itself.
Now what truly happens when you invoke a method might differ...
You are using purely EJB here, there isn't any speck of CDI in your code!
@EJB is an EJB annotation for dependency injection and @Stateless is an EJB annotation for a "scope".
If you were to use CDI and had Weld as its implementation (all EE servers apart from tomee) then you would get lazy instantiation for any normal scoped beans. That would mean that you in fact inject an "empty" proxy object and it will only be instantiated upon first access.
Now, what I mean by CDI injection - use @Inject instead of @EJB.
You can still have your bean @Stateless, CDI, if it's running in your app, then wraps it with it's own scope.
I also said that you need normal scoped beans - that means beans which use proxies.
Those are pretty much all CDI scopes except @Dependent. Therefore it's @RequestScoped, @SessionScoped, @ApplicationScoped. The dependencies of your bean would have to have those scopes to achieve lazy init.


text:
Q: Prime elements of $\mathbb{C}[x]$ which remain prime in a simple algebraic ring extension Let $w$ be an algebraic element over $\mathbb{C}[x]$, with minimal polynomial $f(t)=c_mt^m+\cdots+c_1t+c_0$, $c_i \in \mathbb{C}[x]$.

Is it possible to find all prime elements of $\mathbb{C}[x]$ which remain prime in $R=\mathbb{C}[x][w]$? (in case $R$ has prime elements). Perhaps a partial answer should be in terms of the $c_j$'s.

Remarks: An irreducible element of $\mathbb{C}[x]$ is of the form $ax+b$,
$0 \neq a,b \in \mathbb{C}$, because $\mathbb{C}$ is algebraically closed (we can replace $\mathbb{C}$ by any algebraically closed field).
Also, $\mathbb{C}[x]$ is a UFD, so irreducibles= primes.
Non-example: $R= \mathbb{C}[x][x^{3/2}]$, $f(t)=t^2-x^3$ is the minimal polynomial of $w=x^{3/2}$. Notice that $x$ is prime in $\mathbb{C}[x]$, but it is not prime in $R$, because $xxx=x^{3/2}x^{3/2}$, namely, $x$ divides the product $x^{3/2}x^{3/2}$, but $x$ does not divide $x^{3/2}$. Actually, $R$ does not have prime elements, see this question.
This is a relevant question.

A: An element of the form $x-a\in\mathbb{C}[x]$ remains prime  in $\mathbb{C}[x][w]$, where $w$ satisfies your equation, which I assume is irreducible, if and only if $c_m(a)=\cdots=c_2(a)=0$ and $c_1(a)\neq 0$.
I will elaborate, as you requested, on my answer. Let $f(w)\in\mathbb{C}[w]=A$ be any non-zero polynomial. Then $A/fA$ is a domain if and only if it is a field if and only if $f$ is linear.
In your case, $x-a$ is a prime in $R$ if and only $R/(x-a)R=\mathbb{C}[w]/f(a,w)$ is a domain, where $f(a,w)=c_m(a)w^m+\cdots +c_2(a)w^2+c_1(a)w+c_0(a)$. I hope the rest is clear.

A: OK let's do some algebraic geometry. I realize that wasn't the tag you gave, but that's what we're doing. Each $(x-a)\in\mathbb{C}[x]$ would correspond to a point $a$ on the complex line. Hence when you pass to $\mathbb{C}[x,w]$, $(x-a)$ now corresponds to not a point but in fact the (sort of, considering we're in four dimensions) vertical line over that point consisting of all points of the form $(a,y)$ where $y\in\mathbb{C}$. A vertical line is still irreducible in the plane, so $(x-a)$ must remain prime (as prime ideals correspond to irreducible varieties/geometric objects). I'm trying to dance around using the technical language of algebraic geometry (which you may not know) and the very intuitive picture which answers your question haha.


text:
Q: Without updating the column values in Oracle , is there a way to store the data in a variable and get a count on those data using where condition? I am new to Oracle. I need some help in this. So the scenario is that without updating any column value in the table I have to store a DATE value and from that DATE value I have to get a count based on a where condition, which i know we will use a '<=' operator.
For Example,lets say i have a column "Sweep_Date", in this column,for the time being all the values are nulll.
I am having nearly 2,92,300 rows in which I have to update the date values. But without updating the Sweep_Date column, Is there any way that i can store some dates in the column, for which i can write a where condition and get the count(*) from the table based upon the WHERE condition applied??
Can we use a temp Variable??
Any help is appreciated......

A: Aha, I think I got it.
If sweep_date is empty and you can't/won't update it, then use NVL function. For example:
select count(*)
from your_table t
where nvl(t.sweep_date, date '2020-04-28') > t.some_other_date;

If you use date column from another table, then join tables and use another table's column in NVL. For example:
select count(*)
from your_table t join another_table j on j.some_id = t.some_id
where nvl(t.sweep_date, j.some_date) > t.some_other_date;


text:
Q: VREG output circuitry I am making a PCB and I want the ability to have multiple power sources for it. One is a DC barrel jack and another is a transformer/rectifier.
In the past I would use jumpers to allow one power circuit to be totally disconnected while the other connects, or vice versa. I'm wondering if this is necessary though because I will need to break up some power planes and have less optimal routing on my current design to accomplish this.
My board has a separate regulator for each power source. I would like to have the outputs of each regulator tied together and have either one or the other  power the circuit. Is it bad for a simple linear regulator or LDO to have voltage present at its output while the regulator input is left floating/disconnected?
I have seen some other designs use Schottky diodes in series with the outputs, but I'd rather not lose the 0.3V after the regulator output.
I will never have a situation where it is powered by both sources at once, so one regulator will always be off (its input floating). Is it bad to tie the regulator outputs together in this situation or should I use jumpers to totally isolate them from each other?
Edit: Initial searches only led to discussions of paralleling regulators for increased current, but I recently saw this post:
Can the outputs of 3 different voltage regulators be tied together?
It has been stated in that thread that the regulators could be damaged, but not much explanation why.
Thanks in advance,
Pansy

A: Your architecture doesn't make sense from what you are saying.  Combine the two power sources before the regulator, not after.  The transformer with full wave rectifier already can't be back-driven due to the diodes.  All you need is a Schottky diode in series with the DC barrel connector.  That's a good idea anyway to avoid damage when someone plugs in a wall wart with different polarity.
Combine the output of these two power sources right there.  Now you only need a single regulator, which gets around the awkward combining of the power after it's already at the final voltage.  If the wall wart and transformer output voltages vary a lot, use a switching buck converter.  Those can remain efficient over a much wider input voltage range.  If you really need extra clean linearly regulated final voltage, have the switcher make a few 100 mV more than what you need and use LDOs at the point of use.

A: Instead of Diodes you can easily put a mosfet at the output of every regulator (if you really must have serveral regulators). In this case you have (virtually) no voltage drop on the selector, assuming mosfets with very low Rds(on).
Special care has to be taken if both sources could be powered at the same time.


text:
Q: how to restore the database backup in test server database? i am using mysql database. i am trying to restore the database backup in test server.
my backup file called steer_backup.sql is stored in /root. from the command prompt i am executing the command
mysqldump - u root -p steer < steer_backup.sql

and i will give the password on asking.
but it does not restore the database. i am not sure whether i am doing some mistakes because this is my first time experience of committing the code to test server ... please help me ..
Thanks in advance

A: mysqldump is use to create a dump.
If you want to restore a sql backup, just use
mysql -u [user] -p [databaseName] < [file]

A: mysqldump is for dumping.  To import, just use mysql.
mysql -uRoot -pPassword dbname < file.sql


text:
Q: Construct data table columns on the fly dynamically Note - I followed the approach from this link - How to make columns lwc lightning-datatable dynamic with button-icon
I am trying to build a data table like below:

The column has dates which is start of the week(Sunday) of a month. Example in July - 10,17,24,31 and 7th.  I calculate the date using the apex class. In the apex wrapper.
I am not sure how I can use a single column to populate all the dates from apex. And also I need the ability to move the dates forward to next week when NEXT button on the top is clicked.
What I tried in Apex controller is to build a wrapper and logic to calculate dates:
public class ContactWrapper{
    @AuraEnabled
    public String FirstName;
    @AuraEnabled
    public Date weekStartDate;
}

@AuraEnabled(cacheable=true)
public static List<ContactWrapper> buildWrapper(){
    List<ContactWrapper> result = new List<ContactWrapper>();
    List<Contact> conList = getContactList();
    integer j = 0;
    for(integer i =0;i<4;i++){
        ContactWrapper wrpObj = new ContactWrapper();
        wrpObj.FirstName = conList[i].FirstName;
        wrpObj.weekStartDate = Date.today().toStartofWeek().addDays(j);
        j = j + 7;
        result.add(wrpObj);
    }

    return result;
}

ThE JS:
import { LightningElement, wire } from 'lwc';
import buildWrapper from '@salesforce/apex/ContactController.buildWrapper';

const COLS = [
    { label: 'First Name', fieldName: 'FirstName' },
];
export default class DatatableCustomDataType extends LightningElement {
    columns = COLS;
    contacts;

    @wire(buildWrapper)
     wiredContacts(result){
         console.log('result---> ' + JSON.stringify(result.data));
 if (result.data) {
    this.columns = [...this.columns, ...result.data.weekStartDate];
 }
    }

}

HTML:
<template>
    <lightning-card
        title="Datatable Custom Data Type"
        icon-name="custom:custom62"
    >
    <lightning-button variant="brand" label="Go Next" title="Primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
        <div class="slds-var-m-around_medium">

            <template if:true={contacts}>
                <c-custom-data-types
                    key-field="Id"
                    data={contacts}
                    columns={columns}
                    hide-checkbox-column="true"
                >
                </c-custom-data-types>
            </template>
        </div>

    </lightning-card>
</template>

How can I dynamically change the columns from what is returned from the apex wrapper:
const COLS = [
    { label: 'First Name', fieldName: 'FirstName' },
    // the dates july 10, Juy 17, July 24 and July 31 should dynamically build.
];

Apex Class:
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {
        return [
            SELECT
                Id,
                Name,
                FirstName,
                LastName,
                Title,
                Phone,
                Email,
                Picture__c
            FROM Contact
            WHERE Picture__c != NULL
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }

    @AuraEnabled(cacheable=true)
    public static List<Contact> findContacts(String searchKey) {
        String key = '%' + searchKey + '%';
        return [
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WHERE Name LIKE :key AND Picture__c != NULL
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }

    @AuraEnabled(cacheable=true)
    public static Contact getSingleContact() {
        return [
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WITH SECURITY_ENFORCED
            LIMIT 1
        ];
    }

    @AuraEnabled
    public static void updateContacts(List<Contact> contactsForUpdate) {
        // Make sure we can update the database before trying to update
        if (!Schema.sObjectType.Contact.isUpdateable()) {
            throw new SecurityException(
                'Insufficient permissions to update contacts'
            );
        }
        update contactsForUpdate;
    }

    public class ContactWrapper{
        @AuraEnabled
        public String FirstName;
        @AuraEnabled
        public Date weekStartDate;
    }

    @AuraEnabled(cacheable=true)
    public static List<ContactWrapper> buildWrapper(){
        List<ContactWrapper> result = new List<ContactWrapper>();
        List<Contact> conList = getContactList();
        integer j = 0;
        for(integer i =0;i<4;i++){
            ContactWrapper wrpObj = new ContactWrapper();
            wrpObj.FirstName = conList[i].FirstName;
            wrpObj.weekStartDate = Date.today().toStartofWeek().addDays(j);
            j = j + 7;
            result.add(wrpObj);
        }

        return result;
    }
}

Anything I can refer to implement this? Please let me know.
My code base is based on lwc-receipe - https://github.com/trailheadapps/lwc-recipes/blob/main/force-app/main/default/lwc/datatableCustomDataType/datatableCustomDataType.html

A: As it will be a very long answer to write in full, I will try to explain the approach I have in my mind. There are two parts you need to do.
A: Columns
You need to get the weekStartDate from the apex and then you can build all 7 columns in the lwc or apex controller in this format.
[{
    fieldName: 'day_1',
    label: 'Aug 01',
    type: 'yourCustomType'
},
// ...
{
    fieldName: 'day_7',
    label: 'Aug 07',
    type: 'yourCustomType'
}]

For this, you can run a for loop to generate the above list and
use date format methods from apex/js to format the column label as per your need.
B: Data
You need to format data in such a way that one row contains data for one week.
like:
[
    {
        day_1: 'value 1',
        day_2: 'value 2',
        //...
        day_7: 'value 7',

        // add additional fields if needed.
    },
    {
        day_1: 'value 1',
        day_2: 'value 2',
        //...
        day_7: 'value 7',

        // add additional fields if needed.
    },
    {
        day_1: 'value 1',
        day_2: 'value 2',
        //...
        day_7: 'value 7',

        // add additional fields if needed.
    },

    // ...

]

You can create a wrapper class to store the data in apex like this.
public class WeekDataWrapper{
    @AuraEnabled
    public DataType day_1;
    @AuraEnabled
    public DataType day_2;
    //...

    @AuraEnabled
    public DataType day_7;
}

Please note that I am suggesting generic names for fields instead of dates so that you can do the pagination easily. Also, you can use the apex map if the number of days is dynamic.
Use the below type instead of the wrapper to store data if you want to keep a number of columns dynamic.
List<Map<String>, Object>> getData(){}

where the keys will be the day example day_1 to day_N, and the value will be the data you want to display. You can return this list of maps as it is and JS will automatically convert that to a list of objects very similar to the wrapper format provided above.
You can refer to this post for datatable pagination.
I hope this is helpful!


text:
Q: How to open PDF as BASH variable? I'm trying to open a PDF using Preview where the input file is a shell var:
$ pdf=$(wget -qO- 'http://website.com/file.pdf') && open "$pdf"

$ pdf=$(wget -qO- 'http://website.com/file.pdf') && open -a /Applications/Preview.app -f "$pdf"

$ open -a /Applications/Preview.app $(wget -qO- 'http://website.com/file.pdf')

$ pdf=$(wget -qO- 'http://website.com/file.pdf') | open -a /Applications/Preview.app -f -

etc etc etc
I always get the same error:

-bash: /usr/bin/open: Argument list too long

Is it possible to do this?
example PDF for anyone who wants to try:
https://www.exploit-db.com/docs/english/44592-linux-restricted-shell-bypass-guide.pdf

A: Cool problem showing how amazing bash, pipes and open are. You are so close on the fourth try:
wget -qO- 'https://www.com/big.pdf' | open -f -a Preview.app

Luckily the -a argument lets the -f take the data from stdin but not open in TextEdit.

A: You can open a PDF as a Bash variable (expressed as a path to the file) like this.

*

*Set your variable:
pdf=/path/to/44592-linux-restricted-shell-bypass-guide.pdf

*Open the file like this:
open "$pdf" -a Preview

However, your example indicates that the file doesn't exist on your filesystem. If you want to open a raw data stream stored in a variable, I recommend echoing your variable, and piping it to open using the -f option like this.

*

*Define your variable:
pdf=$(wget -qO- https://www.exploit-db.com/docs/english/44592-linux-restricted-shell-bypass-guide.pdf)

*Open the raw data as a stream from standard input:
echo $pdf | open -f -a Preview

Explanation:
If you store the output of wget -qO- … as a variable, as opposed to downloading the file onto your filesystem, open won't know what to do as you're passing it the raw file data rather than the path to the file. In man open 'file' refers to an openable file for the given application, the variable in your example is not that. The -f option is useful in this scenario as your method of setting the variable involves storing the entire file stream, which won't be interpreted as a file by open, and therefore it can only be opened as a file stream.

A: The same thing @bmike suggested but without wget which isn't native to OS X
curl -so- 'https://www.example.com/some.pdf' | open -f -a Preview.app


text:
Q: spark filter (delete) rows based on values from another dataframe I have a 'big' dataset (huge_df) with >20 columns. One of the columns is an id field (generated with pyspark.sql.functions.monotonically_increasing_id()).
Using some criteria I generate a second dataframe (filter_df), consisting of id values I want to filter later on from huge_df.
Currently I am using SQL syntax to do this:
filter_df.createOrReplaceTempView('filter_view')
huge_df = huge_df.where('id NOT IN (SELECT id FROM filter_view)')

Question 1:
Is there a way to do this using Python only, i.e. without the need to register the TempView?
Question 2:
Is there a completely different way to accomplish the same thing?

A: You can use JOIN
huge_df = huge_df.join(filter_df, huge_df.id == filter_df.id, "left_outer")
                 .where(filter_df.id.isNull())
                 .select([col(c) for c in huge_df.columns]

However it will cause expensive shuffle.
Logic is simple: do left join with filter_df on id fields and check if filter_df is null - if it is null, that means that there's no such row in filter_df

A: Here is another way to do it-
# Sample data
hugedf = spark.createDataFrame([[1,'a'],[2,'b'],[3,'c'],[4,'d']],schema=(['k1','v1']))
fildf = spark.createDataFrame([[1,'b'],[3,'c']],schema=(['k2','v2']))

from pyspark.sql.functions import col
hugedf\
.select('k1')\
.subtract(fildf.select('k2'))\
.toDF('d1')\
.join(hugedf,col('d1')==hugedf.k1)\
.drop('d1')\
.show()

logic is simple, subtract the id values found in filteredDf from id values found in hugeDF leaving ID values which are not in filterDF,
I marked the subtracted values as column 'd1' just for clarity purpose and then join hugeDF table on the d1 values and dropping d1 to give final result.


text:
Q: Complex git workflow I have a scenario in which I have to maintain multiple git repositories  (each with multiple branches) on multiple servers that are not connected together (and never will be).
To simplify the idea, I will identify two hosts as A and B.
Work is performed on A by developers. They are pushing code, making branches, etc.
Work is performed on B by developers. They are pushing code, making branches, etc.
Originally, B is mirrored from A.  So they started identically.
Now I am tasked with taking code from A and bringing it to B.
Likewise, from B and taking it to A.  This will occur on a continual basis.
I am not sure idea how to accomplish this given the fact that:

*

*When I am on A's network I cannot access B.

*When I am on B's network I cannot access A.

*Developers will be creating new branches on both A and B

*Developers will be pushing code into the same named branches on both A and B.

*Plus many other scenarios I can't even think of :(

*

*Maybe implement a PR - but doesn't get merged (on both A and B) when we need to "sync up"

Basically, I am tasked with two teams of developers developing on the same repo that exists on two different networks and 'sneaker netting' the differences between them on an ongoing basis.
Originally I looked into git clone --mirror (and git lfs fetch -all since LFS is in play), and then git push --mirror. This worked fine for the initial sync.  But it cant work for maintenance.
I realize this will ultimately be done programmatically (which is fine), but I am not even sure what process flow I should take on something like this.
Thanks for any help.

A: It seems to me a scenario that can be solved with git bundle.

Some workflows require that one or more branches of development on one
machine be replicated on another machine, but the two machines cannot
be directly connected, and therefore the interactive Git protocols
(git, ssh, http) cannot be used.

You obviously need to set some rules (like limiting history rewriting), in any case you can check if you can apply the bundle using git bundle verify.


text:
Q: How to move to the top of the element? I know that .scrollTo(0,0) works for the window and returns you to the top of the page. But my goal is to return to the top of the certain element on the page. How can I do that?

function returnToTopElement(clickingObjId, element){
 let clickOn = document.getElementById(clickingObjId);
 let topElement = document.getElementById(element);
 clickOn.addEventListener('click', function(){
  topElement.scrollTo(0,0);
 });
};

returnToTopElement("top-button", "elem-b");
    .menu{
   position: fixed;
   background-color: red;
   width: 100%;
   height: 30px;
   top: 0;
    }
    .elem-a{
      height: 200px;
      width: 200px;
      background-color: #f6f6f6;
      color: black;
    }
    .elem-b{
      height: 300px;
      width: 200px;
      background-color: #263B42;
      color: white;
    }
    .top-button{
      margin-top: 200px;
      cursor: pointer;
    }
    .top-button:hover{
      background-color: #b2b2b2;
    }

 Menu

 a

      b

 Return to the top

A: HTMLElement.offsetTop is the distance between this element's top border to its offsetParent's top border, not to the top of the document.
It's also oddly complicated to calculate the relative distance between two elements. In your case, you can calculate it using the following:
topElement.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top

But this doesn't account for the top margin if there's any. So you might have to go further IF you want to include the top margin like this.
topElement.getBoundingClientRect().top
- topElement.getComputedStyle().getPropertyValue('margin-top')
- document.documentElement.getBoundingClientRect().top

You might be wondering if there's a less cumbersome way, but really, this is what you have to do in most cases.


text:
Q: Can the alert keyboard be used for any text field on iOS? I am developing my first iOS app and I really like the look of the alert keyboard. I was wondering if I can use it for any page or if there is a specific reason for it? I do not want my first app to be rejected for something this unimportant, but it would be a nice add on.

A: You can use it for anything you want, alert is nothing more than a keyboard style and there is absolutely nothing in place that tells you what you can and can not use it for.
[myTextField setKeyboardAppearance:UIKeyboardAppearanceAlert];


text:
Q: Can we push software to clients ? We need HTcondor to be installed on computers in network Which is our own campus network for throughput computing, we need maximum nodes so we can do it in a better way.
Mentioned network have many computers which are desktops, laptops some are connected to LAN and some connected through WLAN. There are 3 networks faculty, students, and senior students but for simplicity I am assuming its just single network. and they have different operating systems(Windows 7, Windows 8, Ubuntu, Windows XP) but I am assuming all have Ubuntu.
So how we can somehow broadcast it in network and install on all computers or prompt a pop up to user for installation ?
Or install it anyway on machines, I have looked and only thing i could find is Microsoft Group Policy to install software remotely but this article applies to only Windows 2000 and its not cross platform either.
How can I do that on cross platform or at least on Ubuntu machines using Ubuntu ?
Any suggestions ?

A: for ubuntu machines, you just need to setup an apt repository and add it to the software sources on all machines. then all the ubuntu users can install your software and get updated when you update your software in the apt repository.

see How to set up an APT repository? for more details.

alternatively, you can just use the launchpad PPA service.

see https://help.launchpad.net/Packaging/PPA for more details on how to register a lauchpad account and publish your software through a PPA.


text:
Q: OpenCL Rendering in Blender 3D Hello to everybody!!!,
I have just made a PC with "AMD Radeon RX 480" Graphic Card and "AMD FX-8370E" Processor.
Operating System is Ubuntu 16.04 and I want to use Open Source drivers.
I know that recently with AMDGPU drivers this is possible.
I want to use Cycles rendering with GPU then with OpenCL in Blender 3D.
I have installed MESA 13 from Padoka repository and LLVM 4.0 + CLang 4.0.
When I execute the command:
$ clinfo
    Number of platforms                               1
      Platform Name                                   Clover
      Platform Vendor                                 Mesa
      Platform Version                                OpenCL 1.1 Mesa 13.1.0-devel - padoka PPA
      Platform Profile                                FULL_PROFILE
      Platform Extensions                             cl_khr_icd
      Platform Extensions function suffix             MESA

      Platform Name                                   Clover
    Number of devices                                 1
      Device Name                                     AMD POLARIS10 (DRM 3.2.0 / 4.7.0-040700-generic, LLVM 4.0.0)
      Device Vendor                                   AMD
      Device Vendor ID                                0x1002
      Device Version                                  OpenCL 1.1 Mesa 13.1.0-devel - padoka PPA
      Driver Version                                  13.1.0-devel - padoka PPA
      Device OpenCL C Version                         OpenCL C 1.1
      Device Type                                     GPU
      Device Profile                                  FULL_PROFILE
      Max compute units                               36
      Max clock frequency                             0MHz
      Max work item dimensions                        3
      Max work item sizes                             256x256x256
      Max work group size                             256
    incorrect number of operands in llvm.ident metadata
    !1 = !{!"clang version 4.0.0-svn289636-0~x~padoka0 (trunk)", !"clang version 4.0.0-svn286863-0~x~padoka0 (trunk)"}
    LLVM ERROR: Broken module found, compilation aborted!

I have previous results
GPU is seen by Blender 3D, but there is an error result in rendering try.
This is the error:
Device init success
Compiling OpenCL program base
OpenCL build failed with error CL_BUILD_PROGRAM_FAILURE, errors in console.
Error: Failed loading render kernel, see console for errors

Does Someone know how to resolve this problem?
Thanks!!!


text:
Q: Telegram's mp3 cache in the web version, chrome Where does telegram's web version on Chrome cache audio files to?
I tried looking into the chrome's cache chrome://view-http-cache, but couldn't find any mp3 files.


text:
Q: Displaying my JSON in HTML These are my Json arrays:
{"0":"1","id":"1","1":"2015-01-11 12:30:45","DateTimeCreated":"2015-01-11 12:30:45","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"benjiwjh","username":"benjiwjh"}

{"0":"4","id":"4","1":"2015-02-11 09:09:09","DateTimeCreated":"2015-02-11 09:09:09","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"LSH","username":"LSH"}

{"0":"7","id":"7","1":"2015-12-03 18:30:00","DateTimeCreated":"2015-12-03 18:30:00","2":"Unresolved","status_desc":"Unresolved","3":"SWJH","username":"SWJH"}

{"0":"12","id":"12","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"benjiwjh","username":"benjiwjh"}

{"0":"14","id":"14","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"CYJM","username":"CYJM"}

How am I supposed to use these to display my code in an HTML file?
I have a function to show the data but it does not work:
function showData(response) {

        var data = JSON.parse(response);

        var id = data.id;
        var DateTimeCreated = data.DateTimeCreated;
        var status_desc = data.status_desc;
        var username = data.username;

        myText.textContent= id + DateTimeCreated + status_desc + username;
}

A: I think you should have a div tag in your html template.
For example, in your HTML template, there should be a scope of codes:

And in your JS script,
var textContent = id + DateTimeCreated + status_desc + username
sometext = document.getElementById("sometext");
sometext.innerHTML(textContent);

For more info, please visit http://www.w3schools.com/js/js_output.asp
Hope it would be helpful

A: Based on the question, I'm not entirely sure when you are using the showData function. However, here's a jsfiddle that shows that it works: https://jsfiddle.net/qyy2nvtz/1/

var myText = document.getElementById('hello');

You need to get an element before you can display something in it. So, I've initialized 'myText' with a paragraph element with id 'hello'.
Additionally, make sure that the response that is being passed in to showData is a string before you parse it. If it's already an object, then it won't be parsed.

A: Here you have an example, you need a div element to refer like "js":
<!DOCTYPE html>

<title>Example</title>

Further reading: http://www.w3schools.com/dom/prop_element_textcontent.asp


text:
Q: What would be a good design to avoid methods with large number of parameters? I am having a bit of a design issue.  What I am working on is a drag and drop in a C# desktop app.  I am using the .NET treeview control and a third party grid (not important).  I am using this drag and drop operation of a file system in more than one place so I've created a static class to handle this.  Now this is not just an ordinary file system.  The treeview is a representation of the directories and the grid has the files.  The complicated part is that there is a logical file system as well so all of this is stored in a database as well.  I am only explaining all of this because I wanted to explain why I have a problem.  Because I am working with a number of objects at this point, all of my static methods have a large number of parameters.  All of my static methods are pretty much all using the same parameters as wel  Would there be something I can do to avoid this?

A: Reduce your parameters by encapsulating those fields in common objects, e.g.
Instead of having:
void DoSomething(string first, string middle, string last);

You could have:
void DoSomething(Name name);

Where Name could be represented by,
public class Name
{
   string First {get; set;}
   string Middle {get; set;}
   string Last {get; set;}
}

A: Once we get to a certain number of method parameters (3-5), we create a class to hold the parameter arguments and then just pass an instance of this class as the argument.
This is especially useful if you have multiple methods with essentially the same arguments.
Don't get too carried away with this, though: if you have a parameter that is only used in one method, I wouldn't include this in the arguments class, just pass it as an extra parameter to the exception method.
Also, as a side benefit, this makes passing parameters to threads/background workers much easier because you already have the parameters in a class object.

A: Here you are identifying a known "bad smell" labelled long parameter list. It is described very well on this site.
I find the most straightforward solution is introduce parameter object.
The other refactoring steps mentioned are:

*

*replace parameter with method

*preserve whole object
The potential problems with these two steps are that it introduces more coupling. It would require your static utility methods to know about these methods or existing objects, and this might be entirely inappropriate depending upon your design.


text:
Q: Mobile Accessibility : Focus moves to address bar on radio button, checkbox and button click on IOS 12.1.4 + voice over After updating IOS version to 12.1.4, focus moves to address bar on radio button click.It's working fine on OS V-12.0.1.
Steps:
go to https://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio
Enable the voice over.select male radio button then move focus to female radio button and select female radio button.Focus moves to address bar after selecting female radio button.
Focus moves to address bar when second radio button gets selected.
same behavior can be observed on https://www.accessibilityoz.com/forms/mobile-app-accessibility-audit-request/.
same behavior observed with checkbox and button click event.
I tried to fix it by keeping focus on radio button on click event using javascript but after 1 second focus moves back to address bar.
This is working fine on windows + NVDA ,mac + VO, android + talkback.

A: I am having this issue of VO jumping to either the address bar or to the "Reader" button on most websites in Safari. I am running iOS 12.1.4 on a new iPhone XR. I took my iPhone to the Apple Store and they couldn't figure it out wither, so they replaced my iPhone with a new one, but the issue persists! This doesn't happen in Google Chrome on my iPhone, so my temporary workaround is to use the GMail app instead of Apple Mail. This way, when I click on a link within an email message, it opens in Google Chrome instead of Safari. I am reporting this bug to Apple Accessibility.


text:
Q: Trouble Projecting a linq Query I have the following entity model :

And from it I need data in a format like :
Name, Picked, Packed, Complaints
ie Name=Muhammad Picked=6 Packed=9 Complaints=1

Within a given time period (using ProcessedOn).
I have the following complex looking query (for me).
        using(var db = new DbContainer())
        {
            var workers =
                db.Workers.Select(
                    x => new
                            {
                                x.Name,
                                Picked = x.PickedOrders.Where(a => a.ProcessedOn >= dtStart.Value && a.ProcessedOn <= dtEnd.Value).Sum(y => y.Units),
                                Packed = x.PackedOrders.Where(a => a.ProcessedOn >= dtStart.Value && a.ProcessedOn <= dtEnd.Value).Sum(y => y.Units),
                                Complaints = x.PickedOrders.Where(a => a.ProcessedOn >= dtStart.Value && a.ProcessedOn <= dtEnd.Value).Count(y => y.Complaint != null)
                                    + x.PackedOrders.Where(a => a.ProcessedOn >= dtStart.Value && a.ProcessedOn <= dtEnd.Value).Count(y => y.Complaint != null)
                            }).ToList();
        }

I get this error :
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
Any ideas?


text:
Q: String of text hidden? I have a string of text "Highscore: " and I want this to show up at the bottom of my JFrame. When I try to increase the y the text shows up to about 100 and then if I want to increase it anymore it disappears? I want it past 100 though...
Here is my code:
package Main;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Game {

public static void main(String[] args) {

     final JFrame frame = new JFrame("Tennis Game");
     frame.setSize(300,400);
     frame.setResizable(false);
     frame.setVisible(true);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     //Graphics add
     Menu graphics = new Menu();

     frame.add(graphics);
     graphics.setBounds(0, 0, 300, 100);

     frame.setLayout(null);

     //Buttons
     //Play button
     final JButton b = new JButton("Play");

     b.setFocusPainted(false);
     b.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
     b.setBounds(110,100,80,40);
     b.setForeground(Color.BLACK);

     b.addMouseListener(new java.awt.event.MouseAdapter(){

        public void mouseEntered(MouseEvent evt) {
             b.setForeground(Color.RED);
             b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
         }

        public void mouseExited(MouseEvent evt) {
             b.setForeground(Color.BLACK);
         }
        public void mouseClicked(MouseEvent evt){

        }

     });

     //Exit button
     final JButton b2 = new JButton("Exit");

     b2.setFocusPainted(false);
     b2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
     b2.setBounds(110, 180, 80, 40);
     b2.setForeground(Color.BLACK);

     b2.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent evt) {
            System.exit(0);

        }

     });

     b2.addMouseListener(new java.awt.event.MouseAdapter(){

        public void mouseEntered(MouseEvent evt) {
             b2.setForeground(Color.RED);
             b2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
         }

        public void mouseExited(MouseEvent evt) {
             b2.setForeground(Color.BLACK);
         }

     });

     //Help Button
     final JButton b3 = new JButton("Help");

     b3.setFocusPainted(false);
     b3.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
     b3.setBounds(110, 140, 80, 40);
     b3.setForeground(Color.BLACK);

     b3.addMouseListener(new java.awt.event.MouseAdapter(){

        public void mouseEntered(MouseEvent evt) {
             b3.setForeground(Color.RED);
             b3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
         }

        public void mouseExited(MouseEvent evt) {
             b3.setForeground(Color.BLACK);
         }
        public void mouseClicked(MouseEvent evt){

        }

     });

     frame.add(b);
     frame.add(b2);
     frame.add(b3);

 }
 }

Also:
package Main;

import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;

public class Menu extends JPanel {

int highscore = 0;

public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.setFont(new Font("Arial", Font.BOLD, 30));
    g.setColor(Color.BLACK);
    g.drawString("TENNIS GAME", 40, 60);

    g.setFont(new Font("Arial", Font.BOLD, 18));
    g.setColor(Color.BLACK);
    g.drawString("Made by Jared Butterfield", 36, 82);

    //TEXT HERE
    //TEXT HERE
    //TEXT HERE
    g.setFont(new Font("Arial", Font.BOLD, 18));
    g.setColor(Color.BLACK);
    g.drawString("Highscore: "+ highscore, 0, 150);

}

}

I tried to add comments where the highscore text was for help.

A:
I have a string of text "Highscore: " and I want this to show up at the bottom of my JFrame.

Create a JLabel and then add the label to the frame using:
frame.add(label, BorderLayout.SOUTH);

This assumes you are using the default BorderLayout for the frame, which is always a good idea.
All your other custom painting code should be replaced by JLabels as well. Again you add the labels to a panel using an appropriate layout managers. Read the Swing tutorial on Layout Managers for more information and demo code to get you started.

A: Let's start with the fact that you are using null layouts, then move onto the fact that you purposefully set the bounds of the Menu component to graphics.setBounds(0, 0, 300, 100); (100px high), but then paint the text at the y position of 150, g.drawString("Highscore: " + highscore, 0, 150); and then wonder why it doesn't display?

*

*Don't use null layouts, you are just asking for trouble.  Make use of appropriate layout managers

*Use JLabel to render text, it's what it does and it does it well

See Creating a GUI With JFC/Swing, How to Use Labels and Laying Out Components Within a Container for more details


text:
Q: Batch that convert TIMECODE to frame number in a batch there is a envoroment variable called %timecode% that, if timecode exist and is defined, output a string of this type:
HH:MM:SS:FF

for example 01:32:21:05
In PAL mode, 25fps, I would like convert this timecode in his correspondant frame number, for rxample in the case of 01:32:21:05 is 138530
so the convert processing should output 138530
Another examples: 00:00:00:00 ----------------> 0
00:00:00:01 ----------------> 1
........
00:00:00:24 ----------------> 24
00:00:01:00 ----------------> 25
00:00:01:01 ----------------> 26

and so on
How can I do?

A: @ECHO Off
SETLOCAL
SET "timecode=01:32:21:05"
IF DEFINED timecode (
 SET /a result=((1%timecode:~0,2%-100^) * 90000^) + ((1%timecode:~3,2%-100^) * 1500^) + ((1%timecode:~6,2%-100^) * 25^) + (1%timecode:~-2%-100^)
) ELSE (SET "result=NOT defined")
ECHO result with timecode="%timecode%" is %result%

SET "timecode="
IF DEFINED timecode (
 SET /a result=((1%timecode:~0,2%-100^) * 90000^) + ((1%timecode:~3,2%-100^) * 1500^) + ((1%timecode:~6,2%-100^) * 25^) + (1%timecode:~-2%-100^)
) ELSE (SET "result=NOT defined")
ECHO result with timecode="%timecode%" is %result%

GOTO :EOF

This should point you to a solution.
Note that the carets (^) are only required before the ) because the set command is within a block. If you were to choose to goto a label if timecode was undefined, then the carets would not be required.
I've cosen to calculate the sum using a straight-forward method; prepending a 1 to the two digits, then subtracting 100 (which takes care of the 08/09 problem - a leading 0 is defined as octal and cmd will object to non-octal characters) The routine could be made simpler by the use of magic numbers, but that would require more explanation.

A: @echo off
    setlocal enableextensions disabledelayedexpansion
    set "frameRate=25"

    set "timecode=01:32:21:05"

    for /f "tokens=1-4 delims=:" %%a in (
        "100%timecode::0=: %"
    ) do set /a "frame=((%%a %% 100)*3600 + (%%b0)*60/10 + (%%c0)/10) * %frameRate% + (%%d0)/10"

    echo %frame%

This code splits the timecode variable contents using the colons as delimiters. To account for zero prefixed fields (considered in octal form and problematic in the case of 08 or 09), missing or bad formatted data, some "tricks" are used.
To correct the hour part, the input data is prefixed with 100 and this field will be handled modulo 100.
To handle the problematic zero prefixed fields, a colon followed by a zero in the input data is replaced with the same colon followed by a space.
To handle problems with missing fields, when doing the calcs all extracted data is suffixed with a zero (mutiplying it by 10) and the the result of the operation in this field is divided by 10


text:
Q: Como remover %3F entre outros do resultado? Esse é minha primeira tentativa com programação, eu vi em um site um link que ao colocar nos favoritos serviria pra baixar um vídeo do youtube so que em formato mp3, porem n funcionava, ao fazer tentativas entendi o porque e tentei consertar, consegui fazer parcialmente pois no resultado aparece os simbolos em forma d codigo e eu n consigo fazer nada pra remover ele

javascript:(function() {if (location.href.indexOf('youtube.com') > -1) {window.open('http://youtubeplaylist-mp3.com/download/index/' + encodeURIComponent(location.href) .replace("https", "") .replace("youtube", "") .replace("www.", "") .replace(".com", "") .replace("watch", "") .replace(/[%3A]/, '') .replace("", "") .replace("", ""));} else {alert('So funciona no youtube carambola');}})();

obs: eu sei que tem alguns comandos sem utilização ai mas essa é uma versão bem inicial e tem umas coisas so de testes que eu não acho que estejam influenciando
obss: fazendo isso pelo chrome (não sei se tem diferença mas achei que seria bom comentar)
obsss: eu inicialmente fiz um post no stackoverflow americano, link: https://stackoverflow.com/questions/41526572/how-to-remove-3f-and-others-from-the-result-of-my-first-code (caso alguem queira ver)

A: Você pode utilizar a função: decodeURIComponen. Segue um exemplo simples:

var texto = "%3F%3F%3F";
alert(decodeURIComponent(texto));


text:
Q: Why am I getting "You are not administrator of any billing account" error on GCP when trying to create a new VM Instance? Background
I'm new to GCP. I once had setup a Google Maps Billing account to access the Google Maps API for one of my projects. Because I signed up through Google Maps Billing I wasn't initially given the signup credit of 300$. I contacted the billing support and they credited the 300$ to my Google Maps Billing Account.
Issue
When I tried to create a VM Instance in my project which is connected to the Maps billing account, it shows the following.
[Screenshot showing my account doesn't have administrative right over any billing account][1]
Screenshot[1]:https://i.stack.imgur.com/6zWhX.jpg
The given project is connected to my Maps billing and I was informed that Maps Billing should work for GCP Services.
What am I missing? How can I resolve this?


text:
Q: Set only certain widgets to resize with the window I need some of my widgets to resize with the window as the user makes it larger or smaller, and I've already looked at this question, but unfortunately all the answers there solve the problem by assigning a layout to the main window. Doing so is not an option for me, as I've found it impossible to lay out the widgets the way I want with any of the layout modes offered by Qt Designer; in other words, the layout being set as "broken" is by design, in my case.
I have only three widgets I wish to make responsive: the two boxes you can see in the screenshot below and the big button on the top side. Everything else should stay where it is. How can I achieve this?

To be exact, as the window grows, I would like the two boxes to grow vertically and horizontally in equal measure, while the button should only grow horizontally. I don't need this to be done in the ui file necessarily: code solutions are ok as well.

A: The basic Qt layouts (grid and boxed) are very simple as much as they are powerful, and there are very rare and specific cases for which manual override of the geometry is actually required; even in those cases, one should be very careful with it, as deep knowledge and understanding of Qt size management is required in order to avoid unexpected behavior that could result in an unusable UI or even recursion issues.
99% of the times it's enough to be aware of how layout managers work, and take some time in realizing how the whole layout should be structured, possibly by using nested layouts with proper adjustments of stretches and size policies. Hint: drawing a sketch on paper helps a lot.
In your case, a possible solution could use the following structure:

*

*a main vertical layout for the central widget

*

*a grid layout for the top elements, with:

*

*the label and the line edit on the first row, one cell each

*a spacer

*the button that occupies two rows of the grid

*a vertical layout for each of the two groups, with:

*

*the label

*the scroll area

*a horizontal layout for the bottom elements, with:

*

*the button

*another spacer

*the checkbox

Then, the line edit has a Preferred horizontal size policy, the "Scan now" button has a minimum height and an Expanding horizontal policy instead; the two bottom buttons have the same minimum size, the checkboxes have an Expanding horizontal policy; the two scroll areas are left as they are, as they expand themselves by default (and since they're the only vertically expanding widgets, they will expand equally). All spacers have a fixed width (by default they are "expanding" spacers).
Note that, while I could have used a grid layout for the two bottom "groups", using a nested vertical/horizontal layout is often more flexible; in any case, another possible variation could have been to use a separate grid layout for both those two groups (since they have common element, sizes and behaviors), with both the "header" labels and scroll areas spanning 3 columns.
Here you can see the structure as it will appear in Designer:

And here is the UI file.
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>454</width>
    <height>405</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout_3">
    <item>
     <layout class="QGridLayout" name="gridLayout">
      <item row="0" column="0">
       <widget class="QLabel" name="label">
        <property name="text">
         <string>Scan:</string>
        </property>
       </widget>
      </item>
      <item row="0" column="1">
       <widget class="QLineEdit" name="lineEdit">
        <property name="sizePolicy">
         <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
       </widget>
      </item>
      <item row="0" column="2">
       <spacer name="gridSpacer">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeType">
         <enum>QSizePolicy::Fixed</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>40</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
      <item row="0" column="3" rowspan="2">
       <widget class="QPushButton" name="pushButton">
        <property name="sizePolicy">
         <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="minimumSize">
         <size>
          <width>0</width>
          <height>50</height>
         </size>
        </property>
        <property name="text">
         <string>Scan now</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QVBoxLayout" name="detectVertLayout">
      <item>
       <widget class="QLabel" name="detectLabel">
        <property name="text">
         <string>Detected:</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTextEdit" name="detectTextEdit"/>
      </item>
      <item>
       <layout class="QHBoxLayout" name="detectBtnLayout">
        <item>
         <widget class="QPushButton" name="pasteButton">
          <property name="minimumSize">
           <size>
            <width>100</width>
            <height>0</height>
           </size>
          </property>
          <property name="icon">
           <iconset theme="edit-paste"/>
          </property>
         </widget>
        </item>
        <item>
         <spacer name="horizontalSpacer">
          <property name="orientation">
           <enum>Qt::Horizontal</enum>
          </property>
          <property name="sizeType">
           <enum>QSizePolicy::Fixed</enum>
          </property>
          <property name="sizeHint" stdset="0">
           <size>
            <width>40</width>
            <height>20</height>
           </size>
          </property>
         </spacer>
        </item>
        <item>
         <widget class="QCheckBox" name="copyCheck">
          <property name="sizePolicy">
           <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
            <horstretch>0</horstretch>
            <verstretch>0</verstretch>
           </sizepolicy>
          </property>
          <property name="text">
           <string>Copy automatically</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QVBoxLayout" name="translVertLayout">
      <item>
       <widget class="QLabel" name="translateLabel">
        <property name="text">
         <string>Translations:</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTextEdit" name="translateTextEdit"/>
      </item>
      <item>
       <layout class="QHBoxLayout" name="translBtnLayout">
        <item>
         <widget class="QPushButton" name="translButton">
          <property name="minimumSize">
           <size>
            <width>100</width>
            <height>0</height>
           </size>
          </property>
          <property name="text">
           <string>Translate</string>
          </property>
         </widget>
        </item>
        <item>
         <spacer name="horizontalSpacer_2">
          <property name="orientation">
           <enum>Qt::Horizontal</enum>
          </property>
          <property name="sizeType">
           <enum>QSizePolicy::Fixed</enum>
          </property>
          <property name="sizeHint" stdset="0">
           <size>
            <width>40</width>
            <height>20</height>
           </size>
          </property>
         </spacer>
        </item>
        <item>
         <widget class="QCheckBox" name="autoTranslCheck">
          <property name="sizePolicy">
           <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
            <horstretch>0</horstretch>
            <verstretch>0</verstretch>
           </sizepolicy>
          </property>
          <property name="text">
           <string>Translate automatically</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>454</width>
     <height>24</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

I suggest you to load the above file in Designer and patiently study it; most importantly, take a closer look at overridden properties of each element: row/column spanning, minimum/maximum sizes, size policies and stretches.
Then do some reading about:

*

*layout management;

*using layouts in designer;

*QSizePolicy;

Finally, do lots and lots of tests and experiments, both in Designer and by code.


text:
Q: Does np.array's astype prevent future edits in DataFrames? I can change the first entry of the DataFrame initially:
In [6]: df = pd.DataFrame(np.random.rand(5,2))
In [7]: df
Out[7]:
          0         1
0  0.514592  0.459589
1  0.329704  0.409099
2  0.061246  0.966191
3  0.336747  0.908513
4  0.169220  0.468437

In [8]: df.ix[0][0] = 1
In [9]: df
Out[9]:
          0         1
0  1.000000  0.459589
1  0.329704  0.409099
2  0.061246  0.966191
3  0.336747  0.908513
4  0.169220  0.468437

But after I do this:
In [10]: df[0] = np.floor(df.index / 10).astype(int) * 10
In [11]: df
Out[11]:
   0         1
0  0  0.459589
1  0  0.409099
2  0  0.966191
3  0  0.908513
4  0  0.468437

I can't find a way to change it.
In [12]: df.ix[0][0] = 1
In [13]: df
Out[13]:
   0         1
0  0  0.459589
1  0  0.409099
2  0  0.966191
3  0  0.908513
4  0  0.468437

And I can't even change elements from other columns
In [16]: df.ix[0][1] = 1

In [17]: df
Out[17]:
   0         1
0  0  0.459589
1  0  0.409099
2  0  0.966191
3  0  0.908513
4  0  0.468437

What's up with this?

A: you are editing a copy, try
In [3]: df = pd.DataFrame(np.random.rand(5,2))

In [4]: df[0] = np.floor(df.index / 10).astype(int) * 10

In [5]: df
Out[5]:
   0         1
0  0  0.201611
1  0  0.390364
2  0  0.727422
3  0  0.941035
4  0  0.036764

In [6]: df.ix[0,1] = 1

In [7]: df
Out[7]:
   0         1
0  0  1.000000
1  0  0.390364
2  0  0.727422
3  0  0.941035
4  0  0.036764


text:
Q: how to use variable inside .wrap() This might sound silly but i'm having trouble printing a variable in this code -
var clsuffix = "something";
$("#box").wrap('
');

I want to print the clsuffix variable inside the class=" here "
so it could be like

But when i use the variable inside class="", it comes up as it is (not being treated as variable)

A: Just concatenate it in.  Ultimately, your goal is to build a string consisting of the literal "boxy" and the contents of the variable clsuffix.  That is done with "boxy" + clsuffix in JavaScript:
$("#box").wrap('
');

If you were just trying to insert the variable into the string (such as you might do in a PHP double-quoted string), it won't be interpreted by JavaScript:
// Doesn't work in JavaScript:
$("#box").wrap('
');

A: I'd suggest:
$('#box').wrap('
', {'class' : 'boxy' + cslsuffix});

Which effectively creates the div element, and uses the map to assign values to the defined attributes.