text:
Q: Unity missing PostProcessing namespace in VS2019 Mac I'm trying to dynamically change PostProcessing component values but the namespace for UnityEngine.Rendering.PostProcessing won't be found!

I have:
..tried restarting everything
..installed & reinstalled the PostProcessing package (v3.1.1) via Package Manager
..tried using UnityEngine.Rendering & UnityEngine.Rendering.Universal
..successfully switch to URP
I can't find anything else to try. Anyone ever figured this one out?
Thank you!

A: I got it working! With help from 'Deleted'? Is that the handle or is that person gone?
In the Kart Microgame I just needed to add the Unity.Postprocessing.Runtime ASMDEF to the KartGame ASMDEF. Now my Kart scripts can see the Post Processing classes!
Thanks for the help!


text:
Q: Access denied to C:\Users\Public\Desktop I'm trying to install an application which installs several programs and tries to write their shortcuts to C:\Users\Public\Desktop
It fails, saying that the access is denied, and then doesn't install the programs.
When I try to open C:\Users\Public\Desktop with Explorer, I also get access denied, although my Windows account is an admin account.
I'm using Windows 8.1 64 bits. UAC is set to the minimum setting. Starting the installation program or Explorer as administrator didn't help.
The Desktop folder is set to read only, but if I try to remove that, I get access denied as well. In Properties / Security / Advanced / Permissions, I can only see "You do not have permission to view or edit this object's permission settings.".
Thanks

A: The problem is solved, but I'm still not sure what caused it.
I restarted the computer in safe mode to try to access that "Desktop" folder, and it was not there anymore! Instead, there was a "Public Desktop" folder, which I could access without issues.
I rebooted the PC in normal mode, and same thing: "Desktop" has been replaced by "Public Desktop".
So I tried to install Komplete again, and this time it worked without issues. The programs shortcuts were created inside "Public Desktop".

A: I was able to get around this installation roadblock (in Windows 10 Home) by using the built-in administrator account to take ownership of this folder (or C:\Users\Public\Public Desktop, which seems to be the same as C:\Users\Public\Desktop), and then granting myself (and my everyday user profile) full permissions.  Weird glitch.  The install programs should just let you skip creating these shortcuts if you don't need them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cloud Apps vs Web Apps I have 2 questions:
First, what's the difference between a web application and a cloud application? Are there any differences at all? If I'm developing a web application (a site with many interactive features), can I call it a cloud application?
Second, if there's a difference between a cloud and web application, what languages can cloud applications be developed in? Would a scripting language like PHP be useful for that?

Thanks.

UPDATE: I have watched the video in one of the answers, but I am still a little confused. Taking Google Docs as a example, all I see is a user interface that can be created with html and JS, along with a server script, and the data is stored in a database, which is basically the same thing a web application does. Or is it different?
Thanks

A: Web applications can run on "the cloud". The cloud is basically a collection of dynamic computational resources (cpu, ram, storage etc) that can be used by web applications.
This allows apps running on the cloud to scale well because they are allocated resources dynamically.
You can use public clouds such as Amazon's EC2 - or build your own private clouds.
A web app running on a cloud isn't exactly a "cloud app" - but the app is simply hosted on a cloud.
I find the first half of this video explains it very well (if a little annoying).
Also see this quesiton which has some good answers.

A: A web application is an just an application deployed on a web server.
The user accesses this application knowing that it is accessing a remote application and this application has a specific purpose.I.e. implements a specific functionality.
When you start talking about the cloud, you have a different concept alltogether.
The idea is that you want to access a service that you have no idea where the service actually is being deployed.
The main benefit is that a company can save resources.
For example a company can have e.g. their own CRM and have to pay money for servers, for IT personel etc. or just access a service in a "cloud" where the company providing the cloud is responsible for the servers etc.
So to answer your question, to build the cloud you use web applications as "modules" to provide the cloud.
But a web application by itself (separate of this context) can not be considered as cloud application (unless it runs as part of the cloud).

A: Anything that runs locally can run in a "cloud".  Cloud computing is the inevitable movement of traditional applications/processes to a dedicated provider.  Analogous to the Walmart syndrome, where little mom and pop shops have fallen by the wayside.
The difference between a cloud and web application is where it sits.

A: Web and cloud apps both are distributed applications having server and client parts. They store data on a server side, but can have local data cache for offline cases.
Web applications performed/run by browsers. Normally, they are written on HTMP/CSS/JavaScript. Adobe had another vision of client parts. They proposed special Flex language for Abobe Flash as client run-time environment (prior it has been killed this year).
Cloud apps are very similar to web apps, but their client parts are native applications specially developed to run on selected target platforms (OS X, Win, iOS, etc.)


text:
Q: Get  value from web page and authentication without asking user and password I have this video surveillance software on Windows that has it's brower remote access with user/password authentication, on PC's IP. (I can also view from remote since I have a public IP).
I check the code in the browser UI and want to take these span values (liveCameraCount and totalCameraCount):

I use the lime code, that is work but reply with:
None
None
ON

While it should be
2
2
ON

(I've also try with a time.sleep() to let the page load but without success)
from bs4 import BeautifulSoup
import urllib
import urllib2
import base64

url = "http://my.pc.ip.address:port"
username = "myuser"
password = "mypass"

handle = urllib2.Request(url)
authheader =  "Basic %s" % base64.encodestring('%s:%s' % (username,password))

data = urllib.urlopen(url)
soup = BeautifulSoup(data, "html.parser")

cameras = soup.findAll('span')
for span in cameras:
    print span.string

I'm also trying to login automatically without that it ask every time:
Enter username [for my.pc.ip.address:port]:------
Enter password for username at [for my.pc.ip.address:port]:-----

EDIT 1:
OK. that's strange.
If I press F12 I can see the value inside  as the image posted, but if I press CRTL + U i see this code (without value). I don't understand:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Sighthound</title>

  <link rel="stylesheet" href="/css/sighthound-desktop.css" />

  <link href="/img/apple-touch-icon-xlarge.png" rel="apple-touch-icon-    precomposed" sizes="144x144" type="image/png"/>

  <link href="/img/apple-touch-icon-large.png" rel="apple-touch-icon-precomposed" sizes="114x114" type="image/png"/>

  <link href="/img/apple-touch-icon-medium.png" rel="apple-touch-icon-precomposed" sizes="72x72" type="image/png"/>

  <link href="/img/apple-touch-icon-small.png" rel="apple-touch-icon-precomposed" type="image/png"/>

  <link href="/img/apple-touch-icon-small.png" rel="shortcut icon"/>

  <link href="/img/favicon.png" rel="shortcut icon" type="image/png"/>
  <link href="/img/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

                Cameras
                Clips

                Off
                On

                Cameras

                  /  ON

A: You could try swapping string for text as follows:
data = """
2
" / "
2
ON

"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(data, "html.parser")

for span in soup.findAll('span'):
    print span.text

This would display the following for your small example:
2
2
ON

For your full HTML, the first two s are empty, so empty strings will be printed.


text:
Q: boundary conditions of a diffusion-reaction system The central question is: Is my problem wrong or badly formulated?
Problem
I have to calculate the steady state concentration of a molecule $c$ given by the PDE
$0 = D\cdot\Delta_r c - a\cdot c$
The parameter $a$ describes the exponential decay of the molecule. For reasons of symmetry, the concentration only depends on the distance to the cell center (r).
The boundaries (in spherical coordinate system) of the system are given by:

*

*A cell at the center of the coordinate system and the cell surface at r = R and $c$ is consumed at the cell surface. The boundary condition for this is a Neumann BC with a constant flux $j$:
$\left.\frac{d}{dr}c \right|_{r=R} = \frac{j}{D}$

*The second boundary acts like an inexhaustible reservoir of molecules that is also not exhausted by the consumption on cell surfaces or by decay. For large distances from the cell center, the molecule concentration is constant:
$c(r\rightarrow\infty) + \left.\frac{d}{dr}c \right|_{r\rightarrow\infty} = c_\infty$.

Is there a solution for c(r) with the given boundary conditions?

What I've done so far...
The general solution of the PDE is given by:
$c(r) = \frac{k_1e^{\sqrt{a/D}\cdot r}}{r} + \frac{k_2e^{-\sqrt{a/D}\cdot r}}{r}$
and we have to set $k_1 = 0$ since $lim_{r\rightarrow \infty}c(r) = \infty$.
Thus I have still both boundary conditions to determine $k_2$. Using the first boundary condition I determine $k_2$. The solution is given by
$c(r) = \frac{R^2 \cdot j}{D + R\sqrt{D\cdot a}} \frac{e^{-\sqrt{a/D}\cdot (r - R)}}{r}$
$c(r)$ is completely determined but  $lim_{r\rightarrow \infty}c(r) = 0$ and does not satisfy 2. boundary condition.
Where is the problem???
Alternative Approach
From the ODE
$\dot{c} = 0 = A - a\cdot c$
with the constant influx $A$ I know that I need a influx to obtain a steady state of c, which is non-zero. Thus I modified the PDE to
$0 = D\cdot\Delta_r c - a\cdot c + A$
With this additional influx, the resulting solution is given by
$c(r) = \frac{R^2 \cdot j}{D + R\sqrt{D\cdot a}} \frac{e^{-\sqrt{a/D}\cdot (r - R)}}{r} + \frac{A}{a}$
and the term $\frac{A}{a} = c_\infty$ causes the match with the second boundary condition. BUT now there is a constant influx $A$ of molecules everywhere in the system that does not exist in the formulation of my problem.


text:
Q: Bash: find directory group owner I am sure this is easy but i cant find it.
I am writing a bash script where i want to add a known user to a group.
The group name is determined by the directory, which is sent through as a variable to that bash script.
so:
DIR="whatever"
GROUP=DIR groupname
usermod -a -G $GROUP userx

A: stat -c %g <file> (Linux)
stat -f %g <file> (BSD)
Will return the group ID for the given <file>
EDIT:
stat -c %G <file> (Linux)
stat -f %Sg <file> (BSD)
Will return the group name.

A: This is admittedly way more convoluted, but has the benefit of being more cross-platform friendly:
User:
\ls -l "$(dirname $TARGET_FILE)" | grep -v '^l' | grep " $(basename $TARGET_FILE)\$" | awk '{ print $3 }'
Group:
\ls -l "$(dirname $TARGET_FILE)" | grep -v '^l' | grep " $(basename $TARGET_FILE)\$" | awk '{ print $4 }'
Breaking it down:

*

*Use \ls. The backslash avoids any shell aliases that might set default options like -F.

*Build a -long format listing of the parent dir for $TARGET_FILE.

*grep -v '^l' removes any symlinks that might point to $TARGET_FILE from the listing and passes on the rest.

*Next narrow down the results to the single line from ls that ends in the basename of $TARGET_FILE. The leading ' ' (space) and trailing \$ are important to match the entire basename. (Otherwise old_file, file_new and file might all come up.)

*Finally, pass the single ls -l row for the target file to awk, and grab the 3rd (or 4th) space-separated item as the user (or group) name.

Note that this implementation has trouble with relative directories. (Don't try to run it where TARGET_FILE=../ for example.) I'm sure it could be hardened some more using realpath, but that's not available on OS X, so we're back to platform-specific tools if we use that.


text:
Q: Attempt to set column to two different values and cause InvalidStateException in OneToOne mapping I have a table ConfigManagementSettings and foreign to table DeviceGroup as below:
@Entity
@Table(name = "device_group")
public class DeviceGroup extends devicemanage.repository.base.entity.base.EntityBase implements Serializable
{
    private static final long   serialVersionUID    = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long            id;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_time", nullable = false)
    private Calendar        createTime;
    @Column(name = "domain_id", nullable = false)
    private int             domainId;
    @Column(nullable = false)
    private String          name;
    private String          remark;
    @Column(nullable = false)
    private Integer         type;
    @Version
    private Integer         version;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "deviceGroupParent", fetch = FetchType.LAZY)
    private ConfigManagementSettings    configManagementCollection;

}

@Entity
@Table(name = "config_management_settings")
public class ConfigManagementSettings extends EntityBase implements Serializable
{
    private static final long               serialVersionUID    = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long                            id;
    @Version
    private Integer                         version;
    @Column(name = "group_id", nullable = false, unique = true)
    private Long                            groupId;
    private byte[]  settings;
    @Column(name = "sequential_order", nullable = false)
    private Integer                         sequentialOrder;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "group_id")
    private DeviceGroup                     deviceGroupParent;

    @Transient
    private int                             order;
}

When I doing a simply unit test as below
    @Test
    public void testConfigManagementSettings() throws Exception
    {
        ConfigManagementSettings config = new ConfigManagementSettings();
        config.setGroupId(3L);
        config.setSequentialOrder(1);
        configManagementSettingsDao.save(config);
    }

I got InvalidStateException as below
Caused by: <openjpa-2.2.2-r422266:1468616 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back.  See the nested exceptions for details on the errors that occurred.
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2347)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2184)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2082)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2000)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1524)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:933)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:570)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:515)
... 45 more
Caused by: <openjpa-2.2.2-r422266:1468616 fatal user error> org.apache.openjpa.persistence.InvalidStateException: Attempt to set column "config_management_settings.group_id" to two different values: (null)"null", (class java.lang.Long)"3" This can occur when you fail to set both sides of a two-sided relation between objects, or when you map different fields to the same column, but you do not keep the values of these fields in synch.
    at org.apache.openjpa.jdbc.sql.PrimaryRow.setObject(PrimaryRow.java:344)
    at org.apache.openjpa.jdbc.sql.RowImpl.setObject(RowImpl.java:510)
    at org.apache.openjpa.jdbc.meta.strats.HandlerStrategies.set(HandlerStrategies.java:158)
    at org.apache.openjpa.jdbc.meta.strats.HandlerStrategies.set(HandlerStrategies.java:109)
    at org.apache.openjpa.jdbc.meta.strats.HandlerFieldStrategy.insert(HandlerFieldStrategy.java:130)
    at org.apache.openjpa.jdbc.meta.FieldMapping.insert(FieldMapping.java:623)
    at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.insert(AbstractUpdateManager.java:239)
    at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:166)
    at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:97)
    at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:78)
    at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:732)
    at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
    ... 53 more

However, I also have another two tables Subtask and SubtaskResult as below:
@Entity
@Table(name = "subtask")
public class Subtask extends devicemanage.repository.base.entity.base.EntityBase implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long        id;
    @Column(name = "domain_id", nullable = false)
    private Integer     domainId;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "finish_time")
    private Calendar    finishTime;
    @Column(nullable = false)
    private Integer     state;
    @Column(name = "task_id", nullable = false)
    private Long        taskId;
    @Column(name = "task_type", nullable = false, length = 1)
    private String      taskType;
    @Column(length = 256)
    private String      remark;
    // @Version
    private Integer     version;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "subtaskParent", fetch = FetchType.LAZY)
    private SubtaskResult resultOfSubtask;
}

@Entity
@Table(name = "subtask_result")
public class SubtaskResult extends EntityBase implements Serializable
{
    private static final long   serialVersionUID    = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long                id;
    @Version
    private Integer             version;
    @Column(name = "subtask_id", unique=true, nullable = false)
    private Long                subtaskId;
    private String              results;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "subtask_id")
    private Subtask             subtaskParent;
}

And also a simply unit test I did as below
@Test
public void testSubtaskResult() throws Exception
{
    SubtaskResult subtaskResult = new SubtaskResult();
    subtaskResult.setSubtaskId(33L);
    subtaskResult.setResults("test");
    subtaskResultDao.save(subtaskResult);
}

It works fine and successfully to persists the entity.
Is there something I have missing? Why these two cases have different behavior?
Any help is appreciated.


text:
Q: JSON::ParserError: 743: unexpected token in ROR I am getting this error when try to parse the response from rest_client.
JSON::ParserError: 743: unexpected token at '{
require 'rest_client'
require 'json'

class Kele
    attr_accessor :data
    def initialize(u,p)
        #@values = {email: u, password: p}
        @values = '{"email": "antblessing@gmail.com", "password": "password"}'
        @headers = {:content_type => 'application/json'}
        @data = self.post
    end

    def post
        response = RestClient.post 'https://private-anon-8506c5665f-blocapi.apiary-mock.com/api/v1/sessions', @values, @headers
    end
end

In Ruby irb,
 r = b.post
=> <RestClient::Response 200 "{\n    \"auth...">

 JSON.parse(r.body)
=> JSON::ParserError: 743: unexpected token at '{

a = Kele.new(1,2)
=> #<Kele:0x000000042e2e18 @values="{\"email\": \"antblessing@gmail.com\", \"password\": \"password\"}", @headers={:content_type=>"application/json"}, @data=<RestClient::Response 200 "{\n    \"auth...">>

 a.post.body
 => "{\n    \"auth_token\":\"eyJ0eXAiOiJKV1QiLCJhhGciOiJIUzI1NiJ9.eyJhcGlfa2V5IjoiYTc2MDZkNTBhYjA3NDE4ZWE4ZmU5NzliY2YxNTM1ZjAiLCJ1c2VyX2lkIjoyMzAzMTExLCJuYW1lIjoiQmVuIE5lZWx5In0.3VXD-FxOoxaGXHu6vmL8g191bl5F_oKe9qj8Khmp9F0\",\n    \"user\":\n        {\n            \"id\":2307245,\n            \"email:\"antblessing@gmail.com\",\n            \"created_at\":\"2015-08-11T16:31:08.836-07:00\",\n            \"updated_at\":\"2015-11-04T13:13:32.457-08:00\",\n            \"facebook_id\":null,\n            ...,\n            \"gender\":null\n        }\n}"

I tried this using HTTParty as well:
require 'HTTParty'
class Kele
    include HTTParty
    def initialize(email,password)
        @options = {query: {email: email, password: password}}
    end

    def post
        self.class.post('https://private-anon-8506c5665f-blocapi.apiary-mock.com/api/v1/sessions', @options)
    end
end

I still get this error:
 JSON.parse(a.post.body)
=> JSON::ParserError: 743: unexpected token at '{

A: In your second example, r is not JSON, it is a RestClient::Response object and cannot be parsed. You need to parse the r.body of the RestClient::Response, as you referenced it with a.post.body in your second example.
r = b.post         # => <RestClient::Response 200 "{\n    \"auth...">
JSON.parse(r)      # => JSON::ParserError: ...
r.body             # => "Some valid JSON string"
JSON.parse(r.body) # => Parses "Some valid JSON string"

A: I am not sure every case of error 743 from JSON is the same, but in my case is caused by the API endpoint. It was slightly different than the one I suppose to use.
So, I would check on your API endpoint URL first if you get this error, and make sure you are using the correct one.
In this case,
I should be using https://www.bloc.io/api/v1/sessions


text:
Q: Retrieve ID of instance, like Eclipse's debugger does Eclipse has a convenient feature when you're paused in the debugger that shows an ID for every instance.  They appear to be sequential and based on when an instance was allocated:

I find these extremely useful when I'm digging into a substantial problem, as they're usually small integers that are a lot easier to remember than the full hash codes, or some other internal ID.  They're a very quick check for "is this still the object I think it is?" when you're stepping through complex and deep callstacks.
Are these allocation IDs tracked by the jvm itself, or are they something Eclipse is providing through some unknown mechanism?
Is there any way to get at them from code, so that I can temporarily put them in log messages while debugging?
I don't really want to add an ID field to every object, there's many good reasons why that is a Bad Idea.

A:
Are these allocation IDs tracked by the jvm itself, or are they
something Eclipse is providing through some unknown mechanism?

Object IDs are generated by JDWP agent. JDWP agent is a library that exposes JVM debugging capabilities to external Java debuggers (like Eclipse IDE) through the JDWP protocol.
The agent is typically started with the JVM by the command line option -agentlib:jdwp= or -Xrunjdwp.

They appear to be sequential and based on when an instance was
allocated

IDs are generated on demand when the agent needs to send an object reference to the debugger. They are not related to object creation time or something. Java objects initially have no assigned IDs.

Is there any way to get at them from code

As I said above, object IDs do not exist until the agent exchanges object references with the debugger.
But you may generate your own IDs for objects using IdentityHashMap or similar. Here is a simplest way to create such IDs:
private static final Map<Object, Long> map = new IdentityHashMap<>();

private static long nextId;

public static long getId(Object o) {
    synchronized (map) {
        Long id = map.get(o);
        if (id == null) {
            map.put(o, id = ++nextId);
        }
        return id;
    }
}

Of course, this implementation is not perfect, since it uses a global lock and stores objects forever. A better solution would be a kind of WeakIdentityConcurrentMap.
In fact, this is exactly how JDWP agent generates object IDs. It keeps an internal hash table that maps an object to a sequentially inceremented integer, and uses reference counting for removal. See commonRef.c


text:
Q: Setting focus to an input after changing display to "block" I cant find the answer to this within a search.
Using javascript I have a div (ac) with an onclick event part of which is to set focus to an input element (gn) within a previously hidden div (as).
I would expect this to work:
ac.onmousedown = function () {
    csect.style.display = "none";
    as.style.display = "block";
    gn.focus();
}

but didn't, so I added small delay
ac.onmousedown = function () {
    csect.style.display = "none";
    as.style.display = "block";
    setTimeout(function(){
        gn.focus()
        },30);
}

which made it work.
Is this delay really necessary? Have I missed something?
Thanks for any help.

A: The default action of the click (setting the focus to the thing you clicked on) takes place after the mousedown event handler has fired. This means that the JavaScript sets the focus to gn and then the normal behaviour of clicking on ac sets the focus to ac.
See this example for a demonstration.
Use a click event instead of a mousedown event.


text:
Q: Error connecting to Teradata by Python via teradatasql module || ( failed to follow the required security policy) I am trying to connect to Teradata DB via python using teradatasql module. Below is my code which is simple one.

    import teradatasql
    import pandas as pd

    query="select * from DBC.tablesv sample 10"

    with teradatasql.connect(host='<host ip>', user='<username>', password='<password for user>') as connect:
        df = pd.read_sql(query, connect)

    print(df.head())

But I am getting error message on execution like below. I am a beginner to database programming. Any help from experts will be deeply appreciated.
----------------------------------------------------------------

    Traceback (most recent call last):
      File "/data/home/uk393e/anaconda3-5.2.0/lib/python3.6/site-packages/pandas/io/sql.py", line 1400, in execute
        cur.execute(*args)
      File "/data/home/uk393e/anaconda3-5.2.0/lib/python3.6/site-packages/teradatasql/__init__.py", line 649, in execute
        self.executemany (sOperation, None, ignoreErrors)
      File "/data/home/uk393e/anaconda3-5.2.0/lib/python3.6/site-packages/teradatasql/__init__.py", line 896, in executemany
        raise OperationalError (sErr)
    teradatasql.OperationalError: [Version 17.0.0.2] [Session 91835188] [Teradata Database] [Error 8056] A message was received that failed to follow the required security policy
     at gosqldriver/teradatasql.(*teradataConnection).formatDatabaseError TeradataConnection.go:1138
     at gosqldriver/teradatasql.(*teradataConnection).makeChainedDatabaseError TeradataConnection.go:1154
     at gosqldriver/teradatasql.(*teradataConnection).processErrorParcel TeradataConnection.go:1217
     at gosqldriver/teradatasql.(*TeradataRows).processResponseBundle TeradataRows.go:1716
     at gosqldriver/teradatasql.(*TeradataRows).executeSQLRequest TeradataRows.go:552
     at gosqldriver/teradatasql.newTeradataRows TeradataRows.go:418
     at gosqldriver/teradatasql.(*teradataStatement).QueryContext TeradataStatement.go:122
     at gosqldriver/teradatasql.(*teradataConnection).QueryContext TeradataConnection.go:2083
     at database/sql.ctxDriverQuery ctxutil.go:48

|
|
|
  File "/data/home/uk393e/anaconda3-5.2.0/lib/python3.6/site-packages/teradatasql/__init__.py", line 896, in executemany
    raise OperationalError (sErr)
pandas.io.sql.DatabaseError: Execution failed on sql: select * from DBC.tablesv
[Version 17.0.0.2] [Session 91835188] [Teradata Database] [Error 8056] A message was received that failed to follow the required security policy
 at gosqldriver/teradatasql.(*teradataConnection).formatDatabaseError TeradataConnection.go:1138
 at gosqldriver/teradatasql.(*teradataConnection).makeChainedDatabaseError TeradataConnection.go:1154
 at gosqldriver/teradatasql.(*teradataConnection).processErrorParcel TeradataConnection.go:1217
 at gosqldriver/teradatasql.(*TeradataRows).processResponseBundle TeradataRows.go:1716
 at gosqldriver/teradatasql.(*TeradataRows).executeSQLRequest TeradataRows.go:552
 at gosqldriver/teradatasql.newTeradataRows TeradataRows.go:418
 at gosqldriver/teradatasql.(*teradataStatement).QueryContext TeradataStatement.go:122
 at gosqldriver/teradatasql.(*teradataConnection).QueryContext TeradataConnection.go:2083
 at database/sql.ctxDriverQuery ctxutil.go:48
 at database/sql.(*DB).queryDC.func1 sql.go:1464
 at database/sql.withLock sql.go:3032
 at database/sql.(*DB).queryDC sql.go:1459
 at database/sql.(*Conn).QueryContext sql.go:1701
 at main.goCreateRows goside.go:652
 at main._cgoexpwrap_212fad278f55_goCreateRows _cgo_gotypes.go:357
 at runtime.call64 asm_amd64.s:574
 at runtime.cgocallbackg1 cgocall.go:316
 at runtime.cgocallbackg cgocall.go:194
 at runtime.cgocallback_gofunc asm_amd64.s:826
 at runtime.goexit asm_amd64.s:2361
unable to rollback
------------------------------------------------------------

A: As noted in the "Limitations" section of the documentation, the teradatasql driver does not yet automatically recognize centrally enforced encryption. You will need to explicitly add the encryptdata="true" parameter when invoking the connect method.


text:
Q: Maximum value of the loot, Knapsack problem Problem Introduction
A thief finds much more loot than his bag can fit. Help him to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag.
Problem Description
Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
Input Format. The first line of the input contains the number  of items and the capacity  of a knapsack. The next  lines define the values and weights of the items. The -th line contains integers  and —the value and the weight of -th item, respectively.
Constraints. 1 ≤  ≤ 10^3, 0 ≤  ≤ 2 · 10^6; 0 ≤  ≤ 2 · 10^6, 0 <  ≤ 2 · 10^6 for all 1 ≤  ≤ . All the numbers are integers.
MY CODE:
import sys
import unittest

def get_optimal_value( tot_capacity, weights_kg, values_money):
    amount = 0.
    value_per_item = [float(v) / float(w) for v, w in zip(values_money, weights_kg)]
    value_per_item.sort(reverse = True)
    print(value_per_item)
    for i in range(len(values_money)):
        if tot_capacity == 0:
            return amount
            break
        add_capacity = min(tot_capacity, weights_kg[i])
        amount = amount + add_capacity * value_per_item
        weights_kg[i] = weights_kg[i] - add_capacity
        tot_capacity = tot_capacity - add_capacity
    return amount

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    item, tot_capacity = data[0:2]
    values_money = data[2:(2 * item + 2):2]
    weights_kg = data[3:(2 * item + 2):2]
    opt_value = get_optimal_value(tot_capacity, weights_kg, values_money)
    print("{:.10f}".format(opt_value))

I am getting "Process finished with exit code -1" as an error. please help me in correcting this code


text:
Q: Change sass variable depending on a body class Let's say I have an existing code base using sass variables i.e.
$sw-primary-1: #ccc;
and these classes are used all over the place i.e.
.lifecycle {
    &.new {
      background-color: $sw-primary-1:
    }
  }
}

Is there anything I can do a large existing code base like this where I know want to change this colour palette variables depending on a different class on the body.
i.e. body class="redesign"
where I basically want to go
.redesign {
  $sw-primary-1: blue;
}

But the above doesn't work it still sticks with the original sass variable color.

A: It works.
Note that you should use the !global flag as well.

All variable assignments not at the top level of the document are now local by default. If there's a global variable with the same name, it won't be overwritten unless the !global flag is used. For example, $var: value !global will assign to $var globally. This behavior can be detected using feature-exists(global-variable-shadowing).

Source
$primary-color: blue;

.foo {
  color: $primary-color;
}

.bar {
  $primary-color: red !global;
  color: $primary-color;
}

A: Another way to accomplish this is using mixins.
@mixin bkcolor($color) {
    background-color:$color;
}

.lifecycle {
    &.new {
      @include bkcolor('blue');
    }
  }
}


text:
Q: Running Python script in Excel I would like to run Python script by clicking button in my Excel spreadsheet (by assigning macro to the button). I was trying to that this way like below but Python is running for a less than second and nothing happens... Is there any way to insist on script to wait until it will be finished? Thank you in advance.
Sub Script_Launcher()
    Dim objShell As Object
    Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("WScript.Shell")

    PythonExe = """<path to Python>"""

    PythonScript = "<path to my script>"

    objShell.Run PythonExe & PythonScript
End Sub

This is my Python script to download specific attachments from Outlook, add new column at the beginning and save under specific folder.
import win32com.client
import os
import datetime as dt
import pandas as pd

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

print (dt.datetime.now())

# setup range for outlook to search emails (so we don't go through the entire inbox)
lastWeekDateTime = dt.datetime.now() - dt.timedelta(days = 1)
lastWeekDateTime = lastWeekDateTime.strftime('%m/%d/%Y %H:%M %p')

# Select main Inbox
inbox = outlook.GetDefaultFolder(6)

# Optional:  Select main Inbox, look in subfolder "Test"
#inbox = outlook.GetDefaultFolder(6).Folders["Test"]

messages = inbox.Items

# Only search emails in the time range above:
messages = messages.Restrict("[ReceivedTime] >= '" + lastWeekDateTime +"'")

print ('Reading Inbox, including Inbox Subfolders...')

# Download a select attachment ---------------------------------------
# Create a folder to capture attachments.
folderInv = r'<Path for Inventory files>'
folderRes = r'<Path for Reservations files>'
#if not os.path.exists(Myfolder): os.makedirs(Myfolder)

try:
    for message in list(messages):
        try:
            s = message.sender
            s = str(s)

            for att in message.Attachments:
                if 'Inventory for Dashboard Refresh' in att.FileName:
                # Give each attachment a path and filename
                    print('Sender:' , message.sender)
                    outfile_name1 = folderInv + '\\'  + att.FileName
                    att.SaveASFile(outfile_name1)
                    df = pd.read_csv(outfile_name1)
                    df.insert(0, 'Date', dt.datetime.today().strftime('%Y-%m-%d'))
                    df.to_csv(outfile_name1, index=False)
                    print('Saved file:', outfile_name1)
                elif 'Reservations for Dashboard Refresh' in att.FileName:
                    print('Sender:' , message.sender)
                    outfile_name1 = folderRes + '\\' + att.FileName
                    att.SaveASFile(outfile_name1)
                    df = pd.read_csv(outfile_name1)
                    df.insert(0, 'Date', dt.datetime.today().strftime('%Y-%m-%d'))
                    df.to_csv(outfile_name1, index=False)
                    print('Saved file:', outfile_name1)

        except Exception as e:
            print("type error: " + str(e))
            x=1

except Exception as e:
    print("type error: " + str(e))
    x=1


text:
Q: Generic error: Runtime compiler is not loaded, I am creating a directive in VSCode Editor which loads a html page on specifying a given path:
Below is the code for same:
@Directive({
 selector: 'html-outlet'
})

export class HtmlOutlet {
 @Input() html: string;

 constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {
}

ngOnChanges() {
const html = this.html;
if (!html) return;

@Component({
    selector: 'dynamic-comp',
    templateUrl: html
})
class DynamicHtmlComponent { };

@NgModule({
    imports: [CommonModule],
    declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule { }

this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then(factory => {
        const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
        const cmpRef = this.vcRef.createComponent(compFactory, 0);
    });}}

This code used to work perfectly fine untill i upgraded app to angular 6.
I am getting below error now :
Runtime compiler is not loaded Error stack trace: Error: Runtime compiler is not loaded
    at Le (main.00612d315fe86075b5fb.js:1)
    at t.compileModuleAndAllComponentsAsync
Can i get some help in this

A: If you are running the application in --prod mode it will default to AOT, which doesn't provide the compiler.
I don't think that the Angular team is encouraging the pattern of using the compiler at runtime at all.


text:
Q: Como obter todas as constantes de uma classe? Meu projeto tem uma classe helper com várias constantes que representam roles pré-definidas.
public static class RolesHelper
{
    public const string ModuloUsuarios = "Usuarios";
    public const string ModuloMenus = "Menus";
    public const string ModuloBanners = "Banners";
    public const string ModuloGaleriaFotos = "GaleriasFotos";
    public const string ModuloProgramacao = "Programacao";
    public const string ModuloMetaTags = "MetaTags";
    public const string ModuloNoticias = "Noticias";
    public const string ModuloPaginas = "Paginas";
}

No método Seed (método usado pelo Entity Framework para atualizar a base de dados), eu preciso fazer com que determinado usuário seja relacionado com estes valores.
Atualmente, existe um método AdicionarUsuarioARole() que faz o trabalho todo, e este método é chamado várias vezes, desta forma:
AdicionarUsuarioARole(user, RolesHelper.ModuloUsuarios);
AdicionarUsuarioARole(user, RolesHelper.ModuloMenus);
//E assim por diante

O que eu quero é obter todas as constantes públicas desta classe numa coleção, para fazer iterá-la e chamar o método AdicionarUsuarioARole() com cada valor desta coleção. Desta forma, não preciso me preocupar em atualizar o método Seed sempre que eu adicionar uma constante nesta classe.
Por exemplo:
var listaConstantes = RolesHelper.GetAllConstantValues();

foreach(var constVal in listaConstantes)
{
    AdicionarUsuarioARole(user, constVal);
}

A: Usando Linq fica bem simples:
var constantes = typeOf(RolesHelper).GetFields(BindingFlags.Public |
                                               BindingFlags.Static |
                                               BindingFlags.FlattenHierarchy)
                     .Where(fi => fi.IsLiteral && !fi.IsInitOnly)
                     .ToList();

A: // Lista todos os campos públicos e estáticos,
// tanto da classe quanto das classes-base

foreach (var prop in typeof(SuaClasse)
                     .GetFields(BindingFlags.Public |
                                BindingFlags.Static |
                                BindingFlags.FlattenHierarchy))
{
    // IsLiteral determina que o valor foi criado em tempo de compilação,
    //    e não pode ser alterado.
    // IsInitOnly determina que o valor pode ser alterado no corpo do
    //    construtor.
    if(prop.IsLiteral && !prop.IsInitOnly)
    {
        // Valor do campo
        var valor = prop.GetValue(null);
    }

}


text: Q: External monitor blank start-up + wake blank screen, must manually power on/off the monitor Laptop Precision 5560. When I start up Ubuntu, external monitor (HDMI using a USB-C dongle) is blank. I have to manually power on/off the monitor to wake it up. The laptop detects the external monitor as it is set as primary monitor (the top bar is not present on the laptop's screen and I can move the mouse over the external monitor's area). It seems like the laptop is not able to wake up the monitor...


text:
Q: Where should I close the sql.DB? According to the godoc:

It is rare to Close a DB, as the DB handle is meant to be long-lived
and shared between many goroutines.

Is there any use cases of this method except calling it defer db.Close() inside the main function?

A: I never close databases. Deferring it in main likely won't hurt... but it won't help anything either. The end of main is the end of the program and if main ends, the OS does the cleaning.

Edit:

So why we need it in public API of the database/sql package?

Closing a DB is useful if you don't plan to use the database again. It does all the cleanup that would be done at program termination but allows the program to continue to run.


text:
Q: Starting using Instagram oEmbed feature What is the correct way to start using Instagram oEmbed feature? Documentation (https://developers.facebook.com/docs/instagram/oembed/) claims that I have to pass App Review to start using the feature. And application form says Please provide a URL where we can test Oembed Read. Which I don't have because I have no access to the feature.
What I have tried with no success:
I requested instagram_oembed resource with:

*

*app token of application in live mode

*app token of application in
development mode

*passed URL to a post by official Instagram account
(e.g. https://www.instagram.com/p/CQG4gZxMzzO/)

*passed URL to a post
of a user who is Admin of the app

In all cases I receive (#10) To use 'Oembed Read', your use of this endpoint must be reviewed and approved by Facebook. To submit this 'Oembed Read' feature for review please read our documentation on reviewable features: https://developers.facebook.com/docs/apps/review.
Example of the request I do https://graph.facebook.com/v11.0/instagram_oembed?url=https%3A%2F%2Fwww.instagram.com%2Fp%2FCQG4gZxMzzO%2F&access_token=appAccessToken

A: We're also suffering from this issue, but so far, we thought we already figured out how to do that.
Big picture
Facebook had not sorted this thing out correctly. Or at least, we don't know why they put such a restriction to this API.
The official document is not correct. (or at least not accurate for now, for some part)
Which part was not correct?
The access token part is not right. Or at least, it's the most confusion part.
How can we resolve this?

*

*Use the Graph API Explorer

*Adjust your token(App token, Client access token, user token) with the official URLs(see below) to see if you can get the result

*

*most of us should be able to get the result with user access token, which means you have to access this API after login!

Integrate into your app for review

*

*The review page is also confusing:

*Please provide a URL where we can test Oembed Read. Include the URL of a page, post or video from our official Facebook or Instagram pages, or the pages themselves., it means you can only use links like https://www.facebook.com/instagram or https://www.facebook.com/facebook
With that in mind, so far, the only way to get approved is integrate your oembed usage into your normal UI with facebook user access token ready
Question to the big picture
So, we have to ask user to login with our facebook app, then we can provide this oembed read API returned embed HTML? I'm afraid that's what we have now.

*

*big companies might be able to apply for App Token, I guess in that scenario, facebook login is not necessary

*for small companies, indie developers, hmmm, I don't know any better solutions so far.

A: I have run into this too. I do not have an answer at this time, I just want to report on the frustrations of their 'app review' process. Which makes it feel like you are unlikely to get it to work any time soon.
We have a custom embed code for our weblog authors to use (a shortcode kind of thing) which does the oEmbed call. We just take the HTML from the resulting JSON, and insert it into the weblog article page, and that is it. It stopped working, presenting this same error - in live mode, and in development mode.
The kicker is, I then tried submitting it for app review. Filled out everything I could to the best of my knowledge. Provided them a test account and post on our weblog to show the shortcode editing and expected placement. We got rejected. Why? Your embedding resulted in an error, we can't see it in action to approve you.
Yes. The error I am getting is that I need my 'app' to be reviewed and approved.
This is an infuriating process. This is the only Facebook / Instagram API feature we use at this point. No user data. No attempt to make an Instagram clone app or anything like that. Just an embed.
And they are making this simple use case as impossible to use as they can. And the documentation also feels like an infinite loop. They say users of the old Instagram embed call have until September 7 2021 to get approved. But the call does not work at all because we are not approved. So we cannot get approved.

A: Same loop here. I've managed to report it to Facebook team and get answer "Just submit your Instagram post URL"! I can't believe it, its can't be so simple. I've confirmed it few times with Facebook team person and.... get rejected!
Also, second form in App Review process will LOWERCASE all of your links and I've spent few days just to explain it to reviewers and support person. Still rejected after submitting proper url. This is insane.
My another attempt was about to build a test page where I can auth via Facebook account, parse connected Instagram accounts and GET embed endpoint with user access key in hope that reviewer HAS access to oembed feature - REJECTED. I can't even find what permission I need to add to auth URL to obtain oembed thing.
Will update my answer with new information later.
UPDATE: After reporting about the issue with lowercase URL in submission form they just APPROVED my app without APP REVIEW. Well... Facebook style...

A: I had exactly the same problem recently. Updated the packages with compose, changed the API version from 10 to 11... without any change.
The error was also occurring in development mode, it didn't make sense that Facebook was asking to approve in dev mode.
For me, the problem came from the management of scopes in my application, depending on the version of the Facebook API used.
My advice: check the scopes defined with API version in your code first.

A: I had the same issue and the solution is very simple. The only thing you need to do is copy paste an instagram url in the input field saying: Please provide a URL where we can test Oembed Read.
I did the this link: https://www.instagram.com/p/G/
Which is actually the first instagram post :) Got approved. Hope this helps everybody!


text:
Q: Push notifications iOS - prompt app to check resource and provide local notification if appropriate I am looking into creating an iOS app in Swift along with a remote service that notifies users when an update to an RSS feed occurs only when the update meets certain criteria. A user story would be as follows:

*

*User installs app and decides to be updated when a feed update includes certain words (for example in the title). This relates to a specific 3rd party feed, the address of which is stored in the app.

*When the 3rd party RSS feed is updated, if the title matches the condition previously selected by the user, a notification is made to the user.

I'm trying to work out whether I need a server with a script to monitor the feed and to send updates to the user, however it will send all updates, the phone would then need to check the update and only notify the user if it matched their conditions.
Or, is it better to have the app run periodic background checks against the feed so it can check itself if the update warrants a local notification? This would need to be able to run when the app is completely closed.
Any thoughts?

A: An app can only decide to notify the user about an incoming notification if the app is currently in use by the user.  If closed or in the background, the notification is going to come through to the device and register.  If you need to filter which notifications get pushed, you need a backend server process to do the filtering and push out only the applicable notices.
We did a system where the user was able to set search criteria for animals they would be interested in adopting.  That was stored in the database.  A service on the database server ran every 30 minutes and queried the various search criteria for each person and pushed out a notification to that user if a new pet was found matching their criteria.  Once a notification had been sent for that pet for that user, a flag was set that would prevent the user getting another notification about the same pet 30 minutes later... there are a lot of use cases to consider!!


text:
Q: FB Comment 'Also Post on Facebook' and FB Share - Linkback to different URLs? This is SO annoying.
The Issue is a matter of two scenarios behaving differently when I expect (and wish) them to be the same, these relate to the same webpage/article which features both Facebook Comment widget and a Share icon.
It's important to mention that the webpage is a Wordpress article, and we redirect:

*

*from www.example.com/wordpress/articles/news/thearticle

*to www.example.com/news/thearticle

The issue explained:
Scenario 1) I visit the article and type a facebook comment, I also click 'Also Post on Facebook'. When I view may facebook wall and see the share with the comment I just made, the link is linking back to the wordpress URL - I do not want this.
Scenario 2) I visit the article and share it through the Share icon. On my wall this time the linkback URL is the short one - this is good.
Important info regarding debugging
My OG URL tag is correct:
<meta property="og:url" content="http://www.example.com/news/thearticle"/>

*

*Facebook debugger is picking up the correct desired URL as above,
also listing the desired Fetched URL and Canonical URL. All seems to
be what I want it to be.

*This is true regardless of whether or not I
scrape the URL before or after I try this procedure.

*Even if I then go back and do another comment with 'also post on FB' after doing a scrape with FB debugger, still the share links to the wrong/long format/original URL.

*However, if I at any point share via the share icon, not the comment-share, the desired URL is present as per the OG URL.

*If I do a comment-share, then an icon-share, then another comment-share, the comment share ones still have the wrong URL even though the icon-share had the correct one!

Any ideas? Thanks so much in advance to anyone who can help :)

A: It seems that the Comments FB plugin doesn't get the page info from OpenGraph, but expect a data-href attribute, or if not provided will use the current url by default.
From the doc:

data-href
Description : The absolute URL that comments posted in the plugin will be permanently associated with. Stories on Facebook about comments posted in the plugin will link to this URL.
Default : Current URL.

So what you need to do is to provide the valid URL as an HTML5 attribute on your plugin wrapper:


text:
Q: SQL Server 2005 using case in order by My table looks like this AFTER UNION
St
----
FUT
80CE
79CE
81PE
79PE

I need
St
----
FUT
79CE
80CE
81PE
79PE

Using this:
order by
   case St
      when 'FUT' then 1 else 2 end ,
   case
      when St like '%PE' then St end,
   case
      when St like '%CE' then St  end

I get this:
St
----
FUT
79CE
80CE
79PE
81PE

A: Try this:
order by case St
when 'FUT' then 1 else 2 end ,
case when St like '%CE' then 1 else 2 end ,
case when St like '%PE' then St end DESC,
case when St like '%CE' then St  end

A: Well, you could use ROW_NUMBER() to order the data in a common table expression, that would allow you to easily use the row number in the ordering CASE;
WITH unionresult AS (
  <original query here>
), cte AS (
  SELECT *, ROW_NUMBER() OVER (ORDER BY st) rn
  FROM unionresult
)
SELECT st FROM cte
ORDER BY
  CASE WHEN st = 'FUT' THEN 1 ELSE 2 END,
  CASE WHEN St LIKE '%PE' THEN -rn END,
  CASE WHEN St LIKE '%CE' THEN  rn END

A simple SQLfiddle to test with.

A: Try like  this
select st,case when id like '%PE' then 2 else 1
end "ord" from (
select * from t order by case st
when 'FUT' then 1 else 2 end ,
case when st like '%PE' then stend desc,
case when st like '%CE' then st end) as a order by
ord,case st
when 'FUT' then 1 else 2 end


text:
Q: Vaadin Chart- Hide the legend How can I hide the legend in the Vaadin Charts.
I tried commenting the legend defined in the program
    Legend legend = new Legend();
    legend.setLayout(LayoutDirection.VERTICAL);
    legend.setBackgroundColor(new SolidColor("#FFFFFF"));
    legend.setVerticalAlign(VerticalAlign.BOTTOM);
    legend.setShadow(true);
    conf.setLegend(legend);

After commenting this, only a colour button remains on the graph.

A: configuration.getLegend().setEnabled(false);


text:
Q: Does any odd prime number belong to at least one set of a minimum of $3$ prime numbers, that are separated from each other by the same gap? I have tried searching for the following and I mostly got results dealing with: the rarity of different gaps, twin gaps, cousin gaps...
As a self learner, there is a chance that I didn't know of a better way to search, So if this is a duplicate please close and refer me to it.
I doubt that there is any proof, but I would deeply appreciate any references or any heuristics or any counter example.
The question is quite simple:
Does any odd prime number belong to at least one set of a minimum of $3$ primes numbers, that are separated from each other by the same gap?
*Note: The prime numbers themselves aren't necessarily consecutive in nature.
I am aware that within large prime numbers there are different behaviors, but there are also many more options.
Here are some basic examples:
$3 , 5 , 7$  gap: $2$
$5 , 11  , 17 , 23, 29$ gap: $6$
$7 , 13 , 19$ gap: $6$
$19 , 31 , 43$ gap: $12$
$23 , 41 , 59$  gap: $18$
$23 , 47 , 71$ gap: $40$
$3 , 53 , 103$. gap: $50$
$79 , 109, 139$ gap: $30$
...


text:
Q: Magento Facebook Pixel Tracking Code I am trying to add Facebook Pixel tracking to a Magento site. Specifically I want to track the click of add to cart, the click on add to wishlist and also the success page. I am using the below code in my head.phtml file. However my Chrome browser Facebook Pixel Helper extension says "Facebook Pixel did not load". I am wondering if anyone can help identify the error in my below code.

<?php if((strpos($_SERVER['REQUEST_URI'],'success')==true)):
  $orderObj = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
?>

<img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/offsite_event.php?id=xxxxx&value=<?php echo number_format($orderObj->getBaseGrandTotal(),2) ?>&currency=<?php echo     $orderObj->getOrderCurrencyCode()?>" [^] />
<?php
endif;
if($this->getRequest()->getControllerName()=='product')
 {
   $asku = Mage::registry('current_product')->getSku();
   $pname = Mage::registry('current_product')->getName();
   $pprice = number_format(Mage::registry('current_product')->getPrice(),2);
?>

<?php
  }else{
?>

<?php
  }
?>


text:
Q: Date on x axis iphone using core plot I want to show data on x-axis on CPXYPlotSpace. I have seen doing so on mac using something like that but it does not work on iphone so any suggestion or i have to do it manually.
 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;

A: Don't forget to set intervalLength
    NSTimeInterval oneDay = 24 * 60 * 60;
x.majorIntervalLength = CPDecimalFromFloat(oneDay);
y.orthogonalCoordinateDecimal = CPDecimalFromFloat(oneDay);


text:
Q: Tips to solve this integral $\int_{-\infty}^{\infty} \frac{e^{-\alpha x^2}}{(x^2+c^2)(\sqrt{x^2+u^2})} dx$ $$\int_{-\infty}^{\infty} \frac{e^{-\alpha x^2}}{(x^2+c^2)(\sqrt{x^2+u^2})} dx$$
I tried to do it like this:
$$\int_{-\infty}^{\infty} \frac{e^{-\alpha x^2}}{(x^2+c^2)(\sqrt{x^2+u^2})} dx=\int_{-\infty}^{\infty} \frac{e^{-\alpha x^2}\sqrt{x^2+u^2}}{(x^2+c^2)(x^2+u^2)} dx$$ but
$$\frac{1}{x^2+c^2}=\int_{0}^{\infty}e^{-k(x^2+c^2)} dk $$ and
$$\frac{1}{x^2+u^2}=\int_{0}^{\infty}e^{-k'(x^2+u^2)} dk' $$ so
$$\int_{-\infty}^{\infty} \frac{e^{-\alpha x^2}}{(x^2+c^2)(\sqrt{x^2+u^2})} dx= \int_{-\infty}^{\infty} e^{-(\alpha+k+k')x^2}\sqrt{x^2+u^2}dx\int_{0}^{\infty} e^{-kc^2}dk...  $$
How to solve this first integral?


text:
Q: layout_width attribute android Im getting the error "you must supply a layout_width attribute android" any suggestions?  I thought it was the xmlns line in the first row but still nothing.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_parent"
    android:layout_height="wrap_parent"
    android:layout_gravity="center"
    android:columnCount="2"
    android:orientation="horizontal" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="4" />

</GridLayout>

A: use wrap_content instead of non-existent wrap_parent


text: Q: Delta Lake Table shows data in Glue but not in Athena I am writing data to S3 in delta format from Spark dataframe in Glue. When I read the same table back in a dataframe, I am able to see the data. I created a table in Athena pointing to this S3 location (using the CREATE EXTERNAL TABLE command and not Glue crawler). When I query the data in Athena, I get zero records. What am I missing?


text:
Q: Function to Send Email Notification to Author and Admin When Video is Uploaded I've been struggling; can anyone help please?
I need the Wordpress Templatic Video theme to send a copy of the email that is sent to users when they upload a new video, to admin as well.  Then admin will know to login and publish the video.
The theme should do this, but it doesn't.  So, I'm having a go
The theme URL is: http://www.wordpressdirectorytemplates.com/motaz/video
The function that sends an email when users upload a video is:
    /* send email of video post & update submit*/
    global $post;
    $post = get_post($last_postid);
    $author = $post->post_author;
    $name = get_the_author_meta( 'display_name', $author );
    $email = get_the_author_meta( 'user_email', $author );
    $title = $post->post_title;

    $to[] = sprintf( '%s <%s>', $name, $email );
    $subject = sprintf( 'Video Post: %s', $title );
    $message = '';

$message .= "
Dear $name
";
if(isset($_REQUEST['pid']) && $_REQUEST['pid']!="")
{
        $message .= '
'. __('Thank you for submitting your video at our site, your request has been updated successfully.','templatic').'
';
}else{
   /* if user set by default status publish than show different message */
        $theme_settings = get_option('video_theme_settings');
        if(isset($theme_settings['video_default_status']) && $theme_settings['video_default_status'] == 'publish'){
            $message .= '
'.__('The video will goes live on the site.','templatic').'
';
        }else{
            $message .= '
'.__('The video will require admin approval before it goes live on the site.','templatic').'
';
            $message .= '
'.__('You will get an email confirmation once your video has been published.','templatic').'
';
        }
}
    $message .= "
You can view your video on the following link
";
    $message .= ''.get_permalink($last_postid).'';
    $message .= "
Thank you
";

    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

    $fromEmail = get_option('admin_email');
    $fromEmailName = stripslashes(get_option('blogname'));

    wp_mail( $to, $subject, $message, $headers );

    wp_redirect(site_url().'/?page=success&pid='.$last_postid);
    exit;
}

}
I can get the email to go to admin instead of the user by adding:
    $multiple_recipients = array(
'info@example.com');

And, then putting $multiple_recipients at the start of:
    wp_mail($multiple_recipients , $to, $subject, $message, $headers );

But, this is plain wrong.  Admin does get an email, but the user doesn't get theirs.
I also tried adding a function to the child theme functions file using the WP Codex for help; but, this is incorrect too:
    function email_friends( $post_ID ) {
    $friends = 'info@example.com';
    wp_mail( $friends, "New Video Uploaded", 'A new video has been uploaded on http://nuntim.com');

    return $post_ID;

    }
    add_action( 'function video_posts_submition_success_msg_fn', 'email_friends' );

Can anyone point me in the right direction?

A: you did a wrong add action see the wiki here,
is the hook video_posts_submition_success_msg_fn exist?
if yes, you can add action with something like this
function email_friends( $post_ID ) {

    // may you can play with $post_ID here

    $friends = 'info@example.com';
    wp_mail( $friends, "New Video Uploaded", 'A new video has been uploaded on http://nuntim.com');

    // return $post_ID; // add_action doesn't have return
}
add_action( 'video_posts_submition_success_msg_fn', 'email_friends', 10, 1 );


text:
Q: Invert colors on underlying elements with CSS, Javascript, or SVG Basically, I want to make an empty div that I can put anywhere on the page, and it will invert the colors of everything behind it. Is this possible? (It shouldn't invert entire elements that are overlapped, only the part covered by the div)

A: You can implement it (or any other filter) using the backdrop-filter css property.

.overlay {
  /* The invert effect */
  -webkit-backdrop-filter: invert(100%);
  backdrop-filter: invert(100%);

  position: fixed;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 50px;
  border: solid 1px blue;
  transition: all 0.3s ease;
}
.overlay:hover {
  left: 100px;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dignissim elementum mattis. Pellentesque lacus velit, sollicitudin eget tincidunt et, dapibus a tortor. Vestibulum ultrices nisi ut turpis ultricies interdum. Proin pellentesque purus rutrum, pretium justo ac, scelerisque sem. Suspendisse potenti. Sed iaculis eu velit sed maximus. Phasellus vestibulum in tellus sit amet euismod. Donec id faucibus lectus. Aenean eu pretium risus, ut pharetra odio. Ut hendrerit molestie hendrerit. Morbi consectetur ultricies elit ut convallis. Quisque cursus odio id lacinia ultrices. Nulla eu ligula et mauris laoreet cursus sed nec orci. Donec eu vulputate leo, id scelerisque quam. Aenean dignissim placerat pharetra.

Vestibulum ac fringilla ipsum. Vivamus venenatis non sem sed hendrerit. Etiam mollis libero lorem. Nullam pharetra nulla vitae libero porttitor sollicitudin. Maecenas non sapien a tellus rutrum pellentesque ac non nisi. Aenean rhoncus et arcu ac suscipit. Mauris in nunc quis dolor aliquet pharetra. Nulla mi arcu, mollis ac ligula vel, vestibulum pretium massa. Quisque malesuada justo eu imperdiet lobortis. Mauris elit arcu, feugiat id vulputate quis, efficitur ut neque. In dignissim dignissim euismod. Suspendisse ac arcu ipsum. Cras dignissim justo risus, et blandit ligula egestas eu. Nunc massa purus, hendrerit quis lacinia non, luctus at erat.

Unfortunately this CSS property is not widely supported by browsers.

A: Maybe this is what you need: example
function start() {
    var canvas1 = document.getElementById("canvas");
    var ctx1 = canvas1.getContext("2d");
    var canvas2 = document.getElementById("over");
    var ctx2 = canvas2.getContext("2d");

    // Just put a colorfull random background to play with.
    randomFill( ctx1 );

    // Animation of the lens.
    var x = Math.random() * 100;
    var y = Math.random() * 100;
    var speed = .02;
    var vx = .03 + Math.random() * speed;
    var vy = .03 + Math.random() * speed;
    var lastTime = 0;

    function anim( time ) {
        window.requestAnimationFrame( anim );
        if (lastTime == 0) {
            lastTime = time;
        } else {
            var delay = time - lastTime;
            lastTime = time;
            x += delay * vx;
            y += delay * vy;
            if (x < 0) {
                x = 0;
                vx = -vx;
            }
            else if (x > 299) {
                x = 299;
                vx = -vx;
            }
            if (y < 0) {
                y = 0;
                vy = -vy;
            }
            else if (y > 299) {
                y = 299;
                vy = -vy;
            }
            canvas2.style.top = Math.floor(y) + "px";
            canvas2.style.left = Math.floor(x) + "px";
        }
        applyFilter( ctx1, ctx2, x, y );
    }
    window.requestAnimationFrame( anim );
}

function randomFill( ctx ) {
    var i, x, y, w, h;
    for (i = 0 ; i < 1000 ; i++) {
        x = Math.floor( Math.random() * 400 ) - 50;
        y = Math.floor( Math.random() * 400 ) - 50;
        w = Math.floor( Math.random() * 100 );
        h = Math.floor( Math.random() * 100 );
        ctx.fillStyle = 'rgb(' + Math.floor(Math.random()*256) + ","
            + Math.floor(Math.random()*256) + "," + Math.floor(Math.random()*256) + ')';
        ctx.fillRect( x, y, w, h );
    }
}

function applyFilter( ctx1, ctx2, x, y ) {
    var w = 100, h = 100;
    var img = ctx1.getImageData(x, y, w, h);
    var pixels = img.data;
    var k;
    for (k = 0 ; k < pixels.length ; k += 4) {
        pixels[k + 0] = 255 - pixels[k + 0];
        pixels[k + 1] = 255 - pixels[k + 1];
        pixels[k + 2] = 255 - pixels[k + 2];
    }
    ctx2.putImageData(img, 0, 0);
}

Take attention to the applyFilter function.

A: Or in straight SVG, you can invert the spectrum of a filtered area just using feComponentTransfer as in http://cs.sru.edu/~svg/Chapter05/G05xx16.svg

A: The easiest way is to use CSS3 property mix-blend-mode. It's just one line of code!
.invert-everything-behind {
  mix-blend-mode: exclusion;
}

See: https://css-tricks.com/almanac/properties/m/mix-blend-mode/


text:
Q: How do I get the ath9k driver of backports-3.12-8 installed on Xubuntu 13.10? I downloaded the 3.12-8 kernel files linux-headers-all.deb, linux-headers-generic_i368.deb; linux-image-generic_i386.deb from kernel.org and installed them via:
 dpkg -i *.deb

Now I'm trying to eliminate some wifi signal dropouts, which are probably caused by the driver itself. Apparently there have been some fixes to the ath9k driver, so I'd like to replace the default by a backports version.
I downloaded backports-3.12.8-1.tar.gz from kernel.org and tried to get the ath9k module ready by:
cd ~/.source/backports-3.12.8-1/
sudo apt-get install build-essential
sudo apt-get build-dep linux-image-$(uname -r)
sudo ln -s /usr/src/linux-headers-$(uname -r) /usr/src/linux
make defconfig-ath9k

This leaves me with following "missing-prototypes ERROR":
cc -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer   -c -o conf.o conf.c
cc -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer   -c -o zconf.tab.o zconf.tab.c
cc   conf.o zconf.tab.o   -o conf

But when I continue with:
sudo modprobe -r ath9k
sudo make
sudo checkinstall

everything works!!!
So my questions are:

*

*Does this module depend on certain other kernel modules?

Yes following command does tell you:
modinfo ath9k

*If so, where's information about that stuff?

Have a look at wireless.kernel.org/en/users/Drivers/ath9k.

*Is there a right way to install this kernel module resp. driver?

Probably by getting a pro in kernel compiling :-).

THX

A: For those who might stumble across this question, like I just did:

This leaves me with following "missing-prototypes ERROR":
cc -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer   -c -o conf.o conf.c
cc -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer   -c -o zconf.tab.o zconf.tab.c
cc   conf.o zconf.tab.o   -o conf

These lines aren't actually errors. The make command runs a bunch of other commands, as specified in a file called Makefile. By default, make will write out these commands to the terminal before running them. For example, if Makefile says to run foo then bar then baz, make will write foo to the terminal then run the foo command; then it will write bar to the terminal and run bar; then it will write baz to the terminal and run baz.
In this case, those cc lines are commands that make has been told to run by Makefile. The cc command will run the system's default C compiler, which is probably GCC. Those things beginning with - are options, which affect the behaviour of the C compiler.
For compilers like GCC, options beginning with -W tell the compiler to give out warnings when it sees code that's technically valid, but is often a bad idea (e.g. some pattern in the code which many programmers think will act in some way, but will actually act in another).
In this case -Wall turns on many (not quite all!) of GCC's warnings. -Wmissing-prototypes and -Wstrict-prototypes turn on extra warnings, to spot problems relating to C's function prototype feature.
Hence, these messages are really telling us that the cc command is about to be run, and that (among other things) it should warn us if it thinks the code is dodgy; in particular, if function prototypes are being misused.
GCC warnings look something like this:
main.c: In function 'main':
main.c:1:5: warning: traditional C rejects ISO C style function definitions [-Wtraditional]
 int main(int argc, char **argv) {
     ^

Since nothing like that appears in your output, no warnings or errors occurred; even with these extra -W checks enabled.

A: I would recommend installing a newer kernel although it should be working since correctly since 2.6.30 or a version like that. I'm using it as an AP in kernel 3.13.0-24-generic, even though i know it is better to install a new kernel. I was using it on http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.18.12-vivid/ or a similar one (till my HDD crashed). I can give you details of the one used in the mentioned kernel.

*

*depends:        ath9k_hw,mac80211,ath9k_common,cfg80211,ath

*I have seen the information and hardware capabilities somewhere, but I don't remember where it was

*It sure is :) Look for compat-wireless


text:
Q: Trivialize triangle inequality with linear algebra? I managed to prove the triangle inequality with linear algebra however I feel like there is some algebraic identity that trivializes this inequality.
Let $a=[a_1, a_2, ... a_n],b=[b_1, b_2, ... b_n]\ \epsilon\ \mathbb{R}^n$, then we have $$\sqrt{a_1^2+a_2^2...a_n^2}+\sqrt{a_1^2+a_2^2...a_n^2}\geq \sqrt{(a_1+b_1)^2+(a_2+b_2)^2...(a_n+b_n)^2}$$.
My solution is to simply square both sides and the rest can be simplified by cancellation and CS inequality. However, it looks like there is an identity (maybe Holder's?) that directly trivializes this problem. Is this true?

A: If you use Cauchy-Schwarz,
\begin{align}
\|a+b\|^2&=(a+b)^T(a+b)=a^Ta+b^Tb+2b^Ta\\[0.2cm]
&\leq a^Ta+b^Tb+2\|a\|\,\|b\|\\[0.2cm]
&=\|a\|^2+\|b\|^2+2\|a\|\,\|b\|=(\|a\|+\|b\|)^2.
\end{align}
Taking square roots (of positive numbers), you get
$$
\|a+b\|\leq\|a\|+\|b\|.
$$


text:
Q: How can I get information about the current user from Workbench I'm using Workbench to perform queries.
I would like to get information about the currently logged in user.
In Apex we can use the UserInfo object e.g.
Id userId =UserInfo.getUserId();
User example = [SELECT CurrencyIsoCode FROM User WHERE Id =: userId];

How would I perform a SOQL query in Workbench that returns information about the currently logged in user. e.g. SELECT CurrencyIsoCode from User Where Id = CurrentUserId?
EDIT: I thought I'd also clarify, I'm not just trying to get the currency for the currently logged in user. I am trying to query on other records (e.g. return all Accounts owned by currently logged in user). I'm also trying to do this without changing the SOQL per user. I need it to work regardless of which user executes the SOQL.

A: you don't need to perform SOQL query in workbench to get info what ever you want, once u logged in to workbench in top right corener you get user session info link, you just need to click like in image , then you get current user sesssion results

*if you need to perform SOQL only then first get user id then perform SOQL like below.
SELECT CurrencyIsoCode FROM User WHERE Id = '005t000000xxxxxxx'


text:
Q: Logon failed Crystal Report C# WPF I have a C# Desktop project that use Crystal Report tool, my object is to call a SQL procedure and get the result of this procedures ( fields of tables ) shown in the Crystal Report .rpt.
In my computer this task worked well, but the problem is that I work with a team and when I have pushed the project to GitHub and my colleague pull my work and merge it to his version.
He got a problem of Connection ( Logon failed to the database ) and three lines of Exception in the Console :

Exception thrown: 'System.Runtime.InteropServices.COMException' in CrystalDecisions.CrystalReports.Engine.dll
Exception thrown: 'CrystalDecisions.CrystalReports.Engine.LogOnException' in CrystalDecisions.ReportAppServer.DataSetConversion.dll
Exception thrown: 'CrystalDecisions.CrystalReports.Engine.LogOnException' in CrystalDecisions.CrystalReports.Engine.dll
Exception thrown: 'CrystalDecisions.CrystalReports.Engine.LogOnException' in CrystalDecisions.ReportSource.dll

I would like to know how to set the connection parameters dynamically with Crystal Report, to make the connection success in the two PCs?
try
        {

            CrystalReport1 cry1 = new CrystalReport1();
            cry1.Load(@"CrystalReport1.rpt");

            GlobalConfig.sql.ConnectionString = GlobalConfig.connectionString;
            GlobalConfig gb = new GlobalConfig();
            using (IDbConnection connection = GlobalConfig.sql)
            {
                List<string> ls = new List<string>();
                ls = gb.getConnectionlogin();
                cry1.SetDatabaseLogon(ls[0], ls[1]);

                cry1.SetParameterValue("@institute_id", instituteid);
                cry1.SetParameterValue("@date_from", from1);

                cry1.SetParameterValue("@date_to", to1);
                cry1.SetParameterValue("institutename", institutename);
                crysview.ViewerCore.ReportSource = cry1;
            }

        }
        catch(Exception es)
        {
            Console.WriteLine("Error load file   " + es);
        }

    }


text:
Q: Why doesn't fusion contradict the 1st law of thermodynamics? I was reading up on the 1st law of thermodynamics for my Chemistry exam and I was wondering why doesn't fusion contradict the 1st law of thermodynamics?
The 1st law states that

The energy of an isolated system is constant

or that whatever is put into the system, you get out of it, but in fusion you get more out of the initial reactions than you put in
Hydrogen + Hydrogen = Helium etc.
I am still a bit confused...
Thanks for any help!

A: By that logic, a battery violates the law also.
"Look, all I did was put in enough energy to flip a switch, and now an LED keeps shining and shining! I got more energy out than I put in!"
In nuclear fusion, we are releasing some latent energy which is present in the materials, by changing the nuclear structure into other materials that contain less energy.
The energy we are getting out was "put in" to those nuclear reagents.

A: To answer the question simply, $E=mc^2$.
Energy is a manifestation of mass, and mass is a manifestation of energy. In a fusion or fission process, the total "energy" of the system remains constant, it just changes shape.
By "energy" I mean the totality of the already present energy, and the bound energy of the mass that takes part in the reaction.

A: You have to realize that thermodynamics emerges from the bulk properties of matter, and this is seen better when one goes to the formalism of statistical mechanics. The first law of thermodynamics is the form conservation of energy takes in the thermodynamics mathematical framework which is constrained by classical physics.
As you must know from your chemistry courses, there exists the world of quantum mechanics, which is responsible for the existence of chemistry  and its governing laws, another framework.
Special relativity has been validated experimentally many times over, and it tells us that mass itself is a type of energy .The law of conservation of energy, as @SWeko explains  in his answer, includes the energy contained in the masses of the particles under consideration, the total energy being E=m*c^2.
In a similar manner where energy can be stored in chemical reactions, which can be released under appropriate conditions, energy is stored in nuclear reactions, of which fission and fusion are expressions.
In the realm of special relativity there is no meaning to the first law, because it does not describe nuclear reactions. Once the energy released by a nuclear reaction is taken into the equations then one can consider the thermodynamic properties of the sample resulting from fission or fusion.


text:
Q: NHibernate - composite-id - 3 I have a class in Nhibernate hbm file and for this I'm using a composite id field, in the following way :

 <composite-id>
    <key-many-to-one name="DContent" class="Business.Entities.DContent, Business" column="DId" />
    <key-many-to-one name="Structure" class="Business.Entities.Structure, Business" column="RId"/>
    <key-property name="Language"></key-property>
 </composite-id>

</class>

where DContent & Structure are classes and Language is an int.
I've overwritten the Equals & GetHashCode methods, to keep trace of the 3 objects in the composite key, but what I've discovered is that when it's creating the table in the database only the two DId & RId are part of the primary key, and not the Language.
My question is : Why NHibernate doesn't see that the Language is part of the primary key??
Thank you,
Catalin


text:
Q: Angular: destroy dynamic component Working on a chat application, I am using this to create multiple ChatComponent (as dynamic components).
loader.service.ts
import { ChatComponent } from '../components/shared/chat/chat.component';

@Injectable()
export class LoaderService {

    constructor( @Inject(ComponentFactoryResolver) factoryResolver )
    {
      this.factoryResolver = factoryResolver
    }

    setRootViewContainerRef(viewContainerRef){
      this.rootViewContainer = viewContainerRef
    }

    addDynamicComponent(timeIdentifier){
      const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
      const component = factory.create(this.rootViewContainer.parentInjector)
      component.instance.timeIdentifier = timeIdentifier;
      this.rootViewContainer.insert(component.hostView)
    }
  }

chat-container.component.ts
export class ChatContainerComponent implements OnInit {

    @ViewChild('chat', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef

    constructor( protected loaderService: LoaderService, protected route: ActivatedRoute ) { }

    ngOnInit() {

        this.route.params.subscribe(params => {
            this.loaderService.setRootViewContainerRef(this.viewContainerRef)
            this.loaderService.addDynamicComponent(params['timeIdentifier'])
        });
    }
}

This way I can generate multiple "ChatComponent" as dynamic components.
But how can I destroy them once they are created ?

EDIT

I have added this in ChatComponent (which have been created by the component factory)
this.cmpRef.destroy();
But when i call this, i got stuck in infinite loop with errors like so:
ERROR RangeError: Maximum call stack size exceeded

A: The created components from the factory are of type ComponentRef.
This class has the destroy function to destroy the instance and the associated structures.
Check it here: https://angular.io/api/core/ComponentRef

A: I found a better way to destroy a component, you can do:
addDynamicComponent(timeIdentifier){
  const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
  const component = factory.create(this.rootViewContainer.parentInjector)
  component.instance.timeIdentifier = timeIdentifier;
  component.instance.autodestroy = () => component.destroy();
  this.rootViewContainer.insert(component.hostView)
}

And inside your component class you create a method autodestroy and call it when you want destroy it.


text:
Q: Add row to form which for members? I'm trying to create a signup form which allows the user to add their members. To do this quickly I've created a basic form which has one input, and when the enter key on the keyboard is hit a new row is created.
I've tried the on e key in the input but I can only get this to alert rather than duplicate, here's my form.
<form id="contactForm" novalidate>

                        Member Name
                        <input type="text" class="form-control" placeholder="Member Name" id="member">

            <button type="submit" class="btn btn-success btn-lg pull-right">Next</button>

</form>

A: I would recommend using a javascript framework for this. There are several that are capable, but I would recommend Ember.js
Cross-reference this SO question, which is the same question as yours, except in the context of the Embers.js framework:
Ember: Adding input fields dynamically on click and reading the new data
It describes clicking a button to reveal a new field, but the same may be done with the filling of a field.
Hoping that this helps.

A: There 's no need for an extra javascript framework. Modern browsers can solve this with HTML5 and native Javascript. Here 's a small example.
<template id="my-row">

        Member Name
        <input type="text" placeholder="Member Name" name="member[]" required>

</template>

With HTML5 you can use the template tag. It was made for your purpose. The template content does not appear on the screen. It 's just invisible markup. So let 's have a look, what the javascript would look like.

For example this piece of javascript code does everything what you need. The HTML5 template is inserted as child on pressing the enter key.
The thing you have to deal with: The HTML5 template tag is 'n supported by older browsers. Eventually you have to deal with polymorphs for handling HTML5 template tags in older browsers like the Internet Explorer 11.


text:
Q: Use API Routes on localhost on build in Next.js When I'm building my project with npm run build command I get a connection error because there is no API server running.
export const getStaticProps = async () => {

const res = await fetch(`127.0.0.1:3000/api/articles`);
articles = await res.json();
    return {
      props: {
        articles
             }
           }
}

But it works perfectly with npm run dev. Because there is a server running at 127.0.0.1:3000
I did this workaround (use local data on build):
  if (server !== 'none') {
    const res = await fetch(`${server}/api/articles`);
     articles = await res.json();
  } else {
     const articlesData = await import('../../data');
     articles = articlesData.articles;
  }

But it's not what I want. I want to develop both API routes and the rest of my app in one project, then run it with a simple command npm run start.
Is there a solution to this?
I've tried to run both npm run dev and npm run build on separate terminals. One time it worked, but today I can't repeat it. The build command got stuck on this output:

info  - Finalizing page optimization

I think it's because those commands share the same directory - .next in the root of the project and their buildings are conflicting with each other.


text:
Q: convert sql query into lambda expression Here is my sql query i want to convert it into lambda expression
Select P.PlaceName As UnitNumber,
       PB.PlaceName,
       A.Locality,
       A.SubLocality,
       A.Sublocality_Level_1
from Listing L
inner join Place P ON L.PlaceId = P.Id
Inner Join Place PB ON PB.Id = P.ParentPlaceId
Inner Join [Address] A ON A.Id = PB.AddressId
Where L.Id =9

Thanks in advance .

A: Query expression is much simpler in this case. I don't recommend you to use lambdas with many joins
from l in db.Listing
join p in db.Place on l.PlaceId equals p.Id
join pb in db.Place on p.ParentPlaceId equals pb.Id
join a in db.Address on pb.AddressId equals a.Id
where l.Id == 9
select new {
   UnitNumber = p.PlaceName,
   pb.PlaceName,
   a.Locality,
   a.SubLocality,
   a.Sublocality_Level_1
}

db is your context


text:
Q: siunitx: Alignment Problems with numbers in parenthesis The example given below gives me a strange offset in 4th decimal place in the parenthesis. Interestingly, this problem arose only after I updated my Miktex 2.8 to Miktex 2.9. I don't know whats causing this is slight shift in the last decimal point in the second row.

Here is the code for above output.
\documentclass[12pt]{article}

\usepackage{amsfonts}
\usepackage{amsmath,array}
\usepackage[detect-all]{siunitx}
\usepackage[margin=1 in]{geometry}
\usepackage{booktabs, longtable}
\usepackage[english]{babel}

\begin{document}
\begin{table}[htbp]
\footnotesize
 \centering

\sisetup{input-symbols=(), table-figures-integer = 3, table-figures-decimal = 4, table-number-alignment = center}

\begin{tabular}{lSSSSSS}

\toprule
            & {\bf (A)} & {\bf (B)} & {\bf (C)} & {\bf (D)} & {\bf (E)} & {\bf (F)} \\
\hline \midrule
     & 0.0016*** & 0.0013*** & 0.0015*** & 0.0015*** & 0.0009** & 0.0009** \\
          & (0.0005) & (0.0005) & (0.0006) & (0.0006) & (0.0004) & (0.0005) \\
     &       &       &       & 0.1324*** & 0.1202*** & 0.1203*** \\
          &       &       &       & (0.0131) & (0.0118) & (0.0118) \\
 &       &       &       & -0.0549*** & -0.0569*** & -0.0569*** \\
          &       &       &       & (0.0023) & (0.0024) & (0.0024) \\
    \hline \bottomrule
    \end{tabular}
\end{table}
\end{document}

A: I would probably set the table setup like this:
\sisetup{
  input-symbols         = (),
  table-format          = -1.5,
  table-space-text-post = ***,
  table-align-text-post = false,
  group-digits          = false
}

Setting the *** as text and add a proper table-format (a sign, one digit before the decimal point, 5 after it (counting the closing brace, too)) should get the spacing between the columns right. The option table-align-text-post = false shifts the *** next to the numbers.
In your example the *** and the minus in the column to the right nearly seem to touch each other and in the last columns the *** protrude the table lines.

Full example:
\documentclass[12pt]{article}

\usepackage{amsfonts}
\usepackage{amsmath,array}
\usepackage[detect-all]{siunitx}
\usepackage[margin=1 in]{geometry}
\usepackage{booktabs, longtable}
\usepackage[english]{babel}

\begin{document}

\begin{table}[htbp]
\footnotesize\centering
\sisetup{
  input-symbols         = (),
  table-format          = -1.5,
  table-space-text-post = ***,
  table-align-text-post = false,
  group-digits          = false
}
\begin{tabular}{lSSSSSS}
 \toprule
  & {\bfseries(A)} & {\bfseries(B)} & {\bfseries(C)} & {\bfseries(D)}  & {\bfseries(E)}  & {\bfseries(F)} \\
 \hline \midrule
  & 0.0016*** & 0.0013*** & 0.0015*** & 0.0015***  & 0.0009**   & 0.0009** \\
  & (0.0005)  & (0.0005)  & (0.0006)  & (0.0006)   & (0.0004)   & (0.0005) \\
  &           &           &           & 0.1324***  & 0.1202***  & 0.1203*** \\
  &           &           &           & (0.0131)   & (0.0118)   & (0.0118) \\
  &           &           &           & -0.0549*** & -0.0569*** & -0.0569*** \\
  &           &           &           & (0.0023)   & (0.0024)   & (0.0024) \\
 \hline \bottomrule
\end{tabular}
\end{table}
\end{document}

A: You need to add group-digits=false to the \sisetup which yields:

Note:

*

*The use of group-decimal-digits=false appears to work with MikTeX 2.8, but not TeXLive 2011 so should be avoided.

A: You can also use parse-numbers = false, in the \sisetup.
\documentclass[12pt]{article}

\usepackage{amsfonts}
\usepackage{amsmath,array}
\usepackage[detect-all]{siunitx}
\usepackage[margin=1in]{geometry}
\usepackage{booktabs, longtable}
\usepackage[english]{babel}

\begin{document}
\begin{table}[htbp]
\footnotesize
 \centering

\sisetup{parse-numbers = false,input-symbols=(), table-figures-integer = 3, table-figures-decimal=4, table-number-alignment=center}

\begin{tabular}{lSSSSSS}

\toprule
            & {\bf (A)} & {\bf (B)} & {\bf (C)} & {\bf (D)} & {\bf (E)} & {\bf (F)} \\
\hline \midrule
     & 0.0016*** & 0.0013*** & 0.0015*** & 0.0015*** & 0.0009** & 0.0009** \\
          & (0.0005) & (0.0005) & (0.0006) & (0.0006) & (0.0004) & (0.0005) \\
     &       &       &       & 0.1324*** & 0.1202*** & 0.1203*** \\
          &       &       &       & (0.0131) & (0.0118) & (0.0118) \\
 &       &       &       & -0.0549*** & -0.0569*** & -0.0569*** \\
          &       &       &       & (0.0023) & (0.0024) & (0.0024) \\
    \hline \bottomrule
    \end{tabular}
\end{table}
\end{document}


text:
Q: Laravel 5 oauth2/passport API I've been clawing my eyes out on this and I was wondering if anyone else has experienced this. We are using Laravel 5.4 Passport to handle a SSO. The dev who started this had been developing on a Linux box and since I've taken it over with a Windows box, it's not working. I have dug through the issues on Github for both oauth and passport and haven't seen anything. Here's the summary:
We have a parent application that creates access tokens for the sub applications. I'm able to log into that parent one just fine. When I try to go to a sub department, I get the following error in my parent app laravel log:
2017-11-09 15:24:00] local.ERROR: League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in I:\xampp\htdocs\parentApp\vendor\league\oauth2-server\src\Exception\OAuthServerException.php:168
Stack trace:
#0 I:\xampp\htdocs\parentApp\vendor\league\oauth2-
server\src\AuthorizationValidators\BearerTokenValidator.php(97)

I added a log at where the catch gets thrown:
} catch (\RuntimeException $exception) {
        \Log::info(print_r($exception->getMessage(), true));
        //JWR couldn't be parsed so return the request as is
        throw OAuthServerException::accessDenied('Error while decoding to JSON');
    }

And this is what I get:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'subapplication.oauth_access_tokens' doesn't exist (SQL: select * from `oauth_access_tokens` where `oauth_access_tokens`.`id` = longkey limit 1)

It's trying to find the oauth_access_tokens from the sub application database. We did a walk through with PHPStorm's debugger and it seems to always be looking at the parent's database. It does find the token however it never does authenticate.
Anyone run into this? I appreciate any help in advance!
UPDATE: After going through using Xdebug, I'm wondering if it's a localhost and cookies issue. I'm getting a request with a status of 200 but then Laravel tries to check cookies and there are no cookies.


text:
Q: Iterate over list of CompletableFutures in loop without recursion So I have this piece of Java code written with recursion.
package test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {

        List<AllocationCandidateSet> candidates = new ArrayList<>();
        IntStream.range(0, 5000).forEach(__ -> candidates.add(new AllocationCandidateSet()));
        AllocationContext ctx = new AllocationContext();
        ctx.currentPlacementZoneAllocationCandidatesProvider = candidates.iterator();

        Main main = new Main();
        main.attemptAllocation(ctx).join();

        System.out.println(ctx.firstSuccessfulCandidateSet);
        System.out.println(ctx.iteration);
}

private CompletableFuture<AllocationContext> attemptAllocation(AllocationContext context) {
    return CompletableFuture.completedFuture(context)
            .thenCompose(this::getNextCandidateSet)
            .thenCompose(this::runAffinityFilters)
            .thenCompose(ctx -> {
                if (ctx.firstSuccessfulCandidateSet == null
                        && context.currentPlacementZoneAllocationCandidatesProvider.hasNext()) {
                    return attemptAllocation(ctx);
                } else {
                    return CompletableFuture.completedFuture(ctx);
                }
            });
}

private CompletableFuture<AllocationContext> getNextCandidateSet(AllocationContext ctx) {
    // For the sake of simplicity, I omitted most of the logic inside this method.
    ctx.currentCandidateSet = ctx.currentPlacementZoneAllocationCandidatesProvider.next();
    ctx.iteration++;
    return CompletableFuture.completedFuture(ctx);
}

private CompletableFuture<AllocationContext> runAffinityFilters(AllocationContext ctx) {
    // This is a long running async operation doing DB calls
    return CompletableFuture.completedFuture(ctx)
            .thenCompose(context -> {
                // Do some DB calls and run business logic and evaluate if the current AllocationCandidateSet is successful
                boolean success = context.iteration == 1876;
                return CompletableFuture.completedFuture(success);
            })
            .thenAccept(success -> {
                if (success) {
                    ctx.firstSuccessfulCandidateSet = ctx.currentCandidateSet;
                }
            })
            .thenApply(__ -> ctx);
}

public static class AllocationContext {
    Iterator<AllocationCandidateSet> currentPlacementZoneAllocationCandidatesProvider;
    AllocationCandidateSet currentCandidateSet;

    AllocationCandidateSet firstSuccessfulCandidateSet;

    int iteration = 0;
}

public static class AllocationCandidateSet {

}

}
Results are accumulated inside the AllocationContext which is a thread-safe object holder that contains Iterator - context.currentPlacementZoneAllocationCandidatesProvider.
The iterator is a normal one - having next() and hasNext() methods.
The getNextCandidateSet() method advances the iterator forward. This method is actually sync as opposed to async so theoretically .thenCompose(this::getNextCandidateSet) can be replaced with .thenApply(this::getNextCandidateSet) with little refactoring.
The problem I'm having is with the runAffinityFilters() method... This method is doing async calls to the Database with must be non-blocking. Its signature returns CompletableFuture<AllocationContext> and it's not feasible to change it.
Therefore, calls to runAffinityFilters() are chained in this CompletableFuture chain with recursion - after each runAffinityFilters() call, a check for successful result is made - if running the affinity filters yielded no success ( (ctx.firstSuccessfulCandidateSet == null ) and the iterator can be advanced ( context.currentPlacementZoneAllocationCandidatesProvider.hasNext() )
... then allocateAttempt(ctx) is invoked again.
Is there a way to replace the recursion with regular iteration? With the recursive solution I'm hitting StackOverflowError near the 1000th loop...
It would be ideal to continue running runAffinityFilters() as async call, waiting for it to complete, checking the condition if (ctx.firstSuccessfulCandidateSet == null && context.currentPlacementZoneAllocationCandidatesProvider.hasNext())  and then continuing with next iteration.