text:
Q: Error con las url al listar productos desde archivo index.html Estoy tratando de listar productos en un archivo index.html, agradecería mucho su ayuda.
Tengo este archivo de las url de la aplicación:
from django.conf.urls import url
from . import views

urlpatterns = [
 url(r'^$', views.hello_world, name='hello'),
 url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail)
]

Estoy tratando de acceder a este método que se encuentra en el archivo views.py:
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render, get_object_or_404
from .models import Product

def product_detail(request, pk):
    product = get_object_or_404(Product, pk=pk)
    template = loader.get_template('product_detail.html')
    context = {
    'product': product
    }

    return HttpResponse(template.render(context,request))

y este es el archivo index.html donde listo los productos y me muestra error en el navegador al momento de ejecutar la aplicación:
<!DOCTYPE html>

     {% load staticfiles %}
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-
          scale=1">
     <link rel="stylesheet" href="{% static 'css/base.css' %}">

Hola

        {% for pr in product %}

                    {{pr.name}}

                {{pr.description}}

        {% endfor %}

Este es el error:

A: {% for pr in product %}

            {{pr.name}}

        {{pr.description}}

{% endfor %}

Comencemos con el for, este no es el principal problema pero no puedes iterar un solo objeto, cuando haces el get_object_or_404 estas pidiendo por un solo objeto y no por varios para realizar el for, lo que puedes hacer es un if, para ver si recibimos el producto. Usa product.name, product.description, ...
Ahora si el error esta en  deberia ser  . La razon?, cuando usamos el parametron {% url '' %} , estamos pidiendo por el nombre que le asignamos en el archivo urls.py y no a la function.
from django.conf.urls import url
from . import views

#app_name='tu_nombre' #Si esto es una app agregale nombre para que la diferencie de las otras app y agregalo en la url de esta manera 'tu_nombre:products'

urlpatterns = [
 url(r'^$', views.hello_world, name='hello'),
 url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='products')
]


text:
Q: SSL with Heroku hosting and Gandi domains I'm trying to set up SSL Automated Certificate Management with Heroku. I have my domain with Gandi and am having troubles setting the DNS target.
How Heroku says it should be set up:
Domain Name       DNS Target

mydomain.com      mydomain.com.herokudns.com
www.mydomain.com  www.mydomain.com.herokudns.com

So ideally in Gandi I would have
Name   Type   Value

www    CNAME  www.mydomain.com.herokudns.com
@      CNAME  mydomain.com.herokudns.com

However, you cannot assign a root domain to a CNAME record, so the second line there wouldn't work.
Another way to do it could then be to use an A record
Name   Type   Value

www    CNAME  www.mydomain.com.herokudns.com
@      A      1.2.3.4 (IP Address of my site)

But again this doesn't work because the IP address of Heroku hosted sites can change.
So I thought I found a work around, by forwarding mydomain.com to www.mydomain.com through Gandi's web forwarding. For my DNS Records I just have:
Name   Type   Value

www    CNAME  www.mydomain.com.herokudns.com

So now the website works, I can access it by going to www.mydomain.com or mydomain.com, but now  my SSL certification isn't working!
My site still says "Your connection to this site is not secure"
When I check the status on Heroku I get:
Domain            Status
───────────────   ───────
www.mydomain.com  OK
mydomain.com      Failing

I basically just learned most of how DNS works today, so I could be doing this completely wrong.
Any help is appreciated!

A: It's possible (and cheaper) to use heroku ssl certificate with gandi... You just need to be sure to set up a subdomain everytime. I believe naked subdomain or wildcards are not supported by heroku automated certs because of the let's encryption restrictions. As soon as the statues are ok for all of your subdomains, dont forget to force_ssl in your app, so every http request will be redirected to https. U can do it like this:
# config/environments/{staging,production}.rb
config.force_ssl = true

VERY IMPORTANT! Don't forget to remove or edit any unsercured links to external assets. Otherwise browsers will jugde the page with those links unsecured as described in the Modzilla support page about mixed content.
Once all of this is done, U see the satifying green lock on every pages of your app :D.

A: Ok, so apparently it is impossible to use Heroku's SSL certificate with Gandi, so I ended up going with Gandi's SSL certificate instead. If anyone needs a tutorial here's a great one by Le Wagon
https://vimeo.com/209534466

A: Just a follow up for this question with my experience. I purchased a domain name from Gandi and use permanent web forwarding to forward the domain name to my heroku application. I also add custom domain(the one I bought) to heroku console.
Domain Name        DNS Record Type  DNS Target
─────────────────  ─────────────── ───────────────────────
xshogi.com.tw      ALIAS or ANAME   xshogi.com.tw.herokudns.com
www.xshogi.com.tw  CNAME            www.xshogi.com.tw.herokudns.com

I could not successfully adopt heroku ACM to configure my domain even though I had paid for hobby plan.
I followed the tutorial video that Johnnybib posted.

*

*create server.crs and server.key in project with openssl req -nodes -newkey rsa:2048 -sha256 -keyout server.key -out server.csr

*go to purchase SSL certificate page in Gandi

*cat server.csr and paste it to Gandi console

*pay and wait for authentication done to finish this bill

*download .crt and .pem certificate and concatenate them together into all.crt

*use heroku certs:add --app xshogi all.crt server.key
Also, remember to change CNAME www from webredir.vip.gandi.net. to xshogi.com.tw.herokudns.com.
All set up and wait for a short while, I can curl https://www.xshogi.com.tw. I can also connect to https://www.xshogi.com.tw in browser and the URL does not change to https://xshogi.herokuapp.com.

A: You can actually use heroku's SSL serts.
What you can do in Gandi is redirect to https://www.yoursite.com :)
Considering that you changed your DNS settings to the ones heroku provided.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want the cron job to run the script weekly basis I am trying to setup a cron job on a Ubuntu server. I want the cron job to run the script on weekly basis. Problem is - It should be a working day, If im mentioning it with time interval, it fails during weekoffs - Need an Schedular Exp which has to work weekly only on working days at office hours.(9am to 9pm)max.
Want to Execute the script every week @6 pm during the weekdays. It Can be Mon to Fri.

A: Step1
sudo apt-get install cron

systemctl status cron

Step2
Configure the cron job:
crontab -e

Select an editor of your choice
0 0 * * 0 /path/to/command

Syntax: minute hour day-of-month month day-of-week command.
Day-of-week goes from 0-6 where 0 is Sunday.
Save it.


text:
Q: error Axis2 client invoke SSL Service from J2EE application in Websphere6.1 I am stucked in the issue where my axis2 based client call the ssl service from websphere 6.1 and throws the following exception along with the message at the top. I have followed the step from click here to install the ssl certificate using IBM websphere admin console in default trust store. Please note this client was working fine for APACHE tomcat. Any help in this regard will be highly appreciable Thanks.
setting up default SSLSocketFactory

class com.ibm.websphere.ssl.protocol.SSLSocketFactory is loaded

SSLSocketFactory instantiation failed: java.lang.ClassCastException:
com.ibm.websphere.ssl.protocol.SSLSocketFactory incompatible with         javax.net.ssl.SSLSocketFactory

{HttpMethodDirector:439} - I/O exception (java.net.SocketException) caught when     processing request: java.lang.ClassCastException:     com.ibm.websphere.ssl.protocol.SSLSocketFactory
incompatible with javax.net.ssl.SSLSocketFactory

{HttpMethodDirector:445} - Retrying request

{HttpMethodDirector:439} - I/O exception (java.net.SocketException) caught when     processing request: java.lang.ClassCastException:     com.ibm.websphere.ssl.protocol.SSLSocketFactory incompatible with     javax.net.ssl.SSLSocketFactory

{HttpMethodDirector:445} - Retrying request

{HttpMethodDirector:439} - I/O exception (java.net.SocketException) caught when     processing request: java.lang.ClassCastException: com.ibm.websphere.ssl.protocol.SSLSocketFactory incompatible with javax.net.ssl.SSLSocketFactory

{HttpMethodDirector:445} - Retrying request

{HTTPSender:202} - Unable to sendViaPost to url[https://sma/CBDSMS/api/GetDue.svc]
java.net.SocketException: java.lang.ClassCastException:     com.ibm.websphere.ssl.protocol.SSLSocketFactory incompatible with     javax.net.ssl.SSLSocketFactory
at javax.net.ssl.DefaultSSLSocketFactory.throwException(Unknown Source)
at javax.net.ssl.DefaultSSLSocketFactory.createSocket(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:615)
at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:116)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:130)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:560)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:76)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:400)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:225)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:438)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:402)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)

A: please user "parent last" setting in the classloader for this web app. see here for details.


text:
Q: Can any one please how I should calculate the probability given this probability density function?
Hi,
the problem is attached.
Thanks

A: Your confusion is totally valid because your $f_{\bar{x}}$ is not what we call a probability density function; this terminology is reserved only for continuous random variables. On the other hand, the usual arrow notation (as you see in Figure 1) denotes point mass. So $\bar{x}$ is a mixture of continuous random variable and discrete random variable. In this sense the problem is severely misleading readers.
Anyway, forgetting about the term 'probability density function' and accepting that Figure somehow represents a distribution $F_{\bar{x}}$ such that

*

*$F_{\bar{x}}$ has uniform density of $0.2$ over the interval $[-2,1]$, and

*$F_{\bar{x}}$ has probability mass at $2$, and

*The total mass of $F_{\bar{x}}$ is of course $1$.

Then it follows that
$$ \operatorname{Pr}(\bar{x} = 2) = 1 - \operatorname{Pr}(\bar{x} \neq 2) = 1 - \int_{-2}^{1} 0.2 \, dx = 1 - 0.6 = 0.4. $$
Now you have all the required ingredients. Let us for instance solve [a].
$$ \operatorname{Pr}(\bar{x} \geq -1)
= \operatorname{Pr}(\bar{x} \in [-1,1]) + \operatorname{Pr}(\bar{x} = 2)
= \int_{-1}^{1} 0.2 \, dx + 0.4
= 0.8. $$
Alternatively,
$$ \operatorname{Pr}(\bar{x} \geq -1)
= 1 - \operatorname{Pr}(\bar{x} < -1)
= \int_{-2}^{-1} 0.2 \, dx
= 0.2. $$


text:
Q: Windows serial port timing? I need to measure the time between character events on a serial port, preferably under Windows 7.
I have read in various places, statements like "Windows will not provide greater resolution than 10ms", but I have not been able to find out what that really means.
Is the problem that the OS will not deliver the events with greater accuracy, or is it that the timing functions (for measuring) used to be that "poor"? (I'm thinking GetTickCount)
If the latter, then I guess I should be able to use something like QueryPerformanceCounter for good-enough measuring, but if the events aren't delivered with similar accuracy, that obviously won't help.

A: I think the 10 ms time is due to the task switching.  Even if your timing application is the only user task running, there are still a bunch of system tasks that might get switched in.
On top of that, I'm guessing that the time between receiving a character on the port and receiving a DataReceived event (or whatever software notification you want) is highly variable.  The UART chip may not interrupt the CPU until it feels like it (usually when its FIFO is full or some timeout expires), then the kernel may decide to take some time before sending that interrupt information on to your application.  So even though you can use a high resolution timer in your software, you would probably be at the mercy of hardware/kernel level variability.

A: What you can use to get a much higher timing resolution is a Stopwatch. This is in System.Diagnostics, and its Elapsed field (a Timespan) has a resolution of 100 nanoseconds (I hope that's accurate enough !).
I use C++ Builder and often put in code something like this :
#include <Diagnostics.hpp>

TStopwatch SW;
TTimeSpan TS;
SW = TStopwatch::StartNew();
// Do something we need timed here ...
SW.Stop();
TS = SW.Elapsed;
Caption="That took "+String(TS.Minutes)+" Minutes, "+String(TS.Seconds)+" Seconds."+String(TS.Milliseconds)+" mS.";

For more info, here's a link to an MSDN page about this :
https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(VS.110).aspx


text:
Q: Is the graph of $y=\frac{k}{x}$ a hyperbola? Is the graph of the following inverse relation a hyperbola?$$y=\frac kx$$
If yes, is it the only kind of hyperbola whose equation is an explicit function?

A: Yes, $$y=\frac kx$$
is a hyperbola. In fact, it is a type of rectangular hyperbola which you can read more about here.
This means that a function $y(x)$ that takes the form
$$y-k=\frac {k}{x-h}$$
is also hyperbola.
 I suppose that is the only type of hyperbolas that is a function since any rotation of this type of hyperbolas will immediately cause the plot to fail the vertical line test.
Thanks to @Blue:

Any (non-degenerate) hyperbola with a vertical asymptote is the graph of a function. Rectangularity is not a requirement.

A: It is a hyperbola, and you can even derive it from the original formula of a hyperbola using analytic geometry.
Let $a$ and $b$ be the axes of the $y=1/x$ hyperbola, while $x$ and $y$ are the axes of the $y^2-x^2=k$ hyperbola. If $a=(x+y)/2$ and $b=(y-x)/2$, then graphing the original $y^2-x^2=k$ formula by replacing y with b and x with a respectively we get the exact same hyperbola as $y=k/x$.


text:
Q: How to force Python to ignore re.DOTALL in re.findall() statement? I have been banging my head against the keyboard in search of enlightenment through Google and all Python docs I could get my hands on, but could not find an answer to an issue I'm encountering.
I have the following regex that I run against a website, but Python insists in setting re.DOTALL on it, even though my code does not tell it to:
\d+. +(?P<season>\d+) *\- *(?P<episode>\d+).*?(?P<day>\d+)(?:\/|\s)+(?P<month>[A-Za-z]+)(?:\/|\s)+(?P<year>\d+) +(?:)? ?(?P<name>.*?)

This creates an array of seasons/episodes for TV show listings, and it works fine except on epguides.com/BurnNotice (when using the TVRage listings), due to some spacing before newlines (I guess).
Using http://re-try.appspot.com to test, I've narrowed down the issue to the use of re.DOTALL. If I enable it on re-try, it replicates the results I get when I run it standalone on my script. If I untick DOTALL, then it gives me the results I expect.
How can I force Python NOT to use re.DOTALL?
The script runs both on Ubuntu and OS X.

A: .+> should change to [^>]+> and
.*?> to [^>]*>
You can try replacing others dots into [^\r\n] too, but above 2 changes should be enough.


text:
Q: How to integrate Spring and JSF How to integrate Spring and JSF? I followed Spring documentation (which is sparse on this subject) and googled some more and currently I found two working ways:

*

*JSF Managed Bean will be Spring @Component / @Named (but there doesn't seem to work JSF scopes, but only Spring scopes):
@Component
@Scope("request")
public class ItemController {

  @Autowired
  private ItemService itemService;

}

*I will use @ManagedBean, JSF scopes work, but I cannot autowire Spring bean using @Autowired, the bean must contain setter and I'm not sure if this is best practice:
@ManagedBean
@RequestScoped
public class ItemController {

  @ManagedProperty("#{itemService}")
  private ItemService itemService;

  public void setItemService(ItemService itemService) {
    this.itemService = itemService;
  }

}

*Something else?

A: I would definitely go with way number 1 (and did so in quite some projects). It makes no real sense to mix JSF managed beans with Spring beans, unless you have a good reason to do so. With Spring managed beans, you have far more possibilities and you can use the full power of Spring even for your managed beans.
Theoretically, there is a third way: You could use CDI for the UI layer and Spring in the background. This might be an option if you don't want to use a full blown Java EE environment but still want to benefit from CDI and Myfaces CODI/Deltaspike in the UI layer. But in this case you would additionally need a CDI setup and a CDI to Spring bridge.

A: I was having the same issue a while back.
Although there also is an option of a spring EL enhancement to lookup spring beans there, I still found the differences between JSF and spring to be too wide a gap to try to cross in a seamless manner.
My recommendation is therefore to make the gap explicit and not try to cross it.
In my case I ended up with a service locator pattern, gaining access to spring context and lookup there..
@ManagedBean
@ApplicationScoped
public class ServiceLocator {
   public <T> T getServiceByType(Class<T> serviceType) {
     getSpringContext().getBean(serviceType);
   }

   public ApplicationContext getSpringContext() {
     return FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
   }
}

@ManagedBean
@ViewScoped
public class ViewBean {

   @ManagedProperty("#{serviceLocator}")
   protected ServiceLocator serviceLocator;

   public void actionMethod() {
     serviceLocator.getService(BookingService.class).book(roomId, fromDate, toDate);
  }
}

Written from memory, but you might get the gist

A: You can use @AutowiredBean from JSF-Spring integration project to inject JSF managed beans into Spring beans:
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class JsfTest implements Serializable {
    private static final long serialVersionUID = 1L;

    @AutowiredBean
    private JsfBean jsfBean;

    ...
}

Add Maven artifact com.intersult:jsf-spring:2.2.0.1-SNAPSHOT to your project, see https://www.intersult.com/wiki/page/JSF%20Spring%20Integration (use translation button).

A: One approach is let Spring manage all your bean, definitely you need to use SpringBeanFacesELResolver in faces-config.xml
Bean:

@Component
@Scope("view")
public class UserBean

faces-config.xml:

<el-resolver>
    org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>

Spring provides option to add your custom scope, you need to implement org.springframework.beans.factory.config.Scope interface. Use applicationcontext.xml for registration with Spring.
applicationcontext.xml on a custom 'view' scope implementation :
[ViewScope is my implementation of Scope interface]
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="view">
                <bean class="com.org.common.ViewScope"/>
            </entry>
        </map>
    </property>
</bean>


text:
Q: Could not load dynamic library /usr/lib/OGRE/RenderSystem_GL I am trying to run a program in C++ but I am getting this error:
terminate called after throwing an instance of 'Ogre::InternalErrorException' what():  OGRE EXCEPTION(7:InternalErrorException): Could not load dynamic library /usr/lib/OGRE/RenderSystem_GL.  System Error: /usr/lib/OGRE/RenderSystem_GL.so: cannot open shared object file: No such file or directory

I have installed the Ogre libraries but this problem still persists. Any help on which package do I need to install to get rid of this error? I am using Ubuntu 14.04.

A: OGRE libraries shipped by Ubuntu are installed in /usr/lib/x86_64-linux-gnu/OGRE-1.9.0/ (or -1.8.0), not in /usr/lib/OGRE/.
Your program is attempting a dlopen or similar with an absolute path. If you cannot modify the program so that it uses the new path (or, better, it lets the linker decide what path to use), the easiest solution is creating a symlink with:
sudo ln -s /usr/lib/x86_64-linux-gnu/OGRE-1.9.0/ /usr/lib/OGRE/

A: Try ldd YOUR_BINARY to see if it can find the dynamic linking libs it requires.


text:
Q: How to return the all object on save() function with mongo in PySpark I am very new into PySpark and MongoDB and struggling with the objectId. How can I get the all objectId on save()?
people = spark.createDataFrame([("Bilbo Baggins",  50), ("Gandalf", 100), ("Thorin", 95)], ["name", "age"])
people.show()
people = people.write.format("mongo").mode("append").option("database","test_db").option("collection", "test_table").save()
print(people)

Output of the above print() is None. I wants all the current saved objects and object_ids of all objects on print.
Thanks you.


text:
Q: What is the file with .p8 extension? (APNs Auth Key / JWT) I think it is a little ridiculous but it's hard to find information about what is this file. I've found a lot info how to get this Apple Push Notification Authentication Key, but i also want to know exactly what is it.
Here is some info i have found:
Benefits:

*

*No need to re-generate the push certificate every year;

*One auth key
can be used for all your apps;

*Same for sandbox and Production.

From Apple Docs:

Token-based provider connection trust: A provider using the
  HTTP/2-based API can use JSON web tokens (JWT) to provide validation
  credentials for connection with APNs. In this scheme, you provision a
  public key to be retained by Apple, and a private key which you retain
  and protect. Your providers then use your private key to generate and
  sign JWT provider authentication tokens. Each of your push
  notification requests must include a provider authentication token.
You can use a single, token-based connection between a provider and
  APNs can to send push notification requests to all the apps whose
  bundle IDs are listed in your online developer account.
Every push notification request results in an HTTP/2 response from
  APNs, returning details on success or failure to your provider.
  Further check Token-Based Provider-to-APNs Trust section.

Questions:

*

*What is actually the .p8 file?

*What programm can open it? (Keychain didn't work for me)

*Is there a way to convert it to .pem or .p12?

*A little flow-out question in order to not create a new topic: Does the server side operate with .p8 the same way as .p12 or it should be additional tools added?

A: File extensions are just a convention, but most likely the .p8 extension is used to indicate that it is a PKCS#8 PrivateKeyInfo (or EncryptedPrivateKeyInfo).
I'd expect the Keychain program to be able to open it as "a key", but not having a mac at hand I can't say.  It should open with SecItemImport (kSecFormatOpenSSL, kSecItemTypePrivateKey).

Is there a way to convert it to .pem or .p12?

Assuming you mean "certificate" by .pem, no. If you mean PEM encoded, sure.  It's either "BEGIN PRIVATE KEY" or "BEGIN ENCRYPTED PRIVATE KEY", depending.
It can also, technically, be converted into a PKCS#12.  But Apple's PKCS#12 importer won't import (last I saw) private keys that it can't figure out what certificate they belong with (from the same PKCS#12).
This is just a private key, there's no certificate (thus no expiration).  So certificate-based approaches don't make sense.

Does the server side can operate with .p8 the same way as .p12 or it should be additional tools added?

This depends entirely on the details of the protocol, which I don't know.  If the protocol transported the certificate then different machinery is involved with the conversion.  If it just transported a signature and the server looked up the public key for verification then nothing changed server side.

A: It's a text file! The .p8 extension signifies a simple text file containing public/private key. You can open it with any text editor (TextEdit, vim, Sublime Text) to see your key.

A: The following is the state of my research:
The APNS .p8 file contains the PRIVATE KEY that is used to SIGN the JWT content for APNS messages.
The file itself is a pure text file, the KEY inside is formatted in PEM format.
The part between the -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- is a base64 formatted ASN.1 PKCS#8 representation of the key itself. Some can use the following web service to extract its contents (ASN1JS).
The KEY itself is 32 bytes long and is used to create the required ECDSA P-256 SHA-256 signature for the JWT. The resulting JWT looks like this '{JWT header base64 encoded}.{JWT payload base64 encoded}.Signature (64 bytes) base64 encoded'.
There are a lot of web services to decode such tokens, but some couldn't check the signature, as the corresponding PUBLIC KEY isn't known (Apple keeps it secret when providing the PRIVATE KEY).
EDIT: It seems, that the PUBLIC KEY is also included in the .p8 file, it can be extracted via OpenSSL (and is visible when decoding the ASN.1 content: the 520 bit stream).

openssl ec -in AuthKey_123ABC4567.p8 -pubout -out
  AuthKey_123ABC4567_Public.p8


text:
Q: Why aren't my attempts to freeze time not working? I want it so when the player moves his mouse on an object the time freezes and he can't move anymore. I tried different methods but it just doesn't freeze the time.
private void OnMouseEnter()
    {
        PlayRandomSound();
        Time.timeScale = 0;
    }


text:
Q: P-n junction diode under forward bias configuration Why there is exponential growth in current with respect to voltage in p-n junction diode under forward bias configuration?

A: To briefly summarize the whole physics:
P-n diode has excessive holes in one side of the junction and excess free electrones on the other but both sides are electrically neutral. Initially they diffuse to create an equilibrium of numbers of electron and hole , but in this way They create electric potential on the opposite side Off the flow. This Presents prevent further flow of electrons. But when forward bias is used the potential is lowered and a huge flow is again initiated. The exact mathematical structure(the exponential behaviour) can be obtained by writing down the equations of motion and solving them.
Consult the book on Solid State Physics by Ashcroft and Mermin or by Kittel for the mathematical description.

A: But by  combination of electrons with holes there will be increase in repulsion forces of electrons this will create more resistance. so currrent should not increase exponentially with voltage


text:
Q: Is $a(a+1)=b(b-1) \implies b = a + 1$ correct? ($a, b > 0$) I've seen a website wrote: $$a(a+1)=b(b-1) \implies b = a + 1$$
I don't know where the second part come from. How to prove it?

A: Let $n = b - a$.  Then your equation becomes
$$a(a + 1) = (a + n)(a + n - 1).$$
After expanding this you can cancel an $a^2$ term from each side, then move everything to one side and it factors giving
$$0 = (2a + n)(n - 1).$$
Thus either $n = 1$ or $n = -2a$, so either $b = a + 1$ or $b = -a$.


text:
Q: can we create same store view for multiple websites in magento I have multiple store website in which I want to add feature of language in url. I have created store view name with code 'en' for first site (for ex. www.site-one.com) so that user can open www.site-one.com/en.
Now I want to create the same for second site but using the same code for second site (for ex. www.site-two.com) is giving error "Store with the same code already exists.".
Is this possible to create same store code for more than one site so that user can also open www.site-two.com/en

A: Unfortunateley not. The store code in the core_store database table has a unique key and changing this will break lots of things in Magento.
A possible workaround is not to use the "prepend store code" configuration and instead configure the base urls for the stores like http://www.site-one.com/en/. Then create a rewrite rule (for example using .htaccess) to direct all requests from /en/* to /* and so on.
Example configuration
For the store codes en, fr and de:
    RewriteRule ^(?:en|fr|de)/(.*)$ $1 [QSA]
This should be placed before all other rewrite rules.
OK I tested it and indeed got a 404 error from Magento, probably because it tries to evaluate the request URI relative to index.php.
The usual approach seems to be to actually create the subdirectories, copy index.php and .htaccess, and either

*

*symlink all other directories (en/app -> app etc.) or

*adjust index.php to point to the correct Mage.php and configure only the web base url with subdirectory, so that js, media and skin files still are loaded from their original path.

(1) definitely works, I have done it in the past. (2) should work but there might be some more things to consider


text:
Q: Fetching nth document based on integer array in MongoDB so let's say I have a random array of n integers [23, 2, 78, 99, ... ] where  0 < n < collection.count(), and each element is within this range as well.
In my collection, it is currently indexed by _id, and say it contains the following data:
{
    "_id" : "1293jnqke",
    "name" : "name_string",
    "other_data" : [{
        "data" : ...
    }]
}

How should I go about grabbing the data, in chunks of 50, which correspond to each element in the array? So with the example integer array I have, I will slice it down to the first 50 elements, and then I wish to run a find() on the collection, extracting the names of the 23rd, 2nd, 78th, 99th, etc elements, based on the natural ordering of the collection (no need for any sorting beforehand). So the output should look like this:
{
    [ {"name" : "23rd name"},
    {"name" : "2nd name"},
    {"name" : "78th name"},
    {"name" : "99th name"},
    {"name" : "53rd name"},
    {"name" : "11th name"},
    ...]
}

One way of course is by looping through the array with findOne() and skip() but I don't think that is very efficient, is it possible to execute this in a single query? Or are there any better methods?
Appreciate any help, thank you!


text:
Q: Whitespaces in cvs modules file I'm trying to add some files with whitespaces to my CVS Modules file, but can't figure out how to write its name.
tried using ", ', \", \'.
nothing worked.
how to do it?

A: You cannot have whitespace in the module name. The parser for modules files is as simple as it gets and will stop at the first whitespace to make the module name:
while (*vp && !isspace ((unsigned char) *vp))
    vp++;
if (*vp)
    *vp++ = '\0';       /* NULL terminate the key */
p->type = NDBMNODE;
p->key = xstrdup (kp);


text:
Q: How does @context_processor effect template variables? I found the following code:
@app.context_processor
def inject_user():
    if authed():
        return dict(session)
    return dict()

Then they use session['nonce'] = XXXXX and use the {{ nonce }} in a template.
If I define a var in a context processor, do I know all of its attributes?  Is {{ nonce }} the same as the session value?
I concluded that the session var is passed to all the templates, but it's not clear if its attributes are also known, and if so isn't it supposed to be used as session.nonce instead of nonce?

A: Flask passes the session to the template context by default.  This can be used just like in your view code, it is a dictionary.
{{ session['nonce'] }}
or {{ session.nonce }}

The context processor your posted takes all the items from the session and puts them directly in the template context, so they don't have to be accessed through the session var.
{{ nonce }} comes from session through the context processor

Ultimately, the context processor you posted is pretty useless, but it could be convenient in some cases.


text:
Q: Problem with is_user_logged_in() function in some pages I faced a problem with this function is_user_logged_in() in the header to test if the user is logged in to some code.
Its working just in some pages like homepage but the other sub-pages not I don't know why!!!


text:
Q: How to annotate typing.Generic type itself? I was playing around new Python typing system and I faced concept which I don't know how to express in it. I want to pass the generic class type itself. E.g. to describe function which takes generic[1] G, type T and returns G[T].
I used mypy to check verify my tries.
The naive approach didn't work in Python 3.7.
from typing import Generic, Type, List, Mapping, TypeVar

T = TypeVar('T')

def foo(generic: Generic, param: Type[T]) -> Generic[T]: #  error: Invalid type "typing.Generic"
    return generic[param] #  error: Value of type "Generic?[T?]" is not indexable

ListOfInts: Type = foo(List, int)

assert ListOfInts == List[int] # passes in runtime

Naive GenericMeta in Python 3.6's backport of typing?
There is GenericMeta is available in backport, but I didn't find how to use it and it didn't make it to PEP.
def foo(generic: GenericMeta, param: Type[T]) -> Type[Type[T]]:
    return generic[param] #  error: Value of type "GenericMeta" is not indexable

Mapping[Type, Type]?
I came up with Mapping, but apparently List is not such.
def apply(generic: Mapping[Type, Type], param: Type[T]) -> Type[Type[T]]:
    return generic[param]

# error: Argument 1 to "apply" has incompatible type "Type[List[Any]]"; expected "Mapping[Type[Any], Type[Any]]"
ListOfInts: Type = apply(List, int)

Less strict works in Python 3.6 and 3.7
This is version I use for now.
It catches some absurd calls like apply(10, int), but apply(int, int) will slip through static analysis and raise on runtime.
def apply(generic: Type, param: Type[T]) -> Type[Type[T]]:
    return generic[param]

So the question comes is it possible to express generic type itself?
As for me, based on duck-typing, List should simply be Mapping[Type, Type]. I found PEP for protocols, maybe this is right tool for my problem?
[1] If I understand category theory right, such generic's type is technically named functor and is well known concept in languages like Haskell.


text:
Q: Isuues after converting project from java to kotlin Hello there after a long time thinking about converting my project from java to kotlin , today I shift from java to kotlin , and as expected and warned by the community that the project will not magically just transfer everything easily to kotlin, there are errors now
ok I just make it clear I'm a very beginner in kotlin but I was somewhat familiar with java
there are as I noticed 1 main error with almost all the converted java to kotlin files
Smart cast to 'RecyclerView!' is impossible, because 'postRecyclerView' is a mutable property that could have been changed by this time

in java, for eg if I have to add a scroll listener I just do this
recyclerview.addOnScrollListner

but getting error in kotlin // below is lines are kotlin
postRecyclerView.setLayoutManager(
            staggeredGridLayoutManager
        )

or
 postRecyclerView.addOnScrollListener

or
shimmerFrameLayout.startShimmer()

as I don't know much about kotlin I don't know what it is
and secondly, in my old java adapter class, I have
public static List<Upload> mUploads;

but now as converted in kotlin I'm facing an issue with mUploads
for eg on this line
val uploadCurrent: Upload = Companion.mUploads.get(position)

getting error on mUploads it is showing Unresolved reference: mUploads
Old java adapter class code
PostAdapter_Home.java
public class PostAdapter_Home extends RecyclerView.Adapter<PostAdapter_Home.PostViewHolder> {
    public static List<Upload> mUploads;
    public Context mcontext;

    public PostAdapter_Home(Context context, List<Upload> uploads) {
        mUploads = uploads;
        mcontext = context;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        view = LayoutInflater.from(mcontext).inflate(R.layout.ex_home, parent, false);
        return new PostViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
                .setBaseColor(Color.parseColor("#F3F3F3"))
                .setBaseAlpha(1)
                .setHighlightColor(Color.parseColor("#E7E7E7"))
                .setHighlightAlpha(1)
                .setDropoff(50)
                .build();
        ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
        shimmerDrawable.setShimmer(shimmer);
        Upload uploadCurrent = mUploads.get(position);
        Glide.with(mcontext)
                .load(uploadCurrent.getmImageUrl())
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .placeholder(shimmerDrawable)
                .centerCrop()
                .fitCenter()
                .into(holder.imageView);

//        holder.imageView.setOnClickListener(view -> changeScaleType(holder, position));

    }

    @Override
    public int getItemCount() {
        return mUploads.size();
    }

    public void setUploads(List<Upload> uploads){
        mUploads=uploads;
    }
    public static class PostViewHolder extends RecyclerView.ViewHolder {

        private final ShapeableImageView imageView;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imagePostHome);

        }

    }
}

PostAdapter.kt
class PostAdapter     /* ShimmerFrameLayout shimmerFrameLayout; */(
    var mcontext: Context
) : RecyclerView.Adapter<PostAdapter.PostViewHolder>() {
    private var mListener: OnItemClickListener? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
        LayoutInflater.from(mcontext).inflate(R.layout.post_item_container_profile, parent, false)
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.post_item_container_profile, parent, false)
        return PostViewHolder(view)
    }

    override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
        val uploadCurrent: Upload? = mUploads.get(position)
        val shimmer = ColorHighlightBuilder()
            .setBaseColor(Color.parseColor("#F3F3F3"))
            .setBaseAlpha(1f)
            .setHighlightColor(Color.parseColor("#E7E7E7"))
            .setHighlightAlpha(1f)
            .setDropoff(50f)
            .build()
        val shimmerDrawable = ShimmerDrawable()
        shimmerDrawable.setShimmer(shimmer)
        Glide.with(mcontext)
            .load(uploadCurrent.getmImageUrl())
            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            .placeholder(shimmerDrawable)
            .centerCrop()
            .fitCenter()
            .into(holder.imageView)
    }

    override fun getItemCount(): Int {
        return Companion.mUploads.size
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        mListener = listener
    }

    fun setUploads(uploads: List<Upload>) {
        Companion.mUploads = uploads
    }

    interface OnItemClickListener {
        fun onClick(view: View?)
        fun onItemClick(position: Int)
        fun onDeleteClick(position: Int)
    }

    inner class PostViewHolder internal constructor(itemView: View) :
        RecyclerView.ViewHolder(itemView), View.OnClickListener, OnCreateContextMenuListener,
        MenuItem.OnMenuItemClickListener {
        var imageView: ShapeableImageView
        override fun onClick(v: View) {
            if (mListener != null) {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    mListener!!.onItemClick(position)
                }
            }
        }

        override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) {
            val delete = menu.add(Menu.NONE, 2, 2, "Delete")
            delete.setOnMenuItemClickListener(this)
        }

        override fun onMenuItemClick(item: MenuItem): Boolean {
            if (mListener != null) {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    if (item.itemId == 2) {
                        mListener!!.onDeleteClick(position)
                        return true
                    }
                }
            }
            return false
        }

        init {
            imageView = itemView.findViewById(R.id.imagePost)
            itemView.setOnClickListener(this)
            itemView.setOnCreateContextMenuListener(this)
        }
    }

    companion object
}

A: It happens because in kotlin, There're **two ways to declare variables.
Using lateinit keyword : no need to initialize while declaration.
Using null as initial value for variable.
So when you converted java files to kotlin it may have initialized your values with null
So you can add  !! or ? operator at end of variable for null safety which is initialized as null.
example.
postRecyclerView!!.setLayoutManager(
            staggeredGridLayoutManager
        )
 postRecyclerView!!.addOnScrollListener

for more you can check this link
Null Safety Kotlin
In kotlin, static variables (Which can be accessed only with class name) are under companion object blocks
   companion object{
    //your variables here
    }

As you're using mUploads inside same class, You don't need to access it with class name.
Use
mUploads.get(position)

instead of
Companion.mUploads.get(position)


text:
Q: How to install apt-get package in Amazon Linux machine How to  install apt-get in amazon linux machine,using yum or wget ,i searched extensively but didnt find relvant ..getting below message
[ec2-user@ip-172-31-33-94 ~]$ sudo apt-get update -y && sudo apt-get install -y
linux-image-extra-$(uname -r)
sudo: apt-get: command not found

A: well figured out these commands hence answering,these commands will install apt-get and run docker as ec2 user
sudo yum update -y
sudo amazon-linux-extras install docker
sudo service docker start
sudo usermod -a -G docker ec2-user
docker info
docker run -it --rm tarunkumard/gatling:FirstScript


text:
Q: Is this schema of homogeneity equivalent to Reflection? Take the theory $\sf ZFC + classes$ exposited in this posting. Now replace the axiom schema of replacement in non-class style by an axiom of limitation of size, that is: $$\forall \mathcal X \subset \mathcal V \ (\mathcal X \in \mathcal V \iff |\mathcal X| < \mathcal V)$$ where $\mathcal V$ is the class of all sets (i.e. objects of the first sort).
Now add the following homogeneity axiom schema: $$ \phi^1 \iff \phi^2$$, where $\phi^1, \phi^2$ are homogeneous in non-class, class style respectively, and each is the other formula re-written in its style.
Now clearly this theory call it $\sf ZFC + classes_3$ would interpret both $\sf ZFC + classes$ and $\sf ZFC + classes_2$. But here it is stronger since it clearly interprets $\sf MK$. This theory proves the existence of a class that is of inaccessible cardinality, and thus a set likewise, but this would further pump $\mathcal V$ to the next inaccessible and so there must be a set likewise, and so on...

Now is this homogeneity axiom acting in a way similar to reflection acting on top of limitation of size axiom, like the theory here? or is it weaker? or is it stronger acting like the resemblance axiom schema presented in this theory? or is it even inconsistent?


text:
Q: light action bar support library: why it doesn t work? I'm using the support v7 library and in my style in valus-v11 i set
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">

The problem is that the ActionBar is Dark and i would like Light. Also the dialogs are Dark and i would like light. How can i fix?
Here is written https://developer.android.com/training/basics/actionbar/styling.html
"Theme.AppCompat.Light for the "light" theme." but doen't work

A: Check this link
http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html
Customize according to what you want. See the parent style @android:style/Widget.Holo.Light.ActionBar
<style name="Theme.Styled" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar"
    parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@drawable/ab_custom_solid_styled</item>
    <item name="android:backgroundStacked"
        >@drawable/ab_custom_stacked_solid_styled</item>
    <item name="android:backgroundSplit"
        >@drawable/ab_custom_bottom_solid_styled</item>
</style>


text:
Q: jquery .load() is loading file twice (i.e., grabs two copies instead of one) Onclick, the .load() callback fires twice, and, two identical files get loaded.
var fetch = $this.attr('href')+' #fetchable';
$('div').load(fetch,'', function(){
    console.log('Done.'); // this fires twice
});

Network tab -
b.htm?_=1451867642174
b.htm?_=1451867642175

Console -
(2) Done.

Ideas? I just want it to load once, obviously. Thanks.

A: I was using animationend along with webkitanimationend, and, it was therefore firing off twice since Chrome will process both.


text:
Q: Is there a difference between "being selected" and "being pre-selected"? I am reviewing a document where it is stated that something is part of a set of pre-selected items.
To me that doesn't make sense. Isn't everything selected also pre-selected by definition? I mean being selected, means it happened in the passed, so what does "pre" adds to its meaning?

A: Preselect and preselection can be used in a number of different ways, which are all compatible with the general meaning of selecting in advance.
The first way of using these words is presented in the already posted answers on this page. Preselection may be the process of narrowing down the list of options to a shorter one, from which the choice is to be made later. The word is typically used in this way when the two stages of the process are performed by different decision makers; the preselection is usually intended to make things easier for those who have to make the final decision.
The second way of using these words is for a selection that takes place earlier than would otherwise be expected. An airline may thus refer to the passengers' selection of seats at the time of booking as 'preselection', because it takes place before checking in, when seat selection has traditionally taken place. That way of using it is unlike the first one, in that there is no expectation of any further selection.
Sometimes preselection is used in a way that is effectively a hybrid of the first two: the preselected options are presented to somebody who has to make the final decision (as in the first way), but that decision maker is expected to merely rubberstamp the preselected options and (as in the second way) not make any further selection out of them.
With respect to all these ways of using the word one may wonder whether preselection is the best term for what is intended. Something like creating a shortlist, although somewhat longer, probably conveys much more clearly what is meant by the first way of using the word. The second way of using it can usually be replaced by selection; the context will usually make it clear when the selection takes place, so pre- is unnecessary (and if the context does not make that clear, pre- doesn't help). Preselection can be misleading when used in the third way; something like selection, subject to so-and-so's approval is likely to be much clearer.

A: A pre-selection is the stage before the main selection. In your case they made a pre-selection of items, out of which a final selection will be made.

A: Pre-selected items are already selected items.

A: I am not a native English speaker. In my mind, the term pre-selected, aside from its implicit implying that the selection process is a multistage one, gently stresses that the selection in the first round is not a definitive result, while if the term selection is used instead any act of selection is definitive and irreversible.

A: Isn't everything selected also pre-selected by definition? Yes.
Where the phrase involves the word 'selected', the event has happened in the past.
However, in this instance it is the act of selecting something which has, for whatever reason, previously been through a process of selection: this previous occasion causes the "pre" to be included.


text:
Q: How can I refresh homestead for a new site in my environment? I'm running Laravel 4 on my development machine (Mac) with homestead and enjoying it thus far but having trouble when adding a new site.  The problem is that I add lines like this for a new site in my ~/.homestead/Homestead.yaml file:
folders:
    - map: ~/Sites
      to: /home/vagrant/Sites

sites:
    - map: listingnaples.dev
      to: /home/vagrant/Sites/listingnaples.com/public

    - map: videocraftersusa.dev
      to: /home/vagrant/Sites/videocraftersusa.com/

Then, my /etc/hosts looks like this:
# MY SITES
192.168.10.10 listingnaples.dev
192.168.10.10 videocraftersusa.dev
192.168.10.10 laneyandchris.dev

If i go in and do a homestead destroy followed by homestead up I can access any of those new sites. That deletes my databases though and really sets me back.  How do I "refresh" so to speak?  If I add myawesomesite.dev to my /etc/hosts, how can I have homestead pick it up?
I tried homestead --provision but that isn't a recognized command.
For what it's worth, in my ~/.homestead/ directory, I do not have a VagrantFile.  Not sure where that's at so I can't run a vagrant provision either.

A: I just ssh using homestead ssh and then add this line
serve domain.app /home/vagrant/Code/path/to/public/directory

where you replace domain.app to your app name, the same you use on your yaml file and your path to your new public site directory, then just homestead up and you could see it active.

A: Try run vagrant global-status. You'll see the list of running boxes at this time, like this:
MacBook-Pro-lancedikson:~ lancedikson$ vagrant global-status
id       name    provider   state   directory
------------------------------------------------------------------------------------------
9710b02  default virtualbox running /Users/lancedikson/.composer/vendor/laravel/homestead

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date. To interact with any of the machines, you can go to
that directory and run Vagrant, or you can use the ID directly
with Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"

That's all. Now run vagrant provision 9710b02 and it will be provisioned.

A: As of Laravel 5 and more importantly Homestead 2.0, just run:
homestead up

Then:
homestead provision

A: You have to use vagrant provision anyway from the same directory where Homestead.yaml is.

A: You can run:
homestead up --provision

A: You can also reload the box and the settings
vagrant reload --provision

This reload the box and see if there are changes, if that's the case it will make the changes while reloading

A: In my case I had a Homestead.yaml in ~/.homestead/ and in ~/Homestead/.
I am not sure if the default location changed or that I changed it manually (maybe because I did not like the hidden dir), but make sure you don't have multiple Homestead.yaml files. I now symlinked them so I can not confuse myself any further.
But normally, homestead provision or homestead up --provision (when it was turned off) should do.


text:
Q: How can I get multiple COUNT's in a single SQL query with multiple WHERE conditions? I need to get a report on users' activity on a web app.
First, I have a table that counts the number of times a user logs on our app that looks like this:
user_activity
-----------------------------------------------------
| ID_login | Username | Date       | Hour     | ... |
|---------------------|------------|----------|-----|
|        1 | john     | 2019-03-01 | 08:49:24 | ... |
|        2 | john     | 2019-03-01 | 14:12:49 | ... |
|        3 | jane     | 2019-03-03 | 10:02:31 | ... |
|      ... | ...      | ...        | ...      | ... |
-----------------------------------------------------

What I want to do is have a report that will give me not just the total amount of login per user for a set time period. That I can already do. Where I'm stuck is when I try to get a report for each month of the previous year where months are in separate columns.
I would want the table generated by my query to look like this:
user_activity
--------------------------------------------------------
| Username | login_total | login_jan | login_feb | ... |
|------------------------|-----------|-----------|-----|
| john     |        4827 |       164 |       191 | ... |
| james    |        3866 |        92 |       144 | ... |
| jane     |        2979 |       104 |        92 | ... |
| ...      |         ... |       ... |       ... | ... |
--------------------------------------------------------

So as you can see, I was thinking about using the login_total value to use for ORDER BY.
So here's what I have at this point.
SELECT
    user_activity.Username,
    COUNT(user_activity.ID_login) AS login_total

FROM
    user_activity

WHERE
    user_activity.Date >= '2018-01-01'
    AND
    user_activity.Date <= '2018-12-31'

How do I get another column with the COUNT, but with different criteria? Where am I supposed to put in those criteria? I've tried using IF statements and HAVING statements, but it didn't work.
I was thinking something like this...?
SELECT
    user_activity.Username,
    COUNT(
        IF
            (user_activity.Date >= '2019-01-01'
            AND
            user_activity.Date <= '2019-01-31')
        user_activity.ID_login)
        AS login_jan,

    COUNT(
        IF
            (user_activity.Date >= '2019-02-01'
            AND
            user_activity.Date <= '2019-02-28')
        user_activity.ID_login)
        AS login_feb,
    ...

FROM
    user_activity

Didn't seem to work either... Is there something I'm missing?

A: We can do conditional aggregation, something like this:
SELECT ua.username
     , SUM( ua.date >= '2019-01-01' AND ua.date < '2019-02-01' ) AS login_jan
     , SUM( ua.date >= '2019-02-01' AND ua.date < '2019-03-01' ) AS login_feb
  FROM user_activity ua
 GROUP
    BY ua.username

That uses MySQL shorthand, the expression inside the SUM() aggregate will be evaluated as 1, 0 or NULL. We can use MySQL IF() function or a more portable ANSI SQL CASE expression
SELECT ua.username
     , SUM(IF( ua.date >= '2019-01-01' AND ua.date < '2019-02-01' ,1,0)) AS login_jan
     , SUM(IF( ua.date >= '2019-02-01' AND ua.date < '2019-03-01' ,1,0)) AS login_feb
  FROM user_activity ua
 GROUP
    BY ua.username

or
SELECT ua.username
     , SUM(CASE WHEN ua.date >= '2019-01-01' AND ua.date < '2019-02-01' THEN 1 ELSE 0 END) AS login_jan
     , SUM(CASE WHEN ua.date >= '2019-02-01' AND ua.date < '2019-03-01' THEN 1 ELSE 0 END) AS login_feb
  FROM user_activity ua
 GROUP
    BY ua.username

A: You are trying to create a PIVOT table which you can do in MySQL using conditional aggregation. Note that you can simplify your expressions by using the MONTH and YEAR functions:
SELECT u.Username,
       COUNT(*) AS login_total,
       SUM(MONTH(u.Date) = 1) AS login_jan,
       SUM(MONTH(u.Date) = 2) AS login_feb,
       ...
       SUM(MONTH(u.Date) = 12) AS login_dec
FROM user_activity u
WHERE YEAR(u.Date) = 2018
GROUP BY u.Username

This query also takes advantage of the fact that in a numeric context MySQL treats a boolean expression as 1 (true) or 0 (false), allowing us to SUM those values.


text:
Q: filter data in Spark SQL in Databrick When I run below command in Databrick , I get output where I have three columns called name, id and age but when I try to filter on name by running below I get below error as Name column do not exist. What wrong am i doing?
%sql
SELECT inline(environment.details) FROM TableA

This gives me a table with 3 column correctly.
Now I do filter oon Name like this
%sql
    SELECT inline(environment.details) FROM TableA where `Name` == "XYZ"

and I get error as Name table do not exist.What wis wrong here. Also if someone can tell me how can I export the resultant output.
Thanks

A: Filtering happens before your expand your array of structs.  You have two choices here:

*

*Use common table expressions to explode first & then filter:

with exploded as (
  SELECT inline(environment.details) FROM TableA
)
SELECT * from exploded where name = ....

*Use the filter function to filter out data inside the array with something like that (not tested), but it may require doing the filtering two times:

SELECT inline(filter(environment.details, x -> x.Name = 'XYZ'))
FROM TableA
WHERE array_size(filter(environment.details, x -> x.Name = 'XYZ')) > 0


text:
Q: Как найти максимум и минимум функции для заданного интервала? Есть ли в библиотеке SymPy метод для вычисления минимума и максимума заданной функции на отрезке?
from sympy import *
x = Symbol("x")
x1 = -5
x2 = 5
f = x**2

Необходимо найти экстремумы функции f в промежутке от x1 до x2

A: Можно сделать так:
from sympy import solveset, symbols, Interval, Min, Max
x = symbols('x')

lower_bound = -5
upper_bound = 5
f = x**2

zeros = solveset(f, x, domain=Interval(lower_bound, upper_bound))
assert zeros.is_FiniteSet # If there are infinite solutions the next line will hang.
res_min = Min(f.subs(x, lower_bound), f.subs(x, upper_bound), *[f.subs(x, i) for i in zeros])
res_max = Max(f.subs(x, lower_bound), f.subs(x, upper_bound), *[f.subs(x, i) for i in zeros])

Результат:
In [29]: res_min
Out[29]: 0

In [30]: res_max
Out[30]: 25

PS в следующей версии SymPy должны добавить функции sympy.calculus.util.minimum() и sympy.calculus.util.maximum():
from sympy.calculus.util import minimum, maximum

interv = Interval(-5, 5)
res_min = minimum(f, interv)
res_max = maximum(f, interv)

Источник (с) @smichr


text:
Q: Intermittent issue - ldap_start_tls_s() failed, Connect error We're getting intermittent errors of this nature:
[Mon Mar 20 08:38:37 2017] [info] [client client_ip_here] [27056] auth_ldap authenticate: user first.last@server.com authentication failed; URI /path/to/project/trunk [LDAP: ldap_start_tls_s() failed][Connect error]

In the Apache logs:
197896-[Mon Mar 20 08:38:37 2017] [info] Initial (No.1) HTTPS request received for child 3 (server svn.server.com:443)
197897-[Mon Mar 20 08:38:37 2017] [debug] mod_authnz_ldap.c(432): [client client_ip_here] [27056] auth_ldap authenticate: using URL ldap://ldap.server.com/OU=Accounts,DC=AAA,DC=BBB,DC=CCC?mail
197901:[Mon Mar 20 08:38:37 2017] [info] [client client_ip_here] [27056] auth_ldap authenticate: user first.last@server.com authentication failed; URI /path/to/project/trunk [LDAP: ldap_start_tls_s() failed][Connect error]

Apache configuration:
<Location /svn/>
    DAV svn

    SVNListParentPath on
    SVNParentPath /path/to/repositories
    SVNIndexXSLT "/svnindex.xsl"

    # SetEnv SVN_LOCALE_CHARSET "en_US.UTF-8"
    SetEnv SVN_LOCALE_CHARSET "UTF-8"

    AuthBasicProvider ldap file
    AuthUserFile /path/to/svnfile.acl
    AuthType Basic
    AuthzLDAPAuthoritative off
    AuthName "Login with full email (lowercase) and password / Utiliser votre courriel (minuscules) et mot de passe pour vous authentifier"
    AuthLDAPBindDN "bind_dn_here"
    AuthLDAPBindPassword "password_here"
    AuthLDAPURL "ldap://ldap.server.com/OU=Accounts,DC=AAA,DC=BBB,DC=CCC?mail" TLS
    AuthzSVNAccessFile /path/to/svnrepos.acl

    require valid-user
</Location>

LDAP configuration file:
RERERRALS off
TLS_CACERTDIR   /etc/openldap/certs
TLS_REQCERT never

This used to be rock solid until last week, where we had to change DC. The solution until a solution is found, is to restart Apache every half hour (or when the authentication starts to fail)
Apparently, the new DC is configured the same way as the other one. Unsure how to troubleshoot this. I don't manage all the parts in this equation.

A: You could try running an ldapsearch that mimics what Apache is doing when you notice the problem.  If your issue shuts out all users it shouldn't matter which you bind as.  You would also want the verbose switch to see if you get  a any clues to why starttls is failing.
Another tool you could try is "openssl s_client", that might give you more info on the starttls conversation, and help you narrow the cause down.
Has looked into the logs on your new DC?


text:
Q: Converting Inno Setup WizardForm.Color to RGB If I try this:
[Setup]
AppName=MyApp
AppVerName=MyApp
DefaultDirName={pf}\MyApp
DefaultGroupName=MyApp
OutputDir=.

[Code]
function ColorToRGBstring(Color: TColor): string;
var
  R,G,B : Integer;
begin
  R := Color and $ff;
  G := (Color and $ff00) shr 8;
  B := (Color and $ff0000) shr 16;
  result := 'red:' + inttostr(r) + ' green:' + inttostr(g) + ' blue:' + inttostr(b);
end;

procedure InitializeWizard();
begin
  MsgBox(ColorToRGBstring(WizardForm.Color),mbConfirmation, MB_OK);
end;

I get: red:15 green:0 blue:0
But the result should be: 240 240 240 (grey)
What is wrong?
I need to get the proper TColor and convert it to RGB color code.

A: When the first byte is $FF, the last byte is an index in a system color palette.
You can get RGB of the system color using GetSysColor function.
function GetSysColor(nIndex: Integer): DWORD;
  external 'GetSysColor@User32.dll stdcall';

function ColorToRGB(Color: TColor): Cardinal;
begin
  if Color < 0 then
    Result := GetSysColor(Color and $000000FF) else
    Result := Color;
end;

The ColorToRGB code is copied from Delphi VCL (Vcl.Graphics unit).

The above code returns Win32 API color, what is $BBGGRR. It you need $RRGGBB, you need to swap the bits:
Result :=
  ((Result and $FF) shl 16) +
  (Result and $FF00) +
  ((Result and $FF0000) shr 16);


text:
Q: Angular Error asignando "*" a una variable declarada en el scope Mi problema es el siguiente, tengo declarado en el scope la siguiente variable :
  $scope.submit={
     next:"",
     formparams:"",
     value:""
  };

En mi HTML tengo :

 Opcion:
     <input id="{{opcion.opcion}}" type="radio" name=grupo
      value="{{opcion.Submit}}+{{opcion.opcion}}" ng-model="submit.next"
      ng-change="submit.value={{opcion.opcion}}" ng-required="true"required> {{opcion.opcion}}
    </input>

En el arreglo de opciones vienen un arreglo de la siguiente manera {1,2,3,4,*,#}
Cuando selecciono en el radio cualquiera de las opciones que sean numéricas todo perfecto, pero cuando selecciono ejemplo el "*"  en la consola del navegador veo el siguiente error :
angular.js:9419 TypeError: a is not a function
at OPERATORS.* (http://192.168.0.3:8080/MobilTest/lib/angular.js:9515:44)
at http://192.168.0.3:8080/MobilTest/lib/angular.js:10041:35
at Scope.$eval (http://192.168.0.3:8080/MobilTest/lib/angular.js:11961:28)
at http://192.168.0.3:8080/MobilTest/lib/angular.js:16943:13
at http://192.168.0.3:8080/MobilTest/lib/angular.js:16784:11
at Array.forEach (native)
at forEach (http://192.168.0.3:8080/MobilTest/lib/angular.js:303:11)
at $setViewValue (http://192.168.0.3:8080/MobilTest/lib/angular.js:16782:7)
at http://192.168.0.3:8080/MobilTest/lib/angular.js:16284:14
at Scope.$eval (http://192.168.0.3:8080/MobilTest/lib/angular.js:11961:28)(anonymous function) @ angular.js:9419(anonymous function) @ angular.js:6843(anonymous function) @ angular.js:16786forEach @ angular.js:303$setViewValue @ angular.js:16782(anonymous function) @ angular.js:16284Scope.$eval @ angular.js:11961Scope.$apply @ angular.js:12061(anonymous function) @ angular.js:16283(anonymous function) @ angular.js:2613forEach @ angular.js:310eventHandler @ angular.js:2612

Y el valor de la opcion "*" no se asigana a la variable.
Muchas gracias por su pronta ayuda.

A: El error estaba en que al colocar el * se estaba interpretando como un operador aritmetico no como un valor de tipo string. al crear el arreglo entonces ['1','2','3','*'] ya funciona el código tal cual como lo tengo.

A: El problema está en el array:
{1,2,3,4,*,#}

Con los números funciona sin problemas, porque se interpretan como un valor entero, pero si quieres que el valor de la opción se "*", tienes que entrecomillar el asterisco; si no, se interpretará como el operador de multiplicación y te crea los problemas que estás viendo. De manera similar, tienes que entrecomillar la almohadilla para que se interprete como una cadena y evitar problemas:
{1,2,3,4,"*","#"}


text:
Q: Example of weakly convergent sequence, not convergent in norm I need to find example of sequence $(f_n)_{n=1}^{\infty}$ in $C[a,b]$ which converges weakly to $f \in C[a,b]$, such that $||f_n||_u \to ||f||_u, n \to \infty$, where $$||f||_u = \underset{x \in [a,b]}{max }|f(x)|,$$ but $(f_n)_{n=1}^{\infty}$ doesn't converge to $f$ in norm.
Can you help me, please?

A: Say $[a,b] = [0,1]$ and take for $f_n$ function which is:
a. 1 at 0
b. 0 at $\frac{1}{2n}$
c. 1 at $\frac{1}{n}$
d. 1 at 1
e. and linear between these points
The weak limit of $f_n$ is function which is identically $1$
since we have point-wise convergence and functions are bounded.
At the same time the norm of the difference is $1$.


text:
Q: how to display value in dropdown list depending on another dropdownlist using jsp? I'm tying to bind the value to dropdownlist i.e named as subtype which is depending on another dropdownlist i.e named as type. Please tell me how I can do that.. I have given I following code which implement for binding the dropdownlist depending on another dropdownlist.
  `

 Chosen category :

 <% String getType=request.getParameter("id");
 out.println("
"+getType+"  Change the
 category
");
 %>

 Select type :

 <select name="type">
     <option value="none">Select</option>
  <%
  Connection conn = NewClass.getOracleConnection();
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery("Select distinct company from admin.all_stuff
   where stuff_type='"+getType+"' ");
  while(rs.next()){
      %>
      <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
       <%
  }
 %>
  </select>

  Select Subtype :

     <select name="subtype">
  <option value="none">Select</option>
     <%
  try
  { %>
 <% String typeselected = request.getParameter("type");
  Statement stmtmt = conn.createStatement();
  ResultSet rse = stmtmt.executeQuery("Select model_no from admin.all_stuff
  where stuff_type='"+getType+"' and company='"+typeselected+"' ");
  while(rse.next()){
      %>
      <option value="<%=rse.getString(1)%>"><%=rse.getString(1)%></option>
      <%
  }
  %>
  <% }
  catch(Exception e)
  {
      out.println(e.getMessage());
  }
  %>
  }
    </select>

`

A: You need AJAX for this to get it work.
Your jsp is compiled into a servlet and then delivered to your client. After that no more changes are possible.
You have to handle an onChange event on the first drop down box in HTML and then post an AJAX request to your server to send back the content for the second drop down box.

A: Easiest way to start with AJAX is to get some library for example jQuery
$.get('ajax/test.html', function(data) {
    alert(data);
});

This code allow us to download from HTML page some content from URL 'ajax/test.html'.
Second argument is callback function. Variable data has content of page 'ajax/test.html'
More: http://api.jquery.com/jQuery.get/


text:
Q: Is there a way to combine two similar legends into one simple legend using ggplot? I've attached two example datasets
resind2 <- structure(list(Station = structure(c(2L, 2L, 3L, 3L, 4L, 4L,
5L, 5L, 6L, 6L, 26L, 27L, 27L, 28L, 28L, 29L, 29L, 30L, 30L,
31L, 31L, 20L, 21L, 21L, 22L, 22L, 23L, 23L, 24L, 24L, 25L, 25L
), .Label = c("A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "B1", "B2", "B3", "B4", "B5", "B6", "C1", "C2", "C3", "C4",
"C5", "C6", "D1", "D2", "E1", "E2", "E3", "E4", "E5", "F1", "F2",
"F3", "F4", "G0", "G1", "G2", "G3", "G4"), class = "factor"),
    icegroup = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("pre", "post"
    ), class = c("ordered", "factor")), mean = c(0.00308641975308642,
    0.00308641975308642, 0.00308641975308642, 0.00308641975308642,
    0.00308641975308642, NA, 0.00308641975308642, 0.00308641975308642,
    0.00925925925925926, NA, 0.0524691358024691, 0.182098765432099,
    0.0524691358024691, 0.175925925925926, 0.0493827160493827,
    0.160493827160494, 0.095679012345679, 0.160493827160494,
    0.0925925925925926, 0.12962962962963, 0.0833333333333333,
    0.0294117647058824, 0.0343137254901961, 0.0294117647058824,
    0.318627450980392, 0.151960784313726, 0.264705882352941,
    0.137254901960784, 0.112745098039216, 0.240196078431373,
    0.122549019607843, 0.220588235294118), Lat = c(72.46096,
    72.46096, 72.45834, 72.45834, 72.45723, 72.45723, 72.45455,
    72.45455, 72.45335, 72.45335, 72.32363, 72.32195, 72.32195,
    72.32009, 72.32009, 72.2963, 72.2963, 72.294, 72.294, 72.29368,
    72.29368, 72.37331, 72.37086, 72.37086, 72.35019, 72.35019,
    72.34705, 72.34705, 72.32738, 72.32738, 72.32544, 72.32544
    ), Long = c(-80.90488, -80.90488, -80.90544, -80.90544, -80.89737,
    -80.89737, -80.89799, -80.89799, -80.89003, -80.89003, -81.14611,
    -81.13219, -81.13219, -81.11921, -81.11921, -81.17538, -81.17538,
    -81.17191, -81.17191, -81.16389, -81.16389, -81.00075, -80.98878,
    -80.98878, -81.09397, -81.09397, -81.08279, -81.08279, -81.17314,
    -81.17314, -81.15897, -81.15897), year = c("2018", "2018",
    "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018",
    "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018",
    "2018", "2018", "2018", "2019", "2019", "2019", "2019", "2019",
    "2019", "2019", "2019", "2019", "2019", "2019")), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 60L, 100L, 101L, 102L, 103L, 104L, 105L,
106L, 107L, 108L, 109L, 110L), class = "data.frame")

resindna <- structure(list(Station = structure(c(4L, 6L, 7L, 8L, 9L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 12L, 13L), .Label = c("A0", "A1",
"A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "B3", "B4",
"B5", "B6", "C1", "C2", "C3", "C4", "C5", "C6", "D1", "D2", "E1",
"E2", "E3", "E4", "E5", "F1", "F2", "F3", "F4", "G0", "G1", "G2",
"G3", "G4"), class = "factor"), icegroup = structure(c(1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L), .Label = c("pre",
"post"), class = c("ordered", "factor")), mean = c(0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Lat = c(72.45723, 72.45335,
72.45078, 72.44962, 72.44698, 72.45834, 72.45723, 72.45455, 72.45335,
72.45078, 72.44962, 72.44698, 72.42462, 72.42056, 72.41856),
    Long = c(-80.89737, -80.89003, -80.89063, -80.88254, -80.88313,
    -80.90544, -80.89737, -80.89799, -80.89003, -80.89063, -80.88254,
    -80.88313, -80.97923, -80.95146, -80.93752), year = c("2018",
    "2018", "2018", "2018", "2018", "2019", "2019", "2019", "2019",
    "2019", "2019", "2019", "2019", "2019", "2019")), row.names = c(6L,
10L, 12L, 14L, 16L, 71L, 73L, 75L, 77L, 79L, 81L, 83L, 86L, 87L,
89L), class = "data.frame")

ggplot()+
geom_count(data=resind2,aes(x = Long, y = Lat, size = mean), fill = 'white',shape=21)+
  geom_point(data = resindna, aes(x = Long, y = Lat), color = 'blue', shape = 21, size = 0.7, show.legend = T)+
  facet_grid(year~icegroup, labeller = labeller(icegroup = grouplabs)) + theme_bw()

What I would like to do is get a plot similar to this one, but with a different legend. In the plot above, the two datasets show up as different colors, which is exactly what I want. However, is it possible to remove the blue dots from the legend and instead add a single blue dot above the first black dot that corresponds to a value of 0.0? Alternatively, is there a way to rbind resindna data to the resind2 dataset while achieving the same legend structure?

A: This is quite a tricky one, but it is possible. You need to map a dummy variable to the color aesthetic, then make that blue with scale_colour_manual. You then need to change the guide for the size aesthetic to get rid of its blue dots. Finally you need to remove the title from each legend and set the margins to squash them together:
ggplot() +
  geom_count(data = resind2,aes(x = Long, y = Lat, size = mean),
             fill = 'white', shape = 21,  key_glyph = "point")+
  geom_point(data = resindna, aes(x = Long, y = Lat, color = "0.0"),
             shape = 1, size = 0.7,
             show.legend = TRUE) +
  scale_color_manual(values = "blue", name = "My title") +
  facet_grid(year~icegroup) +
  guides(color = guide_legend(order = 1),
         size = guide_legend(order = 2, title = NULL,
                             override.aes = list(size = c(3, 4, 6)))) +
  theme_bw() +
  theme(legend.margin = margin(-15, 10, 0, 10))


text:
Q: Automatically start Windows Server 2003 Perfmon counter log upon reboot Trying to figure out how to make sure a specific Windows Perfmon Counter Log resumes logging  automatically when the server is rebooted.
This is a Windows 2003 Server, so likely won't have anyone logging on to it immediately upon reboot. I saw this similar question, but didn't think that Scheduled Tasks execute without someone logging on...
Edit: Ok, looks like Scheduled Tasks can be set to run a command each server start, but a couple of remaining questions:

*

*On the "Schedule" tab, should I leave both the "Start log" and "Stop Log" to "manual"? Then use the LOGMAN START command?

*I saw some other web references to instead setting the "Stop Log" to 1 day, and checking the "When a log file closes: Start a new log file" checkbox. Any benefits to this approach? Does it recognize and survive a reboot without the explicit LOGMAN START command?

*The task scheduler UI, on the Settings tab, has a box marked "Stop the task if it runs for..." that defaults to 72 hours. If I don't remove this check, will it stop my log once the server is up for 72 hrs?

And a final strategy question: If I want to monitor a handful of servers in this manner, for  a short period of time, am I better off setting these monitors up directly on each server, or to run directly on my workstation, gathering data remotely?

A: OK - I remember how to do this now!
Set the START TIME to now (or the past).  Set the STOP AFTER to 9999 days.  This will restart the counter automatically after each reboot without the need for a scheduled start script

A: Scheduled tasks can run even with no user logged on.  You provide a username and password for the task (preferably a service account so the password does not expire).

A: Create a scheduled task that runs Logman.exe to start your performance counter log.

A: Update: In the "schedule" tab, select some date in the past( and not manaully!). I think that this should be enough. But I didn't test it lately. To make this more complete choose some reasnoble stop condition, and also select start a new log file in the "when a log file is closed" box. I believe this should solve your problem.
Before Update: What do you mean by "performance counter restars?". Performance counter are always available when the system is up and running. If you want to log the data from the counter than you can use the "counter log" feature. You create a new log with the counters you are intrested in. and can configure the scheduling of the logging. It will autostart if the computer reboots.

A: You can record a non-interactive performance log.
On Windows 7 (and, I assume, Vista) define a "Data Collector Set".
On XP: define a "Counter Log"
(In both cases start by running "perfmon".)
Set up a schedule that runs continuously.
The file created is available in a number of formats, including CSV and suitable for import into the interactive display.


text:
Q: How to proxy an image stream in wcf (REST) I have a WCF service (hosted in ASP.net) that's basically acting as a proxy (turning http into https). I need to connect out to a trusted site, grab an image, and return it through my service.
I want to avoid having to download the entire image on the service before starting to ship the stream out to the consumer, but I'm not exactly sure how to go about that.
I'm pretty sure I need to start getting the response stream from the trusted site, and immediately return that stream (hoping WCF will dispose of the streams once they're done).
So far I've got
    [WebGet(UriTemplate = "/GetImage?imageUrl={imageUrl}")]
    public Stream GetImage(string imageUrl)
    {
        if (string.IsNullOrWhiteSpace(imageUrl))
        { return new MemoryStream(Encoding.UTF8.GetBytes(ErrorBuilder.BuildJsonError("param"))); }

        Uri verification = new Uri(imageUrl);
        if (verification.Host != "flixster.com")
        {
            //TODO: Create new error for unknown urls.
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return new MemoryStream(Encoding.UTF8.GetBytes(ErrorBuilder.BuildJsonError("param")));
        }

        WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(imageUrl);
            //GetResponse() will get the whole thing, which I don't want.
            //I just want to start getting bytes back and then ship the stream off to
            //the consumer. Basically a proxy.
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

            }
        }
        catch (Exception e)
        {
            ExceptionLogger.LogException(e);
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return new MemoryStream(Encoding.UTF8.GetBytes(ErrorBuilder.BuildJsonError("param")));
        }

        throw new NotImplementedException();
    }

Not sure if I'm heading in the right direction or not, and any help would be greatly appreciated. Thanks all!

A: This article is a little old, so there may be newer techniques available, but it seems to be accomplishing something very similar to what you are trying to achieve.
Streaming Proxy


text:
Q: PHPUnit fails to load files with namespace statement When trying to load a source file with an absolute namespace \Blah; declaration from PHPUnit, the loading fails:
Fatal error: Undefined constant 'Blah' in C:\path\to\file.php on line 3

Call Stack:
...

How can I fix this ?

A: Searching the internet, I found a solution suggested by Eric Hogue on Twitter:
Use a relative namespace declaration, i.e. namespace \Blah; becomes
namespace Blah;

https://twitter.com/JeremyKendall/status/294956904067780610


text:
Q: Send array to javascript from Symfony controller I need to send data array from Controller, but i don't know what is the good way. I think the controller should send the array in json.
This is my js code:
 $.typeahead({
        input: '[data-autocomplete="team"]',
        minLength: 1,
        order: "asc",
        offset: true,
        hint: true,
        source: {
             items: {
                 data: [here, i need to get array data from controller]
                 ajax: {
                     type: "POST",
                     url: "/teams",
                     data: {
                         myKey: $('[data-autocomplete="team"]').val()
                     }
                 }
             }
         },
    });

and this is my controller
    /**
     * @Route(name="teams", path="/teams")
     */
    public function sendTeams()
    {
        $em = $this->getDoctrine()->getManager();
        $teams = $em->getRepository(Teams::class)->findAll();
        $data = [];
        foreach($teams as $team){
           $data[] = $team->getName();
        }

        return new JsonResponse($data, 200, [], true);
    }

A: Using a JsonReponse is a proper solution.
But there is multiple way your code could be improved.
If your project is configured with the default autowiring options, you could auto wire your repository (which by the way would have been better if called TeamRepository associated to a Team entity instead of Teams):
/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data, 200, [], true);
}

You should also not set the bool $json parameter of JsonResponse since $data is not a json but an array that you want to be converted into a json. Using a JsonResponse will return a proper JsonResponse with json headers, the bool $json parameter just help converting a php variable into a json (if possible).
/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data);
}

You could also simplify your foreach (The arrow key function is php 7.4+, use a regular callable otherwise):
/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = array_map(fn($e) => $e->getName(), $teams);

    return new JsonResponse($data);
}

It depends of you, but you could also use FOSJsRoutingBundle to not write manually the path to your teams route. You can check how to use it if you want.


text:
Q: Sync of Master Master replication when Primary node comes up MySQL 5.7 Enterprise I have a Master (say Node A) - Master (Say Node B) asynchronous replication setup with ROW based logging method.
Node A has been setup as Write/Read node and Node B has been setup as Read Node Only.
From JBOSS , i am doing switch over that , when A node goes down , all the Write operation will get forward to B node and whenever Node A comes up , JBOSS will forward all the Writes to A node.
Now suppose Node A remains down for long time , then all the Writes will go to B node . When A node comes up , it will remain un-sync for a while till it get complete sync with B . While it is getting sync , write operation is also happening on Node A which might result in locking issues as well.
So my question is :
Is there any method in MySQL that when Node A comes up , it will not be accessible by outer application ( like JBOSS , i have mentioned) till it gets complete sync with Node B .
Can we control it via MySQL_Safe mode so that other application can perceive Node A as still down or is there any other method

A: Do not write to the formerly-down side until replication is "caught up".
In your scenario, the formerly-down Master will eventually catchup.  Wait.  Only if it can't catch up, or you find corruption of some kind, should you go to the effort of copying the data over and rebuilding.  If you want to seriously worry about that, have a Slave hanging off each Master for such recovery purposes.
SET GLOBAL read_only = ON whenever a server is not the writable master.  In fact, have that as the default in my.cnf on both servers.  That way, if there is, say, a brief power failure that causes the writable master to reatart, you won't be able to write to it until you get in there to see what the situation really is.
"Split brain" is the worst thing that can happen.  This is when the network is dead, but both Masters are alive and each thinks that the other Master is dead (because of the network).  Both happily take writes that will cause duplicate key problems later.  Avoid that at all cost.
In general Master-Master, even when writing to only one Master at any time, is the least desirable HA solution.  See "Group Replication" and "Galera" for better solutions.  (But not "Fabric", it seems to be dying.)


text:
Q: update the dataframe value based on if condition i've this snippet (help got my stackoverflow) .
First this is looping into file and splitting based on new line and appending to a list and converting the list into dataFrame and dataFrame to excel.
But my problem is in the third Output column. i wanted to check for a string and if that string contains [Hi sai] it should be same if this string is not present it should update that column as no string found.
Snippet
import pandas as pd
import re

with open(r'report.txt', 'r') as f_in:
    text = f_in.read()

pat = re.compile(r"(?<=\*\*\*$).*?(?=^\*\*\*)", flags=re.S | re.M)

out = []
for group in map(str.strip, pat.findall(text)):
    out.append(group.split("\n", maxsplit=2))

df = pd.DataFrame(out, columns=["ID", "Name header", "output"])

df.to_excel(r'/final_report.xlsx', index=False)

The above only parses the file and appends list but it not checking for the condition.
i tried with this but not sure where to put this. Any help?
if df[~df["output"].str.contains("Hi Sai")]:
    df['output']="No value found"
else:
    pass
``

A: You should be able to do:
df.loc[~df["output"].str.contains("Hi Sai"),"output"] = "No value found"

A: You can use "map":
def set_output(o):
    if not (str(o).__contains__('Hi Sai')):
         return "No value found"
    return o

df['Output']=df['Output'].map(set_output)


text:
Q: Three dimensional associative array for Json? After several attempts, I have to ask for some help to solve this. Below I have some plain JSON:
{
    "test": {
        "r1": [{
            "id": 1,
            "status": true
        }, {
            "id": 2,
            "status": true
        }],
        "r2": [{
            "id": 1,
            "status": false
        }, {
            "id": 2,
            "status": false
        }]
    }
}

This works fine with javascript when I'm reading from a simple .txt file, but I want to create this JSON from PHP. I can make a two dimensional associative array, but for this it seems that I need a three dimensional associative array, and I can't solve that! Could someone give me a hint how that would look or alternative solutions?

A: Here's an embracing example with your data on how to convert from JSON object (string) to PHP array and vice-versa.Hope this makes things clear for you.
<?php

// Original JSON object string
$jsonstring = '{
    "test":{
        "r1":[{
            "id":1,
            "status":true
        },{
            "id":2,
            "status":true
        }],
        "r2":[{
            "id":1,
            "status":false
        },{
            "id":2,
            "status":false
        }]
    }
}';

// Convert JSON string to PHP array
// This can be used by a PHP script to work on
$phparray = json_decode($jsonstring);
echo '
PHP array converted from JSON string

'; var_dump($phparray); echo '
';

// Convert it back to JSON string to prove it's the same
$jsonstring1 = json_encode($phparray);

// Now we create a PHP array corresponding to original JSON string, manually
$phparray = array (
    "test"=> array (
        "r1" => array(
            array(
                "id"=>1,
                "status"=>true
            ),
            array(
                "id"=>2,
                "status"=>true
            )
        ),
        "r2" => array(
            array(
                "id"=>1,
                "status"=>false
            ),
            array(
                "id"=>2,
                "status"=>false
            )
        )
    )
);

// Convert PHP array to JSON string
// This can be sent to a browser where it can be used by Javascript
$jsonstring2 = json_encode($phparray);

echo '
Original JSON string
' . $jsonstring;
echo '
After conversion to array and back
' . $jsonstring1;
echo '
Converted from PHP array
' . $jsonstring2;

?>


text:
Q: Linear Transformation of Tetrahedron Rotation Consider the tetrahedron with vertices $(1,1,1), (-1,-1,1), (1,-1,-1)$, and $(-1,1,-1)$. Give the standard matrices for each of the following symmetries of the tetrahedron. Check that each of the matrices is an orthogonal 3∗3 matrix.
a) $+/- 120$ degree rotations about the line joining $(0,0,0)$ and $(1,1,1)$ (vertex)
b) 180 degree rotation about the lines joining $(0,0,1)$ and $(0,0,-1)$
c) Reflection across the plane containing one edge and the midpoint of the other edge (not sure what this means)
I did not learn linear algebra from a geometric perspective and I don't even know where to start. Any advice or links to useful videos are appreciated.

A: Hint:
Let's say you have a linear transformation $T:\mathbb{R}^n \rightarrow \mathbb{R}^n$.
For convenience, denote $\mathbf{x}_i = T(\mathbf{e}_i)$, where $\mathbf{e}_i$ is the $i$th standard basis vector.  So, for example, $\mathbf{e}_1 = \langle 1, 0, 0 \rangle$ in $\mathbb{R}^3$.  Likewise, $\mathbf{e}_2 = \langle 0, 1, 0 \rangle$, etc.
Then $T$ is encoded by the $n \times n$ matrix $[\mathbf{x}_1, \mathbf{x}_2, \cdots, \mathbf{x}_n]$.

As a simple example, consider a $90^\circ$ counterclockwise rotation about the origin in $\mathbb{R}^2$.  Note that $\langle 1, 0 \rangle \mapsto \langle 0, 1 \rangle$, and further $\langle 0, 1 \rangle \mapsto \langle -1, 0 \rangle$.  So our linear transformation is encoded by the matrix $\left[ \begin{array}{ccc}
0 & -1 \\
1 & 0
\end{array} \right]$.

Now applying this to solve your problem will be a bit of work, but if I'm not mistaken, the standard basis vectors lie on the midpoints of edges of this tetrahedron, and edges will map to edges.  It'll be your task to figure out precisely where they are mapping to.

Another approach:
Let $\mathbf{v}_1, \mathbf{v}_2, \mathbf{v}_3$, and $\mathbf{v}_4$ denote the vertices of your tetrahedron.  Let $T$ be one of the given linear transformations.  Then $T(\mathbf{v}_1) = \mathbf{v}_i$ for some $i$, and so forth.  In this manner you can arrive at a system of equations whose solution yields the entries of the matrix encoding $T$.


text:
Q: What components should I use for a bicycle generator? I know next to nothing about electronics, ergo any help is gratefully received.
I'm trying to build the bicycle generator in this Instructables guide, but there is no specification. I have so far found a 24V 280W scooter motor that could work, but:

*

*What model of diode should I connect to it and the battery?

*What kind of battery would be best?

*What specification of inverter would I need for small applicances eg. 2kW fan heater, kettle, phone charger? (i.e. pure sine wave/modified sine wave etc.)

A:
I have so far found a 24V 280W scooter motor that could work

The important thing is to have the motor rotate at a suitable RPM so it makes enough voltage. If it turns too slow, you won't get any usable output. So you'll need to investigate about the motor's rpm rating when powered by, say, 12V, and possibly build some gearing, perhaps using belts. You could use a small wheel pushed against the bike's rear wheel, but that creates a lot of losses due to friction. I'd recommend using a used electric bicycle wheel motor, because that fits nicely in a bicycle wheel, it's got the proper rpm, and it's most convenient.

What model of diode should I connect to it and the battery?

Schottky diode has lower voltage drop, so that would be best.

What kind of battery would be best?

If you don't know what you're doing, don't use lithium. Maybe lead-acid.

What specification of inverter would I need for small applicances eg. 2kW fan heater, kettle, phone charger? (i.e. pure sine wave/modified sine wave etc.)

An amateur cyclist can generate 100-200W for a few hours. Someone who doesn't exercise will do it for maybe a few minutes.
In other words, if you use a 12V battery, a car USB charger will be nice for your phone, there's no need to go from 12V to mains voltage back to 5V. Likewise for laptops.
As for the kettle and the 2kW fan heater, forget about it, you'd need 10-20 cyclists. Although, if you just want to heat the room with human power, you don't need anything fancy, just a stationary bike. The built-in brake converts the cyclist's energy output into heat without the extra cost of going through electricity, and since the human metabolism is only about 25% efficient, the cyclist will make 3x as much heat as the bike anyway. This will be cheaper than burning fuel only if food calories are cheaper than fuel calories, which is not a given.
Note it is not possible for anyone to produce 200W on a stationary bike (or do any kind of high-power exercise) for any length of time indoors without a fan to cool them. Without wind, they will simply overheat. So if you do build this, you will most likely use the generator to power a fan. In this case, for a mains powered fan, you need a pure sine wave inverter.


text:
Q: gluLookAt is not working properly I'm trying to make the camera follow an object. Here's a dummy of my Camera class:
public void setView(GL2 gl){
    double[] myPos = MyObject.getCoords();
    double[] myTarget = MyObject.getTarget();
    double myRotation = MyObject.getRotation();

    double viewX = myPos[0]+(myTarget[0]*0.1);
    double viewZ = myPos[2]+(myTarget[1]*0.1);
    double camHeight = Terrain.altitude(myPos[0],myPos[2]) + 0.3;
    GLU glu = new GLU();
    gl.glPushMatrix();
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();

    gl.glDisable(GL2.GL_LIGHT1);
    //Look at where the object is looking from behind the object
    glu.gluPerspective(100, aspect, 0.1, 20);
    System.out.println("Teapot pos" + myPos[0] + myPos[2]);
    System.out.println("Eye pos" + (myPos[0]-myTarget[0]) + (myPos[2]-myTarget[1]));
    glu.gluLookAt(-(myPos[0]-myTarget[0]),-camHeight,-(myPos[2]-myTarget[1]), viewX, camHeight, viewZ, 0, 1, 0);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();
    gl.glPopMatrix();
}

And here is the dummy code in my MyObject class:
public static void draw(GL2 gl) {

    GLUT glut = new GLUT();

    gl.glPushMatrix();
    //Draw a teapot
    gl.glTranslated(-coords[0],-coords[1], -coords[2]);
    gl.glRotated(-Math.toDegrees(rotation),0,1,0);
    glut.glutSolidTeapot(0.1);
    gl.glPopMatrix();
}

To make MyObject move, the codes are like this in MyObject class:
// move object
public void translate(double displacement) {
    coords[0] += displacement*Math.sin(Math.toRadians(rotation));
    coords[2] += displacement*Math.cos(Math.toRadians(rotation));
    coords[1] = Terrain.altitude(coords[0], coords[2]);
}

// Rotate camera by degrees
// Target is the vector where MyObject is facing
public void rotate(double rot) {
    rotation += rot;
    target[0] = -Math.sin(Math.toDegrees(rotation));
    target[1] = -Math.cos(Math.toDegrees(rotation));
}

Whenever I print the coordinates without rotating everything seems working fine. After the rotation it is not working properly. For some reason, the camera and the object are moving in different directions. The rotation is kind of weird as well because sometimes I cannot see the teapot. Can anyone help me out with this problem?


text:
Q: I can't scape a particular sentence in Ansible I have the following problem.
I am creating a playbook in Ansible for the installation of OCSInventory, at the time of executing the script the interaction begins to define certain parameters, for this I have used the Expect module, within these questions there is one in particular that I cannot successfully create the escape of the characters, then I share the information.
Although originally they use single quotes, you have to assign double quotes, according to the message delivered by the ansible log
enter image description here
'To ensure Apache loads mod_perl before OCS Inventory NG Communication Server,Setup can name Communication Server Apache configuration file ""z-ocsinventory-server.conf"" instead of ""ocsinventory-server.conf"". Do you allow Setup renaming Communication Server Apache configuration file to ""z-ocsinventory-server.conf"" ([y]/n) \?': ''
And this is the mistake, I tried different ways, without results, if someone could give me some advice.
enter image description here
  "+----------------------------------------------------------------------+",
    "|     OK, Communication server plugins Perl directory created ;-)      |",
    "|                                                                      |",
    "|               Now configuring Apache web server...                   |",
    "+----------------------------------------------------------------------+",
    "",
    "To ensure Apache loads mod_perl before OCS Inventory NG Communication Server,",
    "Setup can name Communication Server Apache configuration file",
    "'z-ocsinventory-server.conf' instead of 'ocsinventory-server.conf'.",
    "Do you allow Setup renaming Communication Server Apache configuration file",
    "to 'z-ocsinventory-server.conf' ([y]/n) ?"

A: You can use lookup plugin to load tricky text into variables.
vars:
  prompt: '{{ lookup("file", "tricky_prompt.txt") }}'

Save the text you want to load into files/tricky_prompt.txt.
Than just use variable prompt everywhere you need your text.