text:
Q: Docker containers exiting without identifiable cause (Django web application) I've taken over the maintenance of a live web project that utilizes docker containers. Immediately, I've noticed that the web app goes down after a couple of hours, and docker ps -a shows me:
CONTAINER ID        IMAGE            COMMAND                  CREATED         STATUS                    PORTS                                   NAMES
9b02f1352f15        nginx:latest     "nginx -g 'daemon off"   9 weeks ago     Exited (1) 14 hours ago   80/tcp, 443/tcp, 0.0.0.0:80->8000/tcp   ng01
8079b3d3b398        webapp_web       "gunicorn --error-log"   9 weeks ago     Exited (1) 14 hours ago   8000/tcp                                webapp_web_1
564fe0b72fa6        d0f5f9c3d3a6     "/bin/sh -c 'apt-get "   12 weeks ago    Exited (0) 12 weeks ago                                           modest_perlman
6cddbfcfa8f6        d0f5f9c3d3a6     "/bin/sh -c 'apt-get "   12 weeks ago    Exited (0) 12 weeks ago                                           backstabbing_goldwasser
7460be4f4451        postgres         "/docker-entrypoint.s"   4 months ago    Exited (1) 14 hours ago   5432/tcp                                webapp_db_1

Notice the 3 containers that exited 14 hours ago - those relate to the web app. How do I diagnose/fix this problem? Being a beginner, I'm struggling here. Thanks in advance! Following are some diagnostics I tried to run.

I used docker logs on the errant containers to see what could be going wrong.
docker logs 9b02f1352f15 (nginx) is empty.
docker logs 8079b3d3b398 (application server - gunicorn) shows many incidences of:
Exception in thread Thread-725265:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/local/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/site-packages/unirest/__init__.py", line 97, in __request
    response = urllib2.urlopen(req, timeout=_timeout)
  File "/usr/local/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python2.7/urllib2.py", line 429, in open
    response = self._open(req, data)
  File "/usr/local/lib/python2.7/urllib2.py", line 447, in _open
    '_open', req)
  File "/usr/local/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python2.7/site-packages/poster/streaminghttp.py", line 142, in http_open
    return self.do_open(StreamingHTTPConnection, req)
  File "/usr/local/lib/python2.7/urllib2.py", line 1198, in do_open
    raise URLError(err)
URLError: <urlopen error [Errno 101] Network is unreachable>

docker logs 7460be4f4451 (postgresql backend) shows many incidences of:
LOG:  database system was interrupted; last known up at 2017-01-22 12:42:46 UTC
LOG:  database system was not properly shut down; automatic recovery in progress
LOG:  invalid record length at 0/17AAD28
LOG:  redo is not required
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started

In case it matters, doing tail -f docker.log at /var/run/upstart/docker.log gives the output:
INFO[0000] Firewalld running: false
time="2017-01-23T14:38:47.142345718Z" level=error msg="devmapper: Error unmounting device 3da5c7e87cc8969249d7ed8b15c9cea9296feaefeba62fde534b4c183e4edbd4: Device is Busy"
time="2017-01-23T14:38:47.142542018Z" level=error msg="Error unmounting container 8079b3d3b3988a793537c4116bd12c70823415cb84068021d25658a316d8f568: Device is Busy"
INFO[0000] Firewalld running: false
INFO[0000] Firewalld running: false
time="2017-01-23T14:40:20.694963580Z" level=error msg="devmapper: Error unmounting device 6fd51632808dede3fea81b4f19fb84f1a13d93c38917e2845d0776de6a2ef941: Device is Busy"
time="2017-01-23T14:40:20.695010680Z" level=error msg="Error unmounting container 9b02f1352f15447acb7669bff918db0eeed58dc832fff565f4b2a4236474db1f: Device is Busy"
INFO[0000] Firewalld running: false
time="2017-01-23T14:41:27.307003457Z" level=error msg="devmapper: Error unmounting device 7c5a35dc9fc1929e57de43f5efc8e05a9442782c7496713d313c95fe62910f7b: Device is Busy"
time="2017-01-23T14:41:27.307059457Z" level=error msg="Error unmounting container 7460be4f445102274dd4aba4f113db23c17f58b9f771fc5c474d174766ae593c: Device is Busy"

I also tried docker inspect on all three. Following are the results relating to state - there seems to be nothing wrong here.
docker inspect 9b02f1352f15(nginx):
  "State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 1,
        "Error": "",
        "StartedAt": "2017-01-22T12:42:47.142236155Z",
        "FinishedAt": "2017-01-22T23:38:46.7038628Z"
    },

docker inspect 8079b3d3b398 (application server - gunicorn):
   "State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 1,
        "Error": "",
        "StartedAt": "2017-01-22T12:42:42.602662338Z",
        "FinishedAt": "2017-01-22T23:38:46.5945186Z"
    },

docker inspect 7460be4f4451 (postgresql backend):
    "State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 1,
        "Error": "",
        "StartedAt": "2017-01-22T12:42:34.413283342Z",
        "FinishedAt": "2017-01-22T23:38:46.5102334Z"
    },

docker-compose.yml is simply:
version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: gunicorn --error-logfile err.log myapp.wsgi:application -b 0.0.0.0:8000
    volumes:
      - .:/code
    expose:
      - "8000"
    depends_on:
      - db
  nginx:
    image: nginx:latest
    container_name: ng01
    ports:
      - "80:8000"
    volumes:
      - .:/src
      - ./config/nginx:/etc/nginx/conf.d
    depends_on:
      - web


text:
Q: When GPO no longer applies, is deployed software automatically uninstalled? Are packages installed by GPO automatically removed when the GPO no longer applies?

A: If you check the checkbox titled, "Uninstall this application when it falls out of the scope of management," on the Software Install policy it will uninstall.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I Remove CodeClimate similar code from strong params? I'm analyzing my code in CodeClimate.com and I have a similar code problem always in the same lines:
params.permit(some parameters here)

CodeClimate is detecting this code as similar based only in the mass of the code, not in the content, so my quality is not improving due to this.
Is there a way to tell CodeClimate that this code is not repeated or even similar, as long as it's a parameters hash?

A: There is no way to avoid this kind of codeclimate problem as long as it is not discriminating the name of the method, just the mass of it.
Edit 2020:
Apparently this issue is happening in every modern linter. They just check that there's a huge set of lines repeated in different files, and mark them as a possible duplicates. And it happens on every other language. Specially the ones that are interpreted.

A: Why not to refactor such issues? Say, you have code:
class PostsController < ApplicationController
  # ...

  def resource_params
    params.require(:post).permit(:title, :body)
  end
end

class CommentsController < ApplicationController
  # ...

  def resource_params
    params.require(:comment).permit(:name, :email, :body)
  end
end

You can move repeating code into superclass, leaving in subclasses only differences:
class ApplicationController < ActionControllerBase
  # ...

  def resource_params
    params.require(resource_name).permit(*permitted_resource_params)
  end
end

class PostsController < ApplicationController
  # ...

  def resource_name
    :post
  end

  def permitted_resource_params
    [:title, :body]
  end
end

class CommentsController < ApplicationController
  # ...

  def resource_name
    :comment
  end

  def permitted_resource_params
    [:name, :email, :body]
  end
end

And, of course, if in some controller you have different rules of params permission — you could redefine resource_params method in it.

A: As MikiDiet suggested, probably the best is to do refactor. But this suggestion won't solve issue completely.  From my experience then CodeClimate will report code smells on:
def resource_name
 :post
end

def permitted_resource_params
  [:title, :body]
end

as code duplication across controllers.


text:
Q: Eagle - Export SMD components to inches not mm I am trying to export the BOM in a pcb, for use in a pick and place machine.
The way I do this is by clicking on File -> Export -> Mount SMD.
This is what the generated mnb file looks like.
C1 12.45 43.18 270 100n C0805
C2 22.44 61.98 180 100n C0805
C3  0.00 31.24  90 100n C0805
C4  2.03 31.24  90 10u C0805

As you can see, the X and Y coordinates are in mm, while I want the output to be in inches.
Even though the grid is selected to be in inches, the output still remains in mm and I see no option available to change it to inches.
Is there a way to change it to inches?
I am using Eagle 7.7.0.

A: I found the answer, however it converts to mil.
Find the file mountsmd_mil.ulp in your system.
Open it with a text editor. Change all references to u2mm to u2mil. Save the file.
Now when you do File -> Export -> MountSMD, the dimensions will be in mil.
Original reference link located here:
https://community.element14.com/products/eagle/f/eagle-user-support-english/40903/generating-pick-and-place-file-with-mountsmd-ulp


text:
Q: Hibernate optimistic locking different behavior between Postgres and MariaDb I just discovered that my application behaves differently when I use optimistic locking with a Postgresql or a MariaDB database and I am wondering if somebody can explain what happens and how could I make the application work in the same way with MariaDB? I use Postgresl 10.5 and MariaDB 10.3.10 with InnoDB engine and default settings. I use Spring framework version 5.1.0 and Hibernate 5.3.6.
So my code looks like this:
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Bla {

    @Id
    @GeneratedValue
    private long id;

    @Version
    private long version;

    private int counter;
}

I also have a repository for this entity and the following service method:
@Transactional
public int increment(long id) {
    Bla bla = blaRepo.getOne(id);
    bla.setCounter(bla.getCounter() + 1);
    return bla.getCounter();
}

If I call this method on multiple threads I would expect update would succeed only for a single one of them if they touch the entity with the same version. As an example: if I start 50 thread with Postgres db in one run I get 3 calls that succeed and return the values 1, 2, 3 and the other 47 fail with an ObjectOptimisticLockingFailureException which is the expected behavior - this is how I would like the app to behave.
However, if I switch to MariaDB then this doesn't happen. All 50 of these threads are completed successfully and I get the same response value in multiple threads as if there would be no optimistic lock. For example now the first 5 threads returned 1, then 20 of them returned 2, and the rest 3 or 4.
Why this is happening? It doesn't make any sense - with both databases the query generated is
update bla set counter=?, version=? where id=? and version=?

But in Postgresql will fail correctly and with MariaDB will succeed unexpectedly.

A: The only way that could happen is of MariaDB had a bug because once a Tx modifies a record, it will lock it until it commits or rollbacks. Other Tx would block the UPDATE due to lock but the condition must be reevaluated after the lock is released.
Try to switch to READ_COMMITTED and see if it fixes the issue. It could be a REPEATABLE_READ anomaly.

A: I found the solution to this problem.
It seems that I had this property set in application.properties:
spring.jpa.properties.hibernate.jdbc.batch_size = 50

When I do use Postgresql I get the following debug trace with two threads:
13223 [pool-2-thread-2] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
13223 [pool-2-thread-1] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
13226 [pool-1-thread-1] DEBUG org.hibernate.engine.jdbc.batch.internal.BatchingBatch - Executing batch size: 1
13226 [pool-1-thread-2] DEBUG org.hibernate.engine.jdbc.batch.internal.BatchingBatch - Executing batch size: 1
13230 [pool-1-thread-1] ERROR org.hibernate.engine.jdbc.batch.internal.BatchingBatch - HHH000315: Exception executing batch [org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1], SQL: update bla set counter=?, version=? where id=? and version=?

and then with MariaDB with the same batch size 50:
21978 [pool-2-thread-2] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
21978 [pool-2-thread-1] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
21979 [pool-2-thread-2] DEBUG org.hibernate.engine.jdbc.batch.internal.BatchingBatch - Executing batch size: 1
21979 [pool-2-thread-1] DEBUG org.hibernate.engine.jdbc.batch.internal.BatchingBatch - Executing batch size: 1
21980 [pool-2-thread-2] DEBUG org.hibernate.jdbc.Expectations - Success of batch update unknown: 0
21980 [pool-2-thread-1] DEBUG org.hibernate.jdbc.Expectations - Success of batch update unknown: 0

and then with MariaDB with batch size 1:
12994 [pool-2-thread-2] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
12994 [pool-2-thread-1] DEBUG org.hibernate.SQL - update bla set counter=?, version=? where id=? and version=?
12997 [pool-2-thread-1] DEBUG org.hibernate.cache.internal.TimestampsCacheEnabledImpl - Invalidating space [bla], timestamp: 6307671153053696
12998 [pool-2-thread-2] DEBUG org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl - JDBC transaction marked for rollback-only (exception provided for stack trace)

And now indeed the application throw the expected ObjectOptimisticLockingFailureException
But unfortunately this means that using MariaDb with optimistic locking on entities and any batch size greater than 1 is not compatible.


text:
Q: Tomcat 7 (when a servlet project) is included is not staring within 45 seconds...and increasing the timeout does not solve Tomcat 7 is not starting when a web application(with a servlet) is attempted to run.The server works well when i only have a html page.But when i try to add a servlet and add it to tomcat.Then the server does not start and gives an error saying "Tomcat 7 didn't start in 45 seconds". I increased the timeout but nothing happened.Please help me solve this problem
The Console says :
"23 Jan, 2012 1:43:44 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in                  production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jdk1.7.0\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.6.0_23/jre/bin/server;C:/Program Files/Java/jdk1.6.0_23/jre/bin;C:/Program Files/Java/jdk1.6.0_23/jre/lib/amd64;C:\Program Files (x86)\Java\jdk1.7.0\jre\bin;F:\SOFTWARES\Eclipse Indigo\eclipse;
23 Jan, 2012 1:43:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property     'source' to 'org.eclipse.jst.jee.server:Basic' did not find a matching property.
23 Jan, 2012 1:43:44 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
23 Jan, 2012 1:43:44 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-9999"]
23 Jan, 2012 1:43:44 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 717 ms
23 Jan, 2012 1:43:44 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
23 Jan, 2012 1:43:44 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.23
23 Jan, 2012 1:43:45 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component     [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Basic]]
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
at java.util.concurrent.FutureTask.get(FutureTask.java:111)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1100)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:674)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component     [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Basic]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
    Caused by: java.lang.UnsupportedClassVersionError: Simple : Unsupported major.minor version 51.0 (unable to load class Simple)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2827)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1160)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1655)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1533)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:108)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:58)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:338)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:831)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:302)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5148)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
23 Jan, 2012 1:43:45 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to     start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
at java.util.concurrent.FutureTask.get(FutureTask.java:111)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1100)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:624)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:623)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:674)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1108)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
23 Jan, 2012 1:43:45 PM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8000]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.startup.Catalina.start(Catalina.java:624)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:623)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component         [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1108)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
23 Jan, 2012 1:43:45 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 313 ms "    '

A: If you just copied the error message of the cause of the exception into Google, you would have found the problem. "Unsupported major.minor version 51.0" means that you compiled the classes with JDK7, but try to deploy and run it with a previous version of the JDK or JRE. Start your tomcat with JDK7, or change the JDK you're using to compile your classes.
Side note: your class seems to be named Simple and to be in the default package. This ie a bad practice that will cause all sorts of problems. Always put your classes in a package.

A: Check the configuration in the file servers.xml in the Package Explorer under Servers in Eclipse.
When you open this file in Design-mode, you can see the different Contexts-configs.
For you start there should be an entry. Check this Context entry: the docBase, path and source should refer to your project.


text:
Q: Text File error Scanner I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work
public static void Option2Method() throws IOException
{

File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader =  new Scanner(inputFile);
Scanner writer =new Scanner(tempFile);
String currentLine;

while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}

A: Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.
Example:
public static void Option2Method() throws IOException {

    File inputFile = new File("wordlist.txt");
    FileWriter fstream = new FileWriter("TempWordlist.txt", true);
    BufferedWriter writer = new BufferedWriter(fstream);

    File tempFile = new File("TempWordlist.txt");
    String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
    Scanner reader = new Scanner(inputFile);

    while (reader.hasNextLine()) {
        String trimmedLine = reader.nextLine().trim();
        if (trimmedLine.equals(lineToRemove))
            continue;

        writer.write(trimmedLine + "\n");
    }

    reader.close();
    writer.close();
    inputFile.delete();
    tempFile.renameTo(inputFile);
}

Using PrintWriter:
    File inputFile = new File("wordlist.txt");
    PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));

    File tempFile = new File("TempWordlist.txt");
    String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
    Scanner reader = new Scanner(inputFile);

    while (reader.hasNextLine()) {
        String trimmedLine = reader.nextLine().trim();
        if (trimmedLine.equals(lineToRemove))
            continue;

        writer.print(trimmedLine + "\n");
    }

    reader.close();
    writer.close();
    inputFile.delete();
    tempFile.renameTo(inputFile);

A: Scanner doesn't have a print method. It is used to scan a file and read data from it.
If you want to write to a file, use this or that or just google "java write to file"


text:
Q: JSF c:set evaluation <c:set var="product" value="#{productDAO.findByCode('code')}"  />
#{product.name}
#{product.name}

I would like to retrieve an object from the DB and store into a variable once.
However, I find the call to the DB is made everytime I access product.
In the example above there are two calls to the DB.

A: You need to explicitly specify the scope.
<c:set var="product" value="#{productDAO.findByCode('code')}" scope="request" />

The proper approach, however, is to create and use a request scoped managed bean and put this logic in its @PostConstruct.


text:
Q: Distribution of $\sin(n)$ for $n=1...\infty$ Is the sequence $a_{n}=\sin(n)$ uniformly distributed on the interval $[-1,1]$?
For the first $10000$ $n$, it seems as if it is more dense at $-1$ and $1$ than in the middle.
Is there any way to prove this or its uniform distribution?
Also, can a result be generalized for $\sin^m(n)$ over its appropriate interval?

A: By Weyl's equidistribution theorem, the sequence $\{e^{in}\}_{n\geq 1}$ is uniformly distributed over the unit circle, by the irrationality of $\pi$. The distribution of $\sin(n)$ over $(-1,1)$ is so the same as the distribution of $\sin(X)$, where $X$ is a random variable uniformly distributed over $(0,2\pi)$. The PDF of such distribution is so given by $\frac{1}{\pi\sqrt{1-t^2}}$, supported on $(-1,1)$.
Here it is a histogram representing the distribution of $\sin(n)$ for $n\in[1,10^4]$:
$\hspace{2cm}$
Yves Daoust's answer deals with the case $\sin(X)^m$, too.

A: If the points $n\bmod 2\pi$ are uniformly distributed, you can expect a density which is proportional to the inverse of the slope of the curve, i.e.
$$a=\sin x, x=\arcsin a,$$
$$d(a)\propto\frac1{\sqrt{1-a^2}}.$$
For the case with the exponent,
$$a=\sin^mx,x=\arcsin\sqrt[m]a
,$$
$$d(a)\propto\frac{\sqrt[m]a}{ma\sqrt{1-\sqrt[m]{a^2}}}.$$


text:
Q: Configuring Unity to resolve a type that takes a decorated dependency that has a parameter that varies with the type into which it is injected This is a fairly straight forward decorator pattern scenario, with the complication that the decorated type has a constructor parameter that is dependent on the type into which it is being injected.
I have an interface like this:
interface IThing
{
    void Do();
}

And an implementation like this:
class RealThing : IThing
{
    public RealThing(string configuration)
    {
        ... implementation ...
    }

    public void Do()
    {
        ... implementation ...
    }
}

And a decorator like this:
class DecoratingThing : IThing
{
    IThing _innerThing;

    public DecoratingThing(IThing thing)
    {
        _innerThing = thing;
    }

    public void Do()
    {
        _innerThing.Do();
    }
}

Finally, I have some types that require an IThing, called Depender1, Depender2 etc..
class DependerX()
{
    public DependerX(IThing thing)
    {
        ... implementation ...
    }
}

I want to configure an IOC container to resolve instances of DependerX such that they are injected with RealThing decorated with a DecoratingThing. Important: Each DependerX type requires a different value of configuration to be passed to the constructor of its RealThing, say "ConfigX" in each case. e.g. The work done by the IoC container might be:
new Depender1(new DecoratingThing(new RealThing("Config1")));
new Depender2(new DecoratingThing(new RealThing("Config2")));

... and so on.
In Unity, this seems quite clunky to configure as I have to mix in the decorator with the decorated:
container.RegisterType<IThing, DecoratingThing>("ConfigX",
    new InjectionFactory(container => new DecoratingThing(new RealThing("ConfigX"));

container.RegisterType<DependerX>(
    new InjectionConstructor(new ResolvedParameter<IThing>("ConfigX");

And repeat, violating DRY nicely, for each DependerX.
What I'd like to do is remove the need to embed the construction of RealThing in the construction of DecoratingThing in each named registration of IThing - and declare the decoration just once. This is so, for example, that if the decoration needs to change in future, it's easier to reconfigure. The best I came up with is this helper method for registration:
void RegisterDepender<TDepender>(IUnityContainer container, string config)
{
    container.RegisterType<TDepender>(new InjectionConstructor(
        new ResolvedParameter<IThing>(config)));
    container.RegisterType<IThing, DecoratingThing>(config,
        new InjectionFactory(c => new DecoratingThing(new RealThing(config))));
}

This removes repetition at least, but I still have to embed the construction of the RealThing inside the DecoratingThing - this means I can't vary their lifetimes independently for example. I can't register IThing again to do this because I've used up my registration of that interface for the name. If I want to do that I have to introduce another set of named instances like so:
void RegisterDepender<TDepender>(IUnityContainer container, string config)
{
    string realConfig = "Real" + config;

    container.RegisterType<TDepender>(new InjectionConstructor(
        new ResolvedParameter<IThing>(config)));
    container.RegisterType<IThing, DecoratingThing>(config,
        new InjectionFactory(c => new DecoratingThing(
            container.Resolve<IThing>(realConfig))));
    container.RegisterType<IThing, RealThing>(realConfig,
        new ContainerControlledLifetimeManager(),
        new InjectionConstructor(config));
}

Is this really the best option? It feels complex and potentially hard for those that will come after to grok. Do other IoC containers have a compelling way to cover this scenario? Since the pattern for how injection works is repeated for each DependerX, is there a way to only use a named instance at the top (DependerX) level?
Any other comments?

A: The class design itself seems reasonable. Here's a convention-based container configuration that basically does this:
public class MyConventions : UnityContainerExtension
{
    protected override void Initialize()
    {
        var dependers = from t in typeof(IThing).Assembly.GetExportedTypes()
                        where t.Name.StartsWith("Depender")
                        select t;

        foreach (var t in dependers)
        {
            var number = t.Name.TrimStart("Depender".ToArray());
            var realName = "Real" + number;
            var decoName = "Deco" + number;
            var config = "Config" + number;
            this.Container.RegisterType<IThing, RealThing>(realName,
                new InjectionConstructor(config));
            this.Container.RegisterType<IThing, DecoratingThing>(decoName,
                new InjectionConstructor(
                    new ResolvedParameter<IThing>(realName)));
            this.Container.RegisterType(t,
                new InjectionConstructor(
                    new ResolvedParameter<IThing>(decoName)));
        }
    }
}

This configuration will automatically add all classes that match the above predicate, so once you've set it up, you can just add more classes (like Depender4 or Depender5) without revisiting the container configuration at all.
The above configuration satisfies these unit tests:
[Fact]
public void ContainerCorrectlyResolvesDepender1()
{
    var container = new UnityContainer().AddNewExtension<MyConventions>();
    var actual = container.Resolve<Depender1>();

    var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
    var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
    Assert.Equal("Config1", thing.Configuration);
}

[Fact]
public void ContainerCorrectlyResolvesDepender2()
{
    var container = new UnityContainer().AddNewExtension<MyConventions>();
    var actual = container.Resolve<Depender2>();

    var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
    var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
    Assert.Equal("Config2", thing.Configuration);
}

[Fact]
public void ContainerCorrectlyResolvesDepender3()
{
    var container = new UnityContainer().AddNewExtension<MyConventions>();
    var actual = container.Resolve<Depender3>();

    var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
    var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
    Assert.Equal("Config3", thing.Configuration);
}

A: Have you ever thought about basing your decorators on the Unity Interception functionality? Then it would be really easy to say "intercept the calls to IThing using this Interceptor" just once.
container.AddNewExtension<Interception>();
container.RegisterType<IThing>(new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<DecoratingThingBehavior>());

and then it would be "inject this IThing into this and that Depender"
container.RegisterType<Depender1>(new InjectionConstructor(new ResolvedParameter<IThing>("myNameForThing")));


text:
Q: Hitting 2 URLS using an anchor tag in Laravel I have got an ancor link tag on the DOM and would like to hit 2 URLS once it is clicked, the endpoints are route('b2c.receipt') and route('b2c.flushData')
 Download Receipt

A: You won't really be able to do this with a raw anchor tag.
Given the name of your second route, flushData, it may be that you can incorporate the "flush data" logic into the first route's controller function.
If not, you're going to need to use JavaScript to fire off two AJAX requests.


text:
Q: mgo/mongodb: aggregate - find all and order by membercount however membercount is an array of member userids The representation of 1 record (a community):
{
    "_id" : ObjectId("538a4734d6194c0e98000001"),
    "name" : "Darko",
    "description" : "Darko",
    "subdomain" : "darko",
    "domain" : "forum.dev",
    "created" : ISODate("2014-05-31T21:18:44.764Z"),
    "category" : "Art and Culture",
    "owner" : "53887456d6194c0f5b000001",
    "members" : [
        "53887456d6194c0f5b000001"
    ]
}

and the Go type
Community struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    Name        string        `json:"name"`
    Description string        `bson:",omitempty" json:"description"`
    Subdomain   string        `bson:",omitempty" json:"subdomain"`
    Domain      string        `json:"domain"`
    Created     time.Time     `json:"created"`
    Category    string        `json:"category"`
    Owner       string        `json:"owner"`
    Banned      []string      `bson:",omitempty" json:"banned"`
    Members     []string      `json:"members"`
    Moderators  []string      `bson:",omitempty" json:"moderators"`
    Admins      []string      `bson:",omitempty" json:"admins"`
    Logo        string        `bson:",omitempty" json:"logo"`
    Stylesheets []string      `bson:",omitempty" json:"stylesheets"`
    Javascripts []string      `bson:",omitempty" json:"javascripts"`
}

Ok now I'd like to retrieve a list of all communities of Category Art and Culture and order by the number of members aka members.length in js or len(Community.Members) in Go.
something like SELECT * FROM communities ORDER BY COUNT(members) WHERE category = 'Art and Culture'
I have a custom type to be filled or unmarshalled into
CommunityDirectory struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    Name        string        `json:"name"`
    Description string        `bson:",omitempty" json:"description"`
    Subdomain   string        `bson:",omitempty" json:"subdomain"`
    Domain      string        `json:"domain"`
    Created     time.Time     `json:"created"`
    Category    string        `json:"category"`
    Logo        string        `bson:",omitempty" json:"logo"`
    Membercount int64         `bson:"membercount" json:"membercount"`
}

What I have so far
func (ctx *CommunityContext) Directory() {
    pipe := ccommunity.Pipe([]bson.M{bson.M{"membercount": bson.M{"$size": "members"}}})
    iter := pipe.Iter()
    result := CommunityDirectory{}
    results := []CommunityDirectory{}
    for {
        if iter.Next(&result) {
            results = append(results, result)
            fmt.Println(result)
        } else {
            break
        }
    }
    ctx.JSON(results)
}

but this doesn't work because
db.communities.aggregate(
[
{"membercount": {$size:"members"}}
]
)

Error("Printing Stack Trace")@:0
()@src/mongo/shell/utils.js:37
([object Array])@src/mongo/shell/collection.js:866
@(shell):3

uncaught exception: aggregate failed: {
    "errmsg" : "exception: Unrecognized pipeline stage name: 'membercount'",
    "code" : 16436,
    "ok" : 0
}

So, it should find all, order by membercount and assign a new "virtual" field membercount but only of category 'Art and Culture'.
I find MongoDB quite complicated in this regard.

*

*What does the mongodb query look like?

*What does that look like in Go/mgo?

A: There are a few concepts to get used to when you are new to the aggregation framework
The correct form of the pipeline as it would work in the shell should be this:
db.communties.aggregate([

    // Match the documents first to filter and possibly make use of an index
    { "$match": {
        "category": "Art and Culture"
    }},

    // You include all fields when adding another and you want all
    { "$project": {
        "name": 1,
        "description": 1,
        "subdomain": 1,
        "domain": 1,
        "created": 1,
        "category": 1,
        "owner": 1,
        "members": 1,
        "memberCount": { "$size": "$members" }
    }},

    // $sort means "ORDER BY" in this case the ascending
    { "$sort": { "memberCount": 1 } },

    // Optionally project just the fields you need in the result
    { "$project": {
        "name": 1,
        "description": 1,
        "subdomain": 1,
        "domain": 1,
        "created": 1,
        "category": 1,
        "owner": 1,
        "members": 1
    }}
])

So there really is no direct equivalent of "SELECT *" unless you don't want to alter the structure at all. Here you need to add a field "memberCount" so you need to specify all of the fields. You can possibly use $$ROOT which copies all the fields in the document but you would need to assign that to another field/property in your $project, such as:
{ "$project": {
    "_id": "$$ROOT",
    "memberCount": 1
 }}

But now of course all your "fields" are not exactly the same as what they were and are all prefixed with _id.. But that is a matter of personal taste.
The next thing to get used to is always try to use $match first. Not only does this help reduce the documents operated on over the rest of the aggregation pipeline, it is also the only chance you get to use an index to optimize your query. Once you modify the documents with other stages, it's all over for using an index as this is no longer the original source that was indexed. Not that different from SQL really, but the semantics differ a somewhat in how you specify. Remember, "pipeline" just like a Unix "pipe" | operator, so do the "matching" first.
Sorting has it's own pipeline stage. So use the $sort operator for the pipeline stage to do this.
The final $project is optional. Here we are just discarding the "memberCount" field that was used to "sort".

The usage with mGo should turn out like this:
pipeline := [].bson.D{
    bson.M{"$match": bson.M{ "category": "Art and Culture" } },

    bson.M{"$project": bson.M{
        "name": 1,
        "description": 1,
        "subdomain": 1,
        "domain": 1,
        "created": 1,
        "category": 1,
        "owner": 1,
        "members": 1,
        "memberCount": bson.M{ "$size": "$members" }
    }},

    bson.M{ "$sort": bson.M{ "memberCount": 1 } },

    bson.M{ "$project": bson.M{
        "name": 1,
        "description": 1,
        "subdomain": 1,
        "domain": 1,
        "created": 1,
        "category": 1,
        "owner": 1,
        "members": 1
    }}
}

pipe := ccommunity.Pipe( pipeline )

So really not that different to the form of most examples out there you will find.
Possibly look at the SQL to aggregation Mapping Chart provided in the core documentation for other examples of common SQL queries as they apply to the aggregation pipeline.


text:
Q: Dagger2 dependent-component vs subcomponent What's the difference between Subcomponents and Dependent-Components with specific scope in action? What's pros or cons of every one?
My Story: Recently I decided to stop using dagger-android and completely switched to traditional dagger for dependency injection in the whole of my project. Do you have any recommendations for creating component/subcomponent per fragment/activity?

A: If you create sub-component, all your component's dependencies will get available in your sub-component too.
You can access sub-component only via parent component instance.
The sub-component, scope is considered smaller than that of its parent component. So, your parent component and sub-component can't use the same scope annotation.
If you create dependent-component, then you have to explicitly expose dependency in your parent component. Then only, the child-component can use it.
You can use dependent-component directly, but you'll have to provide instance of parent component to build a dependent-component.
Get more details from these videos: https://www.youtube.com/playlist?list=PLrnPJCHvNZuA2ioi4soDZKz8euUQnJW65

A: Just watched an interview, and the guy said that the downside of Subcomponents is that if you change anything inside them, the whole AppComponent gets regenerated (and in big codebases that can be very slow), while Dependent-Components are separate entities.
Will research that more and correct the post if it is wrong.


text:
Q: Customizing radio button grouping I have a scenario where I need to rank three options as high, medium or low. I have three radio buttons with values high, medium and low for each option. The selections need to be mutually exclusive.
JSFIDDLE
HTML
Option : 1
<input name="high" type="radio" value="H"> High
<input name="medium" type="radio" value="M"> Medium
<input name="low" type="radio" value="L"> Low

Option : 2
<input name="high" type="radio" value="H"> High
<input name="medium" type="radio" value="M"> Medium
<input name="low" type="radio" value="L"> Low

Option : 3
<input name="high" type="radio" value="H"> High
<input name="medium" type="radio" value="M"> Medium
<input name="low" type="radio" value="L"> Low

By naming the radion buttons this way, I could achieve avoiding a multiple high selections. But, this leads to allowing all of them to be selected for a single option as well because each option has radio buttons named differently.
I know this can be achieved with some JQuery validation. But, need to know if is there any other way to do this with HTML itself.
Thanks.

A: If i understand you correctly this should be the right way.
Option : 1
<input name="option1" type="radio" value="H"> High
<input name="option1" type="radio" value="M"> Medium
<input name="option1" type="radio" value="L"> Low

Option : 2
<input name="option2" type="radio" value="H"> High
<input name="option2" type="radio" value="M"> Medium
<input name="option2" type="radio" value="L"> Low

Option : 3
<input name="option3" type="radio" value="H"> High
<input name="option3" type="radio" value="M"> Medium
<input name="option3" type="radio" value="L"> Low


text:
Q: Scaling a line segment - Java In a project for my CS class, I am supposed to use a double value to scale a LineSegment and return a new LineSegment whose start Point is the same start Point of the old LineSegment, but with a new end point from being scaled. I am unsure of how to do this. I attempted to multiply the line segment by scalar, but that did not work and gave me an incompatible typing error. Here is my code.
public class LineSegment {
private final Point start;
private final Point end;
public LineSegment(Point start, Point end) {
    this.start = start;
    this.end = end;
}
public double slope() {
    return ((end.getY()-start.getY())/(end.getX()-start.getX()));
}
public double yIntercept() {
    return (start.getY()-(this.slope()*start.getX()));
}
public Point getStart() {
    return this.start;
}
public Point getEnd() {
    return this.end;
}
public double length() {
    return (Math.sqrt(Math.pow((end.getX()-start.getX()),2) + Math.pow((end.getY()-start.getY()),2)));
}

public LineSegment scaleByFactor(double scalar) {
    return null;
}
@Override
public String toString() {
    return ("y = " + this.slope() + "x +" + this.yIntercept());
}
}

A: This won't work:
public LineSegment scaleByFactor(double scalar) {
    return (this.length*scalar);
}

Note that the this.length field does not exist.
But even if you called the length method, length(), you'd still have a serious problem, since your method states that it will return a LineSegment Object and you'd be returning a number. I suggest that you use the calculation to create a new LineSegment object (hint -- call the constructor with new and with parameters that use your calculations) and then return it.
in pseudocode:
public LineSegment scaleByFactor(double scalar) {
    // use scalar, start and end to calculate a new end parameter value
    // create new LineSegement object with the old start and new end parameters
    // return this newly created object
}


text:
Q: Let a be a positive real number and let $M_a=\{z \in C^* : |z+\frac{1}{z}|=a\}$ Find the minimum.... Problem :
Let a be a positive real number and let $M_a=\{z \in C^* : |z+\frac{1}{z}|=a\}$ Find the minimum and maximum value of $|z|$ when $z \in M_a$
My approach :
$|z+\frac{1}{z}|=a$
Squaring both sides we get :
$\Rightarrow |z+\frac{1}{z}|^2=a^2$
$ \Rightarrow (z+\frac{1}{z})(\overline{z}+\frac{1}{\overline{z}}) =|z|^2+\frac{z^2+(\overline{z})^2}{|z|^2}+\frac{1}{|z|^2}$
$\Rightarrow |z|^4-|z|^2.(a^2+2)+1 = -(z+\overline{z})^ \leq 0$
Now how to approach further please suggest will be of great help. Thanks.

A: Hint:
$|z+\frac{1}{z}|=a$
$\Rightarrow |\frac{1}{z} (z^2 +1)|=a$
$\Rightarrow |z^2 +1|=a |z|$
$\Rightarrow |z^2 +1|^2=a^2 |z|^2$
Writing $z = r e^{i \theta}$ with $r>0$, the problem is to find the extremal values of $r$.
$\Rightarrow |r^2 e^{2i\theta} +1|^2=a^2r^2$
$\Rightarrow (1+r^2 \cos(2 \theta))^2 + r^4 \sin(2 \theta)^2 = a^2r^2$
$\Rightarrow r^4 + (2 \cos(2 \theta)-a^2) r^2 + 1 = 0 $
With the change of variable $X = r^2$ you get a quadratic equation in $X$:
$X^2 + \lambda X + 1 = 0$ with $\lambda=2 \cos(2 \theta)-a^2$
Solving this equation should give you the possible values of $r = |z|$.


text:
Q: How can I test race conditions created by multiple ajax requests to php? I'm using PHP to create some objects in a DB.  Sometimes, if a user requests an object while it is being created they can see the partially created object (the main db entry exists but not all of the child objects are inserted yet).  I recently implemented a fix, where my code will only serve up the object after it has been fully created by adding a 'creating' flag to the db entry.
How do I test this?  I'm using phpunit.  The two problems as I see it are that I need parallel threads to make the create and get requests at the same time, and I need to ensure that the timing is right so I can actually test the race condition (and not just get the object after it has been fully created).  I want my test to look like this, but am open to suggestions:

*

*thread 1: create the object

*thread 2: try to get the object before its fully created (should return an error)

*thread 1: get the object after its created (should work)

A: Testing for race conditions is already hard in languages that actually do support threads - with PHP, this is even harder. In a single-threaded context you'd have to trigger multiple requests in parallel, maintaining the correct order of these requests so that the test will not randomly fail.
I did it once with a test that checks whether the PHP session locking works correctly:
In PHPUnit I created a curl_multi_query firing three requests against the webserver at a special prepared php script that essentially only starts a session and then sleeps for one second.
The test is successful if the execution of the three requests lasts longer than about 2.5 seconds (don't ask about that time).
I assume the requests will be answered in any (possibly random) order. I am not sure the curl extension will guarantee to start the requests in a certain order. Additionally, I am not sure how the webserver will act when receiving three requests almost instantly. I must assume that the only way to detect locking was successful is to measure the time that passed.
Especially I am not sure that creating a test that will fire two parallel requests, expecting the first request to be successful, the second to always fail, like you want it, will reliably succeed. The only expectation would be that one request out of the two will fail.


text:
Q: How to access custom properties for the Image Gallery web part? I'm attempting to create a sharepoint page programatically by adding an image gallery web part.  How do I access the properties of that web part?  I don't see the documentation anywhere for Image Gallery like I do for the Image web part.  Custom Properties for Image Web Part

A: if you go to the hosted workbench (_layouts/15/workbench.aspx) and configure the canvas how you want, select the "Web Part Data" button on the top left.  That will pop up a window with the serialization format for both modern and classic.  The value in the "Modern Pages" tab is the value that should be stored in the canvas field.


text:
Q: Bar button action on ViewController in ViewContainer I have a container embedded in a ViewController with a navigation bar. The ContainerView contains another ViewController with some textfields.
When the ContainerView is first displayed, the textfields are disabled.
What I would like to do is add an edit button to the navigation bar which enables the textfields.
Basically, is it possible for a bar button item in a viewcontroller to have an action on another view controller displayed in a container?

A: in this case you can do a little trick
the bar button will be in the ViewController but we can store the content of the ContainerView in a variable in the first ViewController
to do that i would suggest to make the content of the ContainerView has a custom class so you would write a function in it
here is an example on how to catch the content of the ContainerView
class ViewController: UIViewController{
    weak var containter: ContainerViewController!

    @IBAction func menuAction(_ sender: UIBarButtonItem) {
        //do what you want containter.doAction()
   }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
      if let vc = segue.destination as? ContainerViewController {
         self.containter = vc
      }
   }
}

A: Always the case. I've been looking for an answer for hours, as soon as I ask I figure it out.
I'm not sure its the best way to do it but I just made an edit bool controller by the edit button. Then used:
    var child = self.childViewControllers[0]
    child.viewWillAppear(false)

This reloaded the data and if it was in edit mode enabled the textfields. Works fine!


text:
Q: Attempted import error: 'unstable_useId' is not exported from '@material-ui/core/utils' (imported as 'useId') I've just spent 3h trying to find a solution by myself, but I'm defintely stuck.
I'd like to use the Mui Autocomplete component, but whatever I try I get this message:
Failed to compile

./node_modules/@material-ui/lab/esm/useAutocomplete/useAutocomplete.js
Attempted import error: 'unstable_useId' is not exported from '@material-ui/core/utils' (imported as 'useId').

I already checked that my core and lab were up to date, but they are:
"@material-ui/core": "^4.9.11",
"@material-ui/lab": "^4.0.0-alpha.50",

And the weirdest is that it works like a charm on CodeSandBox with the very same setup...
No idea if this is a clue or not, but I noticed that, in the folder utils, almost every single file with a .js extension has its "clone" with .d.ts extension. Actually, in this folder, my unstable_useId.js doesn't have its .d.ts one, so... Might it be the problem?
Thanks a lot ! I hope I've been clear enough :)

A: change your @material-ui/lab module's version
FROM "@material-ui/lab": "^4.0.0-alpha.50"
To: "@material-ui/lab": "4.0.0-alpha.46"


text:
Q: Do I need CSP for a Web API? I'm pretty new to web development and just about understand how a Content Security Policy (CSP) can be used to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. This makes sense to me for a Web App issuing web pages. Would I still need to implement CSP for a Web API that just responds with data (json, xml etc.)?

A: When in doubt, I look at what websites with a decent security track record do. For example, Github seems to serve up some of their API responses with a pretty strict CSP:
Content-Security-Policy:default-src 'none'


text:
Q: Analytic function $f$ in $\overline{\mathbb{D}}$ satisfying $\left\lvert\,f'(\tfrac{1}{2})\,\right \rvert\leq 8.$ Let $f$ be an analytic function on the closed unit disk $\overline{\mathbb{D}}$.
On its boundary $\partial \mathbb{D}$ it holds that $\lvert\,f(z) -z\rvert < \lvert z\rvert$.
I now have to show that
$$
\left\lvert\,\, f'\left(\frac{1}{2}\right)\right\rvert \leq 8.
$$
I already figured out, that there cannot be a $\,z_0 \in \partial \mathbb{D}$, such that $\,f(z_0) =0,\,$ since that would mean that $\lvert 0-z_0\rvert < \lvert z_0\rvert\,$
which produces a contradiction, since the inequality is strict.
I also know, that $f$ takes its maximum on $\partial \mathbb{D}$ according to the maximum modulus principle.
My assumption is that i should get $\,\lvert\,f'(z)\rvert < \lvert z^{-3}\rvert\,$ by looking at the numbers, which seem a bit random to me.
But now I'm stuck. Any help would be greatly appreciated!

A: Cauchy's Integral Formula provides that
$$
f'\Big(\frac{1}{2}\Big)=\frac{1}{2\pi i}\int_{|z|=1}\!\frac{f(z)\,dz}{\big(z-\frac{1}{2}\!\big)^2},
$$
and hence
\begin{align}
\left\lvert\, f'\Big(\frac{1}{2}\Big)\right|&\le
\frac{\max_{|z|=1}\lvert\,f(z)|}{(1/2)^2}=4\max_{|z|=1}\lvert \,f(z)|\le
4\max_{|z|=1}\big(\lvert\, f(z)-z|+|z|\big)
\\&\le 4\max_{|z|=1}\big(|z|+|z|\big)=8.
\end{align}


text:
Q: C, detect cycle in directed graph, DFS, inconsistent graph i write program to detect cycle in directed graph, but on testing server is tests with inconsistent graph, and i don't know how change my program for this graph. I used DFS. For input like:
3 3
1 2
2 3
3 1

is ok but i don't know how detect that graph is inconsistent, e.g for input:
5 4
1 2
2 3
4 5
5 4

First line of input is number of verticles and number of connection.
Here is my code:
#include <stdio.h>
#include<stdlib.h>

void dfs(int v, int reach[], int *tab[], int vert)
{
    int i;
    reach[v]=1;
    for(i=0;i<vert;i++)
    {
        if(tab[v][i]&&!reach[i])
        {
            dfs(i, reach, tab, vert);
        }
    }
}

int main()
{
    //wczytaj wymiary
    int vert,edge, i, j, e1, e2, count;
   // printf("number of verticles: ");
    scanf("%d",&vert);
  //  printf("number of connections: ");
    scanf("%d",&edge);

    int *reach;
    int **tab;
    reach=(int*)malloc((vert+1)*sizeof(int));
    tab=(int**)malloc((vert+1)*sizeof(int *)); //alokacja pamieci
    for( i=0; i<vert; i++)
    {
        tab[i]=(int*)malloc((vert+1)*sizeof(int));
       // printf("ok\n");
    }
    for(i=0;i<vert;i++)
    {
        reach[i]=0;
        for(j=0;j<vert;j++)
        {
            tab[i][j]=0;
        }
    }

    for(i=0;i<edge;i++)
    {
        scanf("%d", &e1);
        scanf("%d", &e2);
        tab[e1-1][e2-1]=1;
       // printf("ok %d\n", tab[e1-1][e2-1]);
    }
    for(i=0;i<vert;i++)
    {
        for(j=0;j<vert;j++)
        {
           // printf("%d\n",tab[i][j]);
        }
    }

    dfs(1, reach, tab, vert);
   // printf("\n");

    for(i=0;i<vert;i++)
    {
        if(reach[i])
            count++;
        printf("count: %d", count);
    }
    if(count==vert)
        printf("graph have cycle");
    else
        printf("graph doesn't have cycle");
return 0;

}

A: This is buggy code.
Lets take below example:
No of vertices = 4
Edges = 3
Edges from (2, 1) (2, 3) (2, 4)
tab[][] {0 0 0 0
         1 0 1 1
         0 0 0 0
         0 0 0 0}
There is no cycle but this code says its cyclic graph.
As per my understanding ur only checking graph is connected or not.

A: You have to at least check that your graph does not have the duplicated edges.
That can easily be done in that part of your code: instead of just assigning the entry, check if it was already been initialized. If yes, then your graph has duplicated edges.
for(i=0;i<edge;i++)
{
    scanf("%d", &e1);
    scanf("%d", &e2);
    if (tab[e1-1][e2-1]==1) {
       printf("duplicated edge between %d and %d",e1, e2);
       exit(-1);
    } else tab[e1-1][e2-1]=1;
   // printf("ok %d\n", tab[e1-1][e2-1]);
}


text:
Q: Passing data between two Fragments in a VIewPager (Android) (NullPointerException) So basically I have 2 Fragments - FragmentConverter and FragmentFavourites, and I have one MainActivity. I'm trying to pass 4 arrays from the first fragment to the second one using an Interface called Communicator. The specific snippets are show below:
public interface Communicator {

    public void respond(String[] names, String[] codes, String[] symbols, int[] images);
}

This is a method inside FragmentFavourites:
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

        String[] checkedNames = new String[counter];
        String[] checkedCodes = new String[counter];
        String[] checkedSymbols = new String[counter];
        int[] checkedImages = new int[counter];
        comm = (Communicator) getActivity();
        int index = 0;
        if (item.getItemId() == R.id.action_save){
            for (int i=0;i<checked.size();i++){
                if (checked.get(i) == true){
                    checkedNames[index] = names[i];
                    checkedCodes[index] = codes[i];
                    checkedSymbols[index] = symbols[i];
                    checkedImages[index] = images[i];
                    index++;
                }

            }
            comm.respond(checkedNames, checkedCodes, checkedSymbols, checkedImages);
        }

        return super.onOptionsItemSelected(item);
    }

This is the implemented interface method inside MainActivity:
@Override
public void respond(String[] names, String[] codes, String[] symbols,
        int[] images) {
    // TODO Auto-generated method stub
    FragmentConverter frag = (FragmentConverter) fragmentPagerAdapter.getItem(1);
    frag.changeData(names, codes, symbols, images);
}

And this is a method that collects the data in FragmentConverter:
public void changeData(String[] names, String[] codes, String[] symbols, int[] images){
        this.names = names;
        this.codes = codes;
        this.symbols = symbols;
        this.images = images;

        Log.d("TEST", symbols.length + names.length + codes.length + images.length + "");
        tvOneRate.setText(names[1]);
}

Now the problem is that whenever I try to change a ui component inside FragmentConverter, I get a NullPointerException, though the Log.d statement returns the correct results.
EDIT1: getItem() method of FragmentPagerAdapter:
@Override
    public Fragment getItem(int i) {
        // TODO Auto-generated method stub
        Fragment frag = null;
        if (i == 0){
            frag = new FragmentFavourites();
        }
        if (i == 1){
            frag = new FragmentConverter();
        }
        return frag;
    }

A: EDITED:
When you call fragmentPagerAdapter.getItem(1) you are getting a new instance of the fragment so you are referring to a different object. this is why the view is null and you get the NullPointerException. If you need an adapter for only 2 fragments, you can try with something like that:
public class YourPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {

        private FragmentFavourites mFragFavourites;
        private FragmentConverter mFragConverter;

        public YourPagerAdapter() {

            // ... your code above
            this.mFragFavourites = new FragmentFavourites();
            this.mFragConverter = new FragmentConverter();
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return mFragFavourites;

                case 1:
                    return mFragConverter;
                default:
                    return null;
            }
        }
    }

A: As above carlo.marinangeli has suggested when you call fragmentPagerAdapter.getItem(1) you are getting a new instance of the fragment so you are referring to a different object
So to get same object from you adapter you need to store your object. you can try following method in your adapter -
public Fragment getFragmentAtPosition(int position) {
            return registeredFragments.get(position);
}

where registeredFragments is -
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();

and fill this sparseArray in getItem method like below -
@Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    fragment = FragmentPost.newInstance(position);
                    registeredFragments.put(position, fragment);
                    return fragment;
               }
            return null;
        }

A: By using fragmentPagerAdapter.getItem(pos) method I was referring to a new object every time the respond() method was called. I fixed it by using findFragmentByTag() method instead:
    @Override
    public void respond(String[] names, String[] codes, String[] symbols,
            int[] images) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentConverter frag = (FragmentConverter) manager.findFragmentByTag("android:switcher:" + pager.getId() + ":" + 1);
        frag.changeData(names, codes, symbols, images);
    }

A: you can get that error because you are assuming that you have got the FragmentConverter and the views associated to it.
Without a logcat it becomes a little bit difficult to help you but basically what I would like to do in a situation like this is to pass everything through the activity without letting know the existence of the other fragment to the fragments.

*

*F1 modifies a state object into the activity

*F2 has to register as a
listener to the activity (be aware that the fragment can be attached
and detached in the view pager)

*The Activity as soon it receives an updated, looks for all the registered listeners and if there is someone it delivers the updated


text:
Q: What is LaTeX3 correcting in LaTeX2e? And, updates 2021 on LaTeX implementation on small mobiles OS? There are so many things wrong with LaTeX2e according to the latest discussion, Why is LaTeX3 taking so long to come out?, from documentation to speed, inflexible kernel, etc. We are perhaps waiting in vain for LaTeX3 and expl3 full deployment but what is called "gentle re-fractory" see What's the current state of LaTeX3 (2020)?.
What are the deficiency and features in LaTeX2e that LaTeX3 project hence "gentle refractory" and L3 programming seeks to provide solution to (and how significant )?  Surely separating design and codes will be great, but LaTeX3 project must prove it's relevance in terms of quality of extension, alternate solutions, user interface and better features than LaTeX2e!
Secondly, I haven't seen any basic and compilable Tex for mobiles OS like android. Many use online Tex Editors and tools or snippets  like Overleaf. Will need latest implementation of TeX on say android OS and MacOS.
In my opinion, LaTeX3 project has taken so much time, (more than 20years since the project started), and surlely new issues of change due to time will continually postpone "getting perfected for release" Sure, it won't be able to replace LaTeX2e and conTeXt but "soft refractory" for possible modernization
I find information on the following discussions partly useful and educating..

*

*What's the current state of LaTeX3 (2020)?

*What are the best practices for programmatic interaction between LaTeX3 and LaTeX2e?.

*What is the e specifier for LaTeX3 and where is it documented?.
Am currently working on mobile implementation of TeX-Latex.

A: To some extent, and am really happy with the discussion at What's the current state of LaTeX3 (2020)?
and log report showing the <  LaTeX2e <2020-10-01> patch level 2 L3 programming layer <2020-10-27> xparse <2020-03-03> >. Which shows that it is already being introduced to LaTeX2e, in "a gentle re-fractory" sort of principle.
However ,that was as situation was last year October-November 2020. It seems we are never going to see LaTeX3 as a standalone product or a name replacing LaTeX2e.
It will be good if @Fischer can discribe what "problems" or deficiency in LaTeX2e and conTeXt that LaTeX3 project hence "gentle refractory"  seeks to provide solution (and how significant?)
Notes: LaTeX Project (used to be LaTeX3 project in alias) has made the decision to drop the idea of a separate LaTeX3 format that would exist in parallel to LaTeX2e, but instead decided to gradually modernize LaTeX to keep it competitive in today's world while maintaining compatibility methods for older documents. [https://www.latex-project.org/latex3/]
As part of this change of focus the following major improvements have been introduced in the last few years:

*

*2018: Full support for Unicode input; UTF-8 became the default encoding in LaTeX;

*2019: Introduction of the LaTeX development formats to allow people to try out upcoming releases with ease;

*2020: Integration of the L3 programming layer into the LaTeX format; the first uses of this layer inside the format are a new general hook management system for LaTeX, and the xparse document commands (formerly available as a package);
Interface extensions to NFSS (The LaTeX font selection scheme) to better support modern fonts (OpenType and others).

And recall that at the TUG conference 2020, the group announced the start of a multi-year project (financially supported in part by Adobe) to provide LaTeX support for the straightforward production of 'tagged PDF'. Please note that conTeXt is an independant format and which does not relate to the LaTeX Team. The main project being worked-on by the Team is the tagged pdf project, which involves a lot of other tasks too. See https://www.latex-project.org/publications/indexbyyear/2020 .
Hope, and for better days and more intuitively productive document Typesetting System.

A: And, on implementing Tex ( editing and compiling) on small mobile and tablet PC,

*

*there is a work by Clerk Ma "TeXLive for Android. " (http://code.google.com/p/texlive-for-android/ ) but with unresolved issues relating to font and Bibliography, and installing on Android 5.0 and above.

*VerbTeX Pro is another for editing latex documents, which gives a nice android-friendly UI . Downloable on google play.
(https://www.google.com/url?q=https://play.google.com/store/apps/details%3Fid%3Dverbosus.verbtex%26hl%3Den%26gl%3DUS%26referrer%3Dutm_source%253Dgoogle%2526utm_medium%253Dorganic%2526utm_term%253Dmobile%2Btex%2Beditor&sa=U&ved=2ahUKEwit8pWl5vDvAhVFhf0HHcKVBDMQFjAAegQIARAB&usg=AOvVaw2pH76F8ZYmJ0MSWN-wQD-0 )

*Tex portal also on google play.
Am personally making my own [a collaborative lab work] by extracting only essential packages from Texlive and will be working on minimum packages needed and compatible fonts(Asia, Africa, Europe) as was kindly suggested to me in a chat.
You would like to help? You are most welcome!
Please, let me know in whatever capacity you could be of help - similar works or informed-direction.  Thanks a lot


text:
Q: overriding methods without subclassing in Java I started on a new project recently and saw the usage of overriding like below for the first time.
public class SomeClass {
  public void myMethod() {
    XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
 // the rest ommitted

Basically, it's overriding the wrapMapper() method of the XStream class in the thoughtworks xstream api but without having SomeClass to extend the XStream class.  I've worked with Java for a number of years but this is the first time I saw overriding being done like this.  Can someone explain the ins and out of it?  Thanks.

A: That's an Anonymous Inner Class.

A: In this case the XStream class is an anonymous inner class. Then you're overriding the method of your anonymous XStream class.

A: The new implementation for

wrapMapper(MapperWrapper next)

method is limited for this instance xstream

XStream xstream

this type of overriding is creating a class that extends XStream, that's why it is called Anonymous, do not have a name and you can not have a reference for it.

A: That is called an "Anonymous class". You can find a lot of documentation about this special syntax on Internet. Good luck.

A: Search Google for Anonymous Inner Class in Java
That's pretty useful to implement interfaces or abstract Class methods on concrete objects
That's heavily used when working with threading (Runnable class)


text:
Q: Android IntentService never called I've got an IntentService that I want to start upon onCreate. It's a fire and forget that makes a call to a website and then (possibly) starts a download through downloadmanager. I don't believe that my service is being started, because I don't see any Log statements from it. I've got the service in my manifest, same package as main. It also does not show up in my logcat (another thread said it should).
onCreate:
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    Intent heartbeat = new Intent(this, Heartbeat.class);
    startService(heartbeat);
}

*I've also tried this.startService(heartbeat); and it also did not work.
manifest:
<application
    android:debuggable="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <service android:name=".Heartbeat" android:enabled="true"/>

    <activity
        android:name=".MainActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:label="@string/title_activity_main" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

*with or without android:enabled flag makes no difference
start of IntentService:
public class Heartbeat extends IntentService
{
    public Heartbeat()
    {
        super("Heartbeat");
        Log.v("SUPER", "SUPER");
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Log.v("HERE", "HERE");
        //do other stuff

Neither of these log statements show up in console/logcat, and my service never hits the web server (this code was previously in an asynctask and was functioning). Any ideas on what I'm doing wrong?
Edit - I do see a warning from tag ActivityManager in my all messages stating "Unable to start service Intent { act=com.example.vs_1.Heartbeat }: not found". However, nearly every suggestion I've seen on that message has been to put  in manifest in the application tag, which I've already done.

A: Ah, the plot thickens!
"Unable to start service" is an error, even though it's marked as a warning.
It occurs because the system can't find a class that has the name that's listed. In this case,
it's com.example.vs_1.Heartbeat.
To be sure you have that class, you need a file Hearbeat.java that contains
package com.example.vs_1;
public class Heartbeat extends IntentService...
In your manifest, if your  element contains the attribute
package="com.example.vs_1", then you can say
 Note the period (".") before "Heartbeat".
If you're using another value for "package", then you have to say
/com.example.vs_1.Heartbeat" where  is the value of "package".
It should be clear from this that you should choose a single main package name for your classes, and use the same name for the "package" value.

A: Are you sure the main Activity is being started correctly? LogCat would show you error messages if the system couldn't start your IntentService. Also, these are "verbose" messages, so be sure that LogCat is set to show them. If you have LogCat set to "error", it won't show verbose messages.


text:
Q: String to List Hello I am new to data management and I have stuck walking these values.
I am using the Hive local storage package, which only allows me to store primitive variables, which is why I converted my service response to a String and stored it in a Box (of Hive).
I need to transform that string, to a List of my objects (List <LanguageModel>), to finally pass it to a widget.
Thanks
This is the transformed string of the objects

This is the model I use, the toJsonManual () method, it is the one I was trying to use (but it didn't work)

A: if i get it right .
you want to store your List as String  to save  .
then read it later and convert the String to a List .
you can do it without any code genration
final list = <String,dynamic>[
{'name':'arabic' , 'prefix':'ar'},
{'name':'english' , 'prefix':'en'},
];

for simplicity you can use shared preferences to store List<String>
just map throw the list and use jsonEncode to conver Map to String
untill now you can
import 'dart:convert';
final data = {'data':list)};
final String encodedData = jsonEncode(data);

here you go to convert List to String
my advice is to use the simple option or SQLite  to skip the complexity of decode and encode


text:
Q: MSXML2.ServerXMLHTTP - can't access website For instance, kat.cr is one of the few websites I cannot access.
In the response, I get 2 symbols instead of the actual webpage:

Here's the VBA code I'm using:
url = "https://kat.cr"
Set xmlHTTP = CreateObject("MSXML2.serverXMLHTTP")
xmlHTTP.Open "GET", url, False
xmlHTTP.setRequestHeader "Accept-Language", "en-US,en;q=0.8"
xmlHTTP.setRequestHeader "Content-Type", "text/xml"
xmlHTTP.Send

Set html = CreateObject("htmlfile")
response = xmlHTTP.responseText

Is the website actually denying me access or am I doing something wrong?

A: The website is not denying you access, it's your code I am afraid. Below is a quick example to get the HTML you want from the page you visit.
Note: This was just a quick type-o, but to help get you in the right direction.
Dim ie As InternetExplorer
Dim html As HTMLDocument

Set ie = New InternetExplorer
ie.Visible = False
ie.navigate "https://kat.cr"

Set html = ie.document
'this is the inner html  -html.DocumentElement.innerHTML
Set ie = Nothing

Edit - This might be a better solution for you
Set xmlHTTP = New MSXML2.XMLHTTP
xmlHTTP.Open "GET", "https://kat.cr", False
xmlHTTP.send

Dim doc As Object
Set doc = CreateObject("htmlfile")
doc.body.innerHTML = xmlHTTP.responseText
debug.print doc.body.innerHTML

A: Use CreateObject("MSXML.XMLHTTP") for client applications. ServerXMLHttp is meant for server applications. See this article for more information on the two.
Set xmlHTTP = CreateObject("MSXML2.XMLHTTP")
xmlHTTP.Open "GET", "https://kat.cr", False
xmlHTTP.Send
Debug.Print xmlHTTP.responseText


text:
Q: Call flutter widgets dynamically by their name (with a string)? I have several custom widgets which alle accept the same data type as a parameter:
class Widget1 extends StatelessWidget {
  Widget1({@required this.data});
  final data;
}

class Widget2 extends StatelessWidget {
  Widget2({@required this.data});
  final data;
}

...

I have another widget which acts like a widget manager:
class WidgetManager extends StatelessWidget {
  final data;
  final type;

  WidgetManager({this.data, this.type});

  @override
  Widget build(BuildContext context) {
    if (this.type == 'Widget1') {
      return Widget1(data: this.data);
    } elseif (this.type == 'Widget2') {
      return Widget2(data: this.data);
    }
  }
}

In PHP I could call the widgets with a string like this:
$widget_name = 'Widget1';
$widget = new $widget_name($data);

Is there any way to do a similar thing in flutter?
Like return this.type(data: this.data);?


text:
Q: Google Cloud Function to schedule exports for datastore entities We have an app hosted in GCP AppEngine. This app saves images and other data in datastore. The images are separated entities (kinds) say Kind1 and Kind2. We only need to export these two entity kinds and store the export  in a storage bucket called datastore-exports. We have exported these two entity kinds manually via console. We would like to create a cloud function that could export the two fore mentioned datastore entity kinds on a daily basis every 24 hours. I need assistance on the files and code logic for this to take place.
Below are two examples that I came across that are somewhat what we want to accomplish.
I see they are doing that with firestore HERE.
I also had a look at this doc HERE but we need to use python 3.
Any assistance on either node.js or python3 methods will be highly appreciated.
Thanks,

A: I tried to reproduce your use case:

*

*Run the command:
 gcloud app decribe
 # .......
 #locationId: europe-west2

*Make sure that your export bucket and your cloud function are deployed in the same location.

*Your cloud function will use App Engine default service account.
 PROJECT_ID@appspot.gserviceaccount.com

*Assign to this service account the role Datastore Import Export Admin
(I would recommend to create a new service account for your cloud function, not using App Engine default service account.)

*Create the cloud function:
a.main.py
def export_datastore(request):
    import google.auth
    import google.auth.transport.requests
    import json
    import requests

    #Get the Access Token
    creds, project_id = google.auth.default()
    auth_req = google.auth.transport.requests.Request()
    creds.refresh(auth_req)

    token = creds.token
    output_url_prefix = 'gs://your-bucket'
    url = 'https://datastore.googleapis.com/v1/projects/{}:export'.format(project_id)

    #We export all kinds and all namespaces
    entity_filter = {
                      'kinds': [],
                      'namespace_ids': []
                  }

    request = {
             'project_id': project_id,
             'output_url_prefix': output_url_prefix,
             'entity_filter': entity_filter
           }

    headers = {
                 'Content-Type': 'application/json',
                 'Authorization': 'Bearer ' + token,
                 'Accept': 'application/json'
            }
    #Call the API to make the Datastore export
    r = requests.post(url, data=json.dumps(request), headers=headers)
    print(r.json())
    return('Export command sent')

b. requirements.txt
  # Function dependencies, for example:
  google-auth

*Use Google Cloud Scheduler to call the cloud function every 24 hours.


text:
Q: Error in .pointsToMatrix(p1) : latitude < -90 _- getting this error in R file_data_frame$sg_long <- 103.843061
file_data_frame$sg_lat <- 1.276105
distGeo(file_data_frame[,c("LONGITUDE","LATITUDE")],
        file_data_frame[,c("sg_long","sg_lat")])/1609.35

some data from the data frame file_data_frame with negative values are as below,

It is working fine with -90 to 90 latitude value. Please help.


text:
Q: two array foreach echo I am having trouble with showing my data. i have 2 arrays, i want to check it if array 2 is equal to array 1. in the sample array below the output should be like this. Any answers would be appreciated. i am a newbie

100000, 010000, 010000, 000001, 000001, 100000, 100000

array 1 data
array(6) {
  [0]=>
  object(stdClass)#370 (1) {
    ["id"]=>
    string(1) "1"
  }
  [1]=>
  object(stdClass)#369 (1) {
    ["id"]=>
    string(1) "2"
  }
  [2]=>
  object(stdClass)#368 (1) {
    ["id"]=>
    string(1) "3"
  }
  [3]=>
  object(stdClass)#367 (1) {
    ["id"]=>
    string(1) "4"
  }
  [4]=>
  object(stdClass)#366 (1) {
    ["id"]=>
    string(1) "5"
  }
  [5]=>
  object(stdClass)#365 (1) {
    ["id"]=>
    string(1) "6"
  }
}

array 2 data
array(7) {
  [0]=>
  object(stdClass)#354 (1) {
    ["stage_id"]=>
    string(1) "1"
  }
  [1]=>
  object(stdClass)#355 (1) {
    ["stage_id"]=>
    string(1) "2"
  }
  [2]=>
  object(stdClass)#353 (1) {
    ["stage_id"]=>
    string(1) "2"
  }
  [3]=>
  object(stdClass)#352 (1) {
    ["stage_id"]=>
    string(1) "6"
  }
  [4]=>
  object(stdClass)#378 (1) {
    ["stage_id"]=>
    string(1) "6"
  }
  [5]=>
  object(stdClass)#377 (1) {
    ["stage_id"]=>
    string(1) "1"
  }
  [6]=>
  object(stdClass)#376 (1) {
    ["stage_id"]=>
    string(1) "1"
  }
}

This is what i have tried and doesnt work. it only shows 100000
foreach ($this->stage as $index => $object)
{
    if (isset($this->items[$index]) && $object->id == $this->items[$index]->stage_id)
    {
        echo 1;
    }
    else
    {
        echo 0;
    }
}


text:
Q: Get real time updates from a Facebook page I do not own Is it possible to get real time updates from a Facebook page that I'm not a owner with Graph API 2.x.?
For example, when the page adds a new post.

A: No, this isn't possible. Only for Pages which use the app:

*

*https://developers.facebook.com/docs/graph-api/reference/v2.2/app/subscriptions#publishperms

Subscriptions for the object type page will only be valid for Pages that have installed the app. You can install the app for a Page using the /{page-id}/subscribed_apps edge.


text:
Q: Internet Explorer finds error in core Vue.js file I have a Vue.js-based application which works fine in all browsers. Except, you guessed it...
When I try to open it in Internet Explorer, I get this error:
Expected identifier in vue.min.js, line 6 character 4872

When I navigate to that line/character, it shows that the error is in code that says:
var i=e.extends;

To be precise, IE places the cursor right after the dot in the expression above when I go to the error.
Vue.js is included from https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js but I get the same issue if I include it locally.
Is there a solution to this besides telling users to use a different browser?

A: I made a test with above Vue JS file in IE.
Based on my testing results, I find that this error can occur with older versions of IE like IE-5, IE-7, IE-8.
Error did not occurred with IE-9, IE-10, IE-11.
Here is a testing result.

Here, I want to suggest you to upgrade to IE 11 version which latest and only supported version currently.
Microsoft had already stopped providing support for other older versions of IE.
If you upgrade to IE 11 than it will be helpful to solve your issue.


text:
Q: What is the diffecence between these two if-else block and conditional operator block? I think those two blocks have same meaning but the second code doesn't work even though the first works.
The second one looks not that cool, but I think it is easier to understand than the first one.
The first one is a part of very simple React practice code on here(https://en.reactjs.org/docs/lifting-state-up.html)
, and I made a little modification on it.
//1st
  const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
  const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

//2nd
  if(scale === 'f') {
    const celsius = tryConvert(temperature, toCelsius);
    const fahrenheit = temperature
  } else if (scale === 'c') {
    const celsius = temperature;
    const fahrenheit = tryConvert(temperature, toFahrenheit);
  } else {
    const celsius = temperature;
    const fahrenheit = temperature;
  }

Running my React code including the second codes, Error message appears on console that "celsius is not defined".
In the second code, I think that 'celsius' must be defined whatever 'scale' is because there is else statement in the last of block.
What is the difference between those two codes?
I'm sorry for my bad english..
Thanks for reading my question!

A: your code works. the problem is that const (and also let) are so-called "block scoped". Thus; if you define them inside a if/for/while they are only defined inside of that block.

A: I guess the issue is not here in this code. It might be there you accessing celsius variable/constant.
Declare the variable outside the if-else-if block like this
 let celsius = temperature
 let fahrenheit = temperature
 if(scale === 'f') {
    celsius = tryConvert(temperature, toCelsius);
 }
 if (scale === 'c') {
    fahrenheit = tryConvert(temperature, toFahrenheit);
 }

In this way, you don't need the 3rd block. If you don't like to use a conditional operator and want to make it better, try this.
 let celsius = temperature
 let fahrenheit = temperature
 if(scale === 'f') celsius = tryConvert(temperature, toCelsius);
 if (scale === 'c')  fahrenheit = tryConvert(temperature, toFahrenheit);


text:
Q: Python : append a list to a list I'm doing some exercises in Python and I came across a doubt. I have to set a list containing the first three elements of list, with the .append method. The thing is, I get an assertion error, lists don't match. If I print list_first_3 I get "[['cat', 3.14, 'dog']]", so the double square brackets are the problem. But how can I define the list so the output matches?
list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3.append(list[:3])

assert list_first_3 == ["cat", 3.14, "dog"]

A: When appending a list to a list, the list becomes a new item of the original list:
list_first_3 == [["cat", 3.14, "dog"]]

You are looking for:
list_first_3 += list[:3] # ["cat", 3.14, "dog"]

This adds every item from list to list_first_3.
Also you shouldn't name your variables like inbuilt types like list.
If you NEED to append, you could use a for-loop:
list_first_three = []
for item in list[:3]:
    list_first_three.append(item)

A: append can only add a single value. I think what you may be thinking of is the extend method (or the += operator)
list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3.extend(list1[:3])

assert list_first_3 == ["cat", 3.14, "dog"]

or
list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3 += list1[:3]

assert list_first_3 == ["cat", 3.14, "dog"]

otherwise you'll need a loop:
list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
for value in list1[:3]: list_first_3.append(value)

assert list_first_3 == ["cat", 3.14, "dog"]

with append but without a loop would be possible using a little map() trickery:
list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
any(map(list_first_3.append,list1[:3]))

assert list_first_3 == ["cat", 3.14, "dog"]

A: Your problem is that you try to append a list to another list.
list[:3] will return you the result ["cat", 3.14, "dog"]
Then, you take that result as a whole and put it as an item in list_first_3.
If you want to fix that, you can do:
list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3 += list[:3]

assert list_first_3 == ["cat", 3.14, "dog"] # Return True

And if you insist using append method:
list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []

for item in list[:3]
    list_first_3.append(item)

assert list_first_3 == ["cat", 3.14, "dog"] # Return True


text:
Q: R read.table csv with classic-mac line endings I have a comma-separated value file that looks like this when I open it in vim:
12,31,50,,12^M34,23,45,2,12^M12,31,50,,12^M34,23,45,2,12^M

and so forth.  I believe this means my CSV uses CR-only (classic mac) line endings.  R's read.table() function ostensibly requires LF line endings, or some variant thereof.
I know I can preprocess the file, and that's probably what I'll do.
That solution aside: is there a way to import CR files directly into R?  For instance, write.table() has an "eol" parameter one can use to specify the line ending of outputs -- but I don't see a similar parameter for read.table() (cf. http://stat.ethz.ch/R-manual/R-patched/library/utils/html/read.table.html).

A: R will not recognize "^M" as anything useful.(I suppose it's possible that vim is just showing you a cntrl-M as that character.) If that were in a text-connection-stream R will think it's not a valid escaped-character, since "^" is not used for that purpose. You might need to do the pre-processing, unless you want to pass it through scan() and substitute using gsub():
subbed <- gsub("\\^M", "\n", scan(textConnection("12,31,50,,12^M34,23,45,2,12^M12,31,50,,12^M34,23,45,2,12^M"), what="character"))
Read 1 item

> read.table(text=subbed, sep=",")
  V1 V2 V3 V4 V5
1 12 31 50 NA 12
2 34 23 45  2 12
3 12 31 50 NA 12
4 34 23 45  2 12

I suppose it's possible that you may need to use "\\m" as the patt argument to gsub.
A further note: The help page for scan says: "Whatever mode the connection is opened in, any of LF, CRLF or CR will be accepted as the EOL marker for a line and so will match sep = "\n"." So the linefeed character ("\n"if that's what they are) should have been recognized them, since read.table is based on scan. You should look at ?Quotes for information on escape characters.
If this vim tutorial is to be believed those may be DOS-related characters since it offers this advice:
Strip DOS ctrl-M's:
:1,$ s/{ctrl-V}{ctrl-M}//

A: There is an R native solution that requires no preprocessing or external hacks. You should use the encoding input argument to the read.table function and set it equal to "latin1" for Mac character encoding.
For example, say your file in Mac (^M for return) format is saved as test.csv, load as follows:
 test <- read.table("./test.csv", sep=",", encoding="latin1")

To see what options you can pass the encoding argument type ?Encoding into the R interpreter and you will see "latin1", "UTF-8", "bytes" or "unknown"are the supported encodings.
This is the best & cleanest way to do this.


text:
Q: Training a spaCy NER model and losses keep increasing with iterations and batches # Create a blank 'en' model
nlp = spacy.blank("en")

# Create a new entity recognizer and add it to the pipeline
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
# Add a new label
ner.add_label('LABEL')

# Start the training
optimizer = nlp.begin_training()
# Loop for 10 iterations
for itn in range(10):
# Shuffle the training data
    random.shuffle(spacy_train)
    losses = {}
    # Batch the examples and iterate over them
    for batch in spacy.util.minibatch(spacy_train, size=spacy.util.compounding(4.0, 32.0, 1.001)):
        texts = [text for text, entities in batch]
        annotations = [entities for text, entities in batch]
        print("epoch: {} Losses: {}".format(itn, str(losses)))
    # Update the model
        nlp.update(texts, annotations, drop=0.5, losses=losses, sgd=optimizer)

I'm trying to train a spaCy NER model and followed the spaCy training guide. Over time the losses should go down, however with each epoch it keeps going up. I've tried tweaking the batch size and iterations to no avail.
Examples:
epoch: 0 Losses: {}
epoch: 0 Losses: {'ner': 37.49999785423279}
epoch: 0 Losses: {'ner': 72.21390223503113}
epoch: 0 Losses: {'ner': 93.70724439620972}
epoch: 0 Losses: {'ner': 124.94790315628052}
epoch: 0 Losses: {'ner': 164.6911883354187}
epoch: 0 Losses: {'ner': 182.06093049049377}
epoch: 0 Losses: {'ner': 200.32691740989685}
epoch: 0 Losses: {'ner': 210.71145126968622}
epoch: 0 Losses: {'ner': 222.89578241482377}
epoch: 0 Losses: {'ner': 233.59122055233456}
epoch: 0 Losses: {'ner': 245.26212133839726}
epoch: 0 Losses: {'ner': 258.0684297736734}
For the last batch of this epoch, losses are 11,000. Appreciate the help.


text:
Q: Python - Django - server - Searches for installed module in wrong version of Python using WinSCP when I try to load my server using Django, I get a 'no module named bs4' error. It seems that it searching to for it in Python 2.7 library instead of Python3.6. python 3.6 is in my PATH. I tried looking, but I'm pretty new to this and don't quite understand all the jargon. Can someone 'explain like I'm 5' on how to make it so that it searches Python 3.6 instead of python 2.7? This is the error:
    ImportError at /
No module named bs4
Request Method:
GET
Request URL:
http://104.236.89.238/
Django Version:
1.8.7
Exception Type:
ImportError
Exception Value:
No module named bs4
Exception Location:
/usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93
Python Executable:
/usr/bin/python
Python Version:
2.7.12
Python Path:
['/home/django/django_project',
 '/home/django/django_project',
 '/usr/bin',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']
Server time:
Mon, 11 Dec 2017 20:58:02 +0000

I'm using WinSCP to transfer the files. Everything works perfectly on a local host before I transfer the files and try and run it on a server. Here are some settings on WinSCP. First here is my manage.py
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

my settings.py in WinSCP is:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}

I updated python 2.7 with the missing modules and I got different errors for missing modules. I'm unsure of where I need to make the change to 3.6. The error I'm getting now is 'Templates not found' which to me means that Django is installed to use 3.6 properly, but I'm not completely sure. Thanks so much fo your assistance!