text:
Q: free membership on register by domain On our site we have it so that our posts are only visible to paid subscribers. But we want users with certain email address domains to, when they register, be able to view every post we have without having to pay for it. We use the paid memberships pro plugin on wordpress and they have these to bits of code in their documentation that allows us to automatically assign membership on sign up and to restrict sign up to certain domains. They both work as intended on their own but when we tried the combine them it didn't work. We don't really know any php, so we're just moving lines around to where we think makes sense. The third bit of code is our attempt to combine them. Does anyone have any suggestions on how they can be put together?
/* When registering, add the member to a specific membership level
 * @param integer $user_id*/
//Disables the pmpro redirect to levels page when user tries to register
add_filter("pmpro_login_redirect", "__return_false");
function my_pmpro_default_registration_level($user_id) {
//Give all members who register membership level 1
pmpro_changeMembershipLevel(1, $user_id);
}
add_action('user_register', 'my_pmpro_default_registration_level');

function restrict_email($value)
{
    $email = $_REQUEST['bemail'];

    if(!check_validity($email))
    {
        global $pmpro_msg, $pmpro_msgt;
        $pmpro_msg = "Please enter a valid email address";
        $pmpro_msgt = "pmpro_error";
        $value = false;
    }
    return value;
}
add_filter('pmpro_registration_checks','restrict_email', 10, 1);
//Taken from: http://www.bitrepository.com/how-to-extract-domain-name-from-
an-e-mail-address-string.html
function getDomainFromEmail($email)
{
// Get the data after the @ sign
    $domain = substr(strrchr($email, "@"), 1);

    return $domain;
}
function check_validity($email)
{
    $domain = getDomainFromEmail($email);

    $valid_domains = array("yahoo.com", "*.gmail.com", "*.domain.uk");
    foreach($valid_domains as $valid_domain)
    {
        $components = explode(".", $valid_domain);
        $domain_to_check = explode(".", $domain);

        if($components[0] == "*" && sizeof($domain_to_check > 2))
        {
            if($components[1] == $domain_to_check[1] && $components[2] == $domain_to_check[2])
            {
                return true;
            }
        }
        else
        {
            if(!(strpos($valid_domain, $domain) === false))
                return true;
        }
    }
    return false;
}

add_filter("pmpro_login_redirect", "__return_false");
function restrict_email($value)
{   $email = $_REQUEST['bemail'];

    if(!check_validity($email))
    {   global $pmpro_msg, $pmpro_msgt;
        $pmpro_msg = "Please enter a valid email address";
        $pmpro_msgt = "pmpro_error";
        $value = false;
    }
    return value;
}
add_filter('pmpro_registration_checks','restrict_email', 10, 1);
function getDomainFromEmail($email)
{    // Get the data after the @ sign
    $domain = substr(strrchr($email, "@"), 1);
    return $domain;
}
function my_pmpro_default_registration_level($user_id) {
function check_validity($email)
{   $domain = getDomainFromEmail($email);

    $valid_domains = array("ipqpubs.com", "ipqpubs.org");
    foreach($valid_domains as $valid_domain)
    {   $components = explode(".", $valid_domain);
        $domain_to_check = explode(".", $domain);

        if($components[0] == "*" && sizeof($domain_to_check > 2))
        {   if($components[1] == $domain_to_check[1] && $components[2] == $domain_to_check[2])
            {
                pmpro_changeMembershipLevel(1, $user_id);
            }}
        else
        {
            if(!(strpos($valid_domain, $domain) === false))
                return true;
        }}

    return true;
}
add_action('user_register', 'my_pmpro_default_registration_level');
}

A: If you are looking to run pmpro_changeMembershipLevel(1, $user_id) when the domain is ipqbubs.com or .org, you have a couple of issues here. For one, you'll want to put that function under the strpos line. As it is, that function will never run because nothing in your valid_domains array contains "*" (represents a subdomain). Second, $user_id is not in scope for check_validity. Please try something more like this:
function my_pmpro_default_registration_level($email, $user_id) {
    $domain = getDomainFromEmail($email);
    $valid_domains = array("ipqpubs.com", "ipqpubs.org");
    foreach($valid_domains as $valid_domain) {
       if(strpos($valid_domain, $domain) !== false)
       {
          pmpro_changeMembershipLevel(1, $user_id);
          return true;
        }
     }
}


text:
Q: Finding vector perpendicular to R3 plane What I know about the surface is that it has point (1,1,2) and 2 vectors [1,2,3] and [3,4,5]
How do I solve this? :<

A: Hint:  Given two vectors $v$ and $w$ in $\mathbb R^3$, the crossproduct $v\times w$ will give a normal to all planes that are parallel to each of $v$ and $w$ (provided $v$ and $w$ are not parallel).  This will help you to determine the equation of this parallel class of planes, and the given point will determine the plane you want uniquely.
The simplest equation for a plane is the so-called scalar form:
$$A(x-x_0) + B(y-y_0) + C(z-z_0)=0$$
where $\langle A,B,C\rangle$ is any normal to the plane, and $(x_0,y_0,z_0)$ is any point on the plane.

A: Just some hint, I might expand my answer later. From having the point $A(1,1,2)$ and vectors $ \mathbf{u} = [u_1,u_2,u_3]=[1,2,3]$ and $\mathbf{v} = [v_1,v_2,v_3] = [3,4,5] $ you obtain parametric expression of the plane $\tau \in \mathbb{R}^3$. That means $\tau = A + t\mathbf{u} + s\mathbf{v}$, where $t, s \in \mathbb{R}$ are scalars. In coordinates:
\begin{align*}
x &= 1 + t\cdot 1 + s \cdot 3\\
y &= 1 + t\cdot 2 + s \cdot 5\\
z &= 2 + t\cdot 3 + s \cdot 6\\
\end{align*}
So, by specifying $t, s$ you can get every point from the plane. But for plane we have another expression called implicit expression, which looks something like this $ax+by+cz+d = 0$. The point I am trying to make is, that if we took $(a,b,c) = \mathbf{n}$ we get a normal vector of the plane $\tau$, which is, as you might have guessed already, perpendicular to $\tau$.
And more, every other vector perpendicular to the plane $\tau$ we get by multiplying $\mathbf{n}$ by any scalar.
Transforming back and forth between parametric and implicit expression is another question, but I think there is plenty of material covering that topic, and it is one o'clock in the morning in my country, so I better be going.

A: I would start from the parametric equations of the plane:
$$x = 1 + 1\lambda + 3\mu $$
$$y = 1 + 2\lambda + 4\mu$$
$$z = 2 + 3\lambda + 5\mu$$
and then solve for $\mu$ and $\lambda$...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Amazon AWS login error on port 443 I am trying to login to my Amazon AWS instance and I am getting this error.
        debug1: Connection established.
        debug1: identity file VOIPSystemServer.pem type -1
        debug1: identity file VOIPSystemServer.pem-cert type -1
        debug1: Enabling compatibility mode for protocol 2.0
        debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2
        debug1: ssh_exchange_identification: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

        debug1: ssh_exchange_identification:

        debug1: ssh_exchange_identification: <title>400 Bad Request</title>

        debug1: ssh_exchange_identification:

        debug1: ssh_exchange_identification:
Bad Request

        debug1: ssh_exchange_identification:
Your browser sent a request that this server could not understand.

        debug1: ssh_exchange_identification:

        debug1: ssh_exchange_identification:

        debug1: ssh_exchange_identification: <address>Apache/2.4.7 (Ubuntu) Server at ip-172-31-20-234.ap-southeast-2.compute.internal Port 80</address>

        debug1: ssh_exchange_identification:

        ssh_exchange_identification: Connection closed by remote host

I have changed the port to 443, but I cannot login at all. I do not recall putting the HTTP server on port 443, so is this fixable?

A: SOLVED, I re-booted the server instance and it started working again. Sorry to post a redundant question. Not sure what the problem was, but an instance reboot was the solution.


text:
Q: WebSphere MQ Viewing Channels in WMQ Explorer We need to execute SET AUTHREC PROFILE($cname) OBJTYPE(CHANNEL) GROUP('mq-user') AUTHADD(...) so that the channels show up WMQ Explorer, it that correct? Current the access is prevented.

A: Yes.  With the AUTHREC profiles defined in this and previous questions you have authorized the user to connect to the QMgr, put requests to the command queue and receive replies on a model queue.  The command server needs to know what operations on other objects the group is authorized for.  As an example, it won't display or let members of the group control channels until you authorize them.
A quick way to see what objects need to be authorized is the Role Based Authorities Wizard in WMQ Explorer.  Right-click on the QMgr, select Object Authorities, then Add Role Based Authorities like so:

Next, select Group and put in the group name:

The wizard outputs setmqaut commands which you can issue from the command line as mqm. There are equivalent AUTHREC commands for these.  Rather than convert them manually, I'd recommend running the setmqaut versions, then capturing the rule using the dmpmqcfg command.
The actual commands created in the wizard using the settings above are:
setmqaut -m QM75_1 -t qmgr -g mq-user +connect +inq +dsp
setmqaut -m QM75_1 -n "**" -t q -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t topic -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t channel -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t process -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t namelist -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t authinfo -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t clntconn -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t listener -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t service -g mq-user +dsp
setmqaut -m QM75_1 -n "**" -t comminfo -g mq-user +dsp

setmqaut -m QM75_1 -n SYSTEM.MQEXPLORER.REPLY.MODEL -t q -g mq-user +dsp +inq +get
setmqaut -m QM75_1 -n SYSTEM.ADMIN.COMMAND.QUEUE -t q -g mq-user +dsp +inq +put


text:
Q: Symfony: Get FormType Name From Variable In my project, when I change the select, a ajax call gets a new select element and replaces it with my current one.
See page for reference.
So basically, my Ajax calls /ticket/owner-select to get the owner options. Everything works perfectly.
This is my controller for the url:
//TicketController.php

...

/**
 * @Route("/ticket/owner-select", name="app_ticket_owner_select", methods={"GET"}, condition="request.isXmlHttpRequest()")
 */
public function getTicketOwnerSelect(Request $request, DepartmentRepository $departmentRepository)
{
    $department = $departmentRepository->findOneBy(['id' => $request->query->get('value')]); //gets id from get-parameter

    if(!$department) {
        return new Response(null, 204); //return empty response if no department selected or found
    }

    $ticket = new Ticket();
    $ticket->setDepartment($department);
    $form = $this->createForm(TicketType::class, $ticket);

    if(!$form->has('owner')) {
        return new Response(null, 204); //return empty response
    }

    return $this->render('ticket/select.html.twig', ['form' => $form->createView()]); //render the select element with correct options
}

...

Now I want to reuse the exact same url for other FormTypes, since I have multiple forms where the owner changes depending on another select field.
Example:
$form = $this->createForm(TicketType::class, $ticket);
$form = $this->createForm(AnotherTicketType::class, $ticket);
$form = $this->createForm(AnotherAnotherTicketType::class, $ticket);

So the FormType should be dynamic. Probably the best way would be another get parameter, but I'm not quite sure how to do that and especially check if that type even exists (error handling).
Reason: The controller would look the same for every select-field on every ticket form. Since I do not want duplicated code (most part), I want to create a dynamic solution.
Mabye someone could help me.
Thanks in advance.

A: You are already passing parameters to the controller via query string in your ajax request (the id parameter) so I assume you know how to add a new parameter, let's say type.
Since ::class just returns a string with the fully qualified class name, you can just use this new parameter to build your FormType class and instance it normally. In case the requested type doesn't exist, createForm will throw InvalidArgumentException.
$ticketType = $request->query->get('type', ''); // Set 'main' type if not specified
$ticketFormType = 'App\Form\' . $ticketType . 'TicketType';

$ticket = new Ticket();

try {
    $form = $this->createForm(TicketType::class, $ticket);
} catch (Symfony\Component\Form\Exception\InvalidArgumentException $e) {
     // FormType doesn't exist
     return new Response(null, 400);
}

return $this->render('ticket/select.html.twig', ['form' => $form->createView()]);

A: What about a hidden field with the type?


text:
Q: Adding xml-stylesheet at the second line of the xml string how to add style sheet at the second line of the xml file, i have write the code but it add the style-sheet on the first line of my xml String file, please see my code it is working code but it add the stylesheet at the first line of xml string and my requirment is to add xml-stylesheet at the second line of xml string please help
public class StringToDocumentToString {

    public static void main(String[] args)
            throws TransformerConfigurationException {
        String xmlstring = null;
        String filepath = "E:/C-CDA/MU2_CDA_WORKSPACE/AddingStylesheetTOxml/documentfile.txt";
        final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
                + "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"
                + "<role>Developer</role><gen>Male</gen></Emp>";

        Document doc2 = convertStringToDocument(xmlStr);
        Document doc1 = null;
        try {
            doc1 = addingStylesheet(doc2);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str = convertDocumentToString(doc1);
        System.out.println(str);
    }

    private static <ProcessingInstructionImpl> Document addingStylesheet(
            Document doc) throws TransformerConfigurationException,
            ParserConfigurationException {

        ProcessingInstructionImpl pi = (ProcessingInstructionImpl) doc
                .createProcessingInstruction("xml-stylesheet",
                        "type=\"text/xsl\" href=\"cda.xsl\"");
        Element root = doc.getDocumentElement();
        doc.insertBefore((Node) pi, root);
        return doc;

    }

    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
            // "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(new InputSource(new StringReader(xmlStr)));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }
}

A: Before transforming
transformer.transform(new DOMSource(doc), new StreamResult(writer));

try with the below output properties,
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");


text:
Q: subset rows in dataframe using combinations of conditions I have a data frame:
table = structure(list(Plot = 1:10, Sp1 = c(0L, 0L, 1L, 1L, 0L, 1L, 0L,
                                    0L, 1L, 0L), Sp2 = c(1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L),
               Sp3 = c(1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 0L), Sp4 = c(0L,
                                                                        1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA,
                                                                                -10L))

0 represents a species (Sp) being absent from a plot. 1 represents a species being present.
First, I want to subset my data frame so that only plots with Sp1 or Sp3 or Sp4 remain. This can be done easily with filter from dplyr:
reduced_table <- table %>% filter(table$Sp1 == 1 |table$Sp3 == 1 | table$Sp4 == 1)

But, what if I want to reduce the table so that only plots that have any combination of two of these species is present. For example plots with Sp1 & Sp3, or Sp1 and Sp4, or Sp3 and Sp4 would remain.
Can this be done eloquently like using filter? My real situation has many more species and therefore many more combinations so explicitly writing out the combinations is not ideal.

A: We can use if_any with filter
library(dplyr)
table %>%
   filter(if_any(c(Sp1, Sp3, Sp4), ~ .== 1))

-output
#   Plot Sp1 Sp2 Sp3 Sp4
#1    1   0   1   1   0
#2    2   0   0   1   1
#3    3   1   1   1   1
#4    4   1   0   1   0
#5    5   0   0   1   1
#6    6   1   0   0   0
#7    7   0   1   1   0
#8    8   0   0   1   1
#9    9   1   0   0   1

Or using a combnation of columns
library(purrr)
combn(c("Sp1", "Sp3", "Sp4"), 2, simplify = FALSE) %>%
  map_dfr( ~ table %>%
         filter(if_all(.x, ~ . == 1))) %>%
  distinct

If the intention is to do filtering on pairwise column checks, use combn from base R
subset(table, Reduce(`|`, combn(c("Sp1", "Sp3", "Sp4"), 2,
  FUN = function(x) rowSums(table[x] == 1) == 2, simplify = FALSE)))


text:
Q: how to convert a running process into a nohup and keep a logfile I have a process currently occupying a terminal
]$ command some_argument

I want to exit from the terminal and go home, but in the mean time I don't want to kill this running process.
For the above running process, I want to achieve something like the following:
]$ nohup command some_argument >& logfile &

A: Disowning the process and redirecting STDOUT from an already backgrounded process isn't feasible for most users. This SO answer covers the topic pretty well.
Disassociating the process from the current shell isn't so hard: you're looking for disown. From the manpage:
SIGNALS

....

       The shell exits by default upon receipt of a SIGHUP.   Before  exiting,
       an  interactive  shell  resends  the  SIGHUP  to  all  jobs, running or
       stopped.  Stopped jobs are sent SIGCONT to ensure that they receive the
       SIGHUP.   To  prevent the shell from sending the signal to a particular
       job, it should be removed from the jobs table with the  disown  builtin
       (see  SHELL  BUILTIN  COMMANDS  below)  or marked to not receive SIGHUP
       using disown -h.

....

SHELL BUILTIN COMMANDS

....

       disown [-ar] [-h] [jobspec ...]
              Without options, each jobspec  is  removed  from  the  table  of
              active  jobs.   If jobspec is not present, and neither -a nor -r
              is supplied, the shell's notion of the current job is used.   If
              the -h option is given, each jobspec is not removed from the ta‐
              ble, but is marked so that SIGHUP is not sent to the job if  the
              shell  receives a SIGHUP.  If no jobspec is present, and neither
              the -a nor the -r option is supplied, the current job  is  used.
              If no jobspec is supplied, the -a option means to remove or mark
              all jobs; the -r option without  a  jobspec  argument  restricts
              operation  to running jobs.  The return value is 0 unless a job‐
              spec does not specify a valid job.

If you want to learn more about what nohup and disown actually do, you can check out this question. (disclaimer: shameless self-promotion)

A: I understand you are currently using a Linux based OS but for the record and in case someone happening to use Solaris 10 or newer find this page while looking for a solution, Solaris nohup implements what you are looking for:
$ command some_argument
...
^Z[1] + Stopped (SIGTSTP)        command some_argument
$ bg
[1]     command some_argument&
$ jobs -l
[1] + 1061       Running                 command some_argument
$ nohup -p 1061
Sending output to nohup.out
$ exit

A: Looks like you are close:
 nohup sh custom-script.sh > custom-out.log &

From here


text:
Q: AdMob banner in fragments so I have made an app and now Im putting ad banners here. I followed this tutorial https://firebase.google.com/docs/admob/android/quick-start and everything works fine but I want to put banners to my fragments too. I was looking here on website and I found this to put to fragment
    MobileAds.initialize(getApplicationContext(), "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx");

    AdView mAdView = (AdView)findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

but when i click on fragment afterwards the app stop working
Im total beginner in this.

A: Put bellow code in xml layout file
 <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

Where banner_ad_unit_id is your ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxx
To crate ad unit id follow bellow link
  https://support.google.com/admob/answer/3052638

Add dependancy in build.gradle file

compile 'com.google.firebase:firebase-ads:10.0.0'

Now to display Ads write bellow code in Activity
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);


text:
Q: Code Style scheme and import order in IntelliJ not working In the project I am working on at the moment we have an Eclipse XML Profile  CodeStyle scheme that I have to use.
We also have to do our imports in a certain order. I have imported the codestyle and set Code Style to that scheme. Also under Java Imports I have set the order in which imports should be placed.
However, if I now do optimize imports, it keeps ordering it in the wrong way. It appears not even according to the default setting. I have tried moving around the order in the default setting, and it changes some imports, but not everything in the order it should.
I have also tried copying the settings to the project scheme, and set it to that. But that also doesn't work.
For example the order includes

*

*nl.*

*org.*

*others

If I do optimize imports it is ordering like

*

*org.*

*lombok. (other)

*nl.*

Is there any setting I am missing that blocks it using the order of the assigned scheme?
IntelliJ is up to date to the newest version.
Eclipse Code Formatter plugin is installed.
screenshot of imports as requested:


text:
Q: How to Specify Interbase Service Name with TIBRestore Per the Interbase Operations Guide, GBAK allows the IB server location to be specified like this:
-se localhost:service_mgr
Or if we were remoting to a server named "test" we could specify:
-se test:service_mgr
This would restore the data local to server "Test", or in the former example it would restore on the machine you're running the restore on which would give better performance.
How can this be specified in TIBRestore? There is a protocol property with TCP or Local. Does specifying the local protocol use localhost service_mgr? Or is it controlled by passing localhost as the server name?

A: If you're on a server named "jupiter" restoring to a server named "pluto" over a TCP/IP connection:
gbak -r user -joe -pass blurf@ -se jupiter:service_mgr /backup/foo.ibk pluto:/companydb/foo.ib

From what I recall, you can also use a TCP/IP address, instead of the destination server name (i.e., 10.20.30.254 instead of pluto). That part is not really stated as such in the documentation but works on TCP/IP.
See the official examples for examples.


text:
Q: If I set the build architecture as 32bit in Xcode, do my app runs on 64bit machines? A basic question about building in 32/64 architecture with Xcode
If I set the build architecture as 32bit in Xcode, do my app runs on 64bit machines?
Is it going to run much slower?

A: Yes, 32 bit apps run just fine on 64 bit OS X. They may run slightly faster or slower in certain cases, but the difference is generally negligible. The only real limitation is the size of your virtual address space, i.e. 4 GB for a 32 bit app.


text:
Q: Matlab print -dpdf produces fuzzy lines I have a problem when printing a 2D plot to pdf in matlab. I'm trying to print the following plot to a file (pdf, eps, svg, doesn't matter):

The problem is that at some points the line is very "jiggly" (sorry for the lack of a better word). I zoomed in on the upper part so you can see what I mean:

This is obviously not a problem for the matlab figure window. But when I print it to pdf, this is what it looks like:

The result is identical for pdf, svg and eps. I guess the problem is that matlab is creating a vectorized path (that is good!) but the path line is too thick and then every little spike can be seen.
Here's the code I'm using to produce the pdf:
sTitle = 'trajectory';
sFile = 'Data/trajectory.mat';
sPdfFile = 'pdfs/trajectory.pdf';
linewidth = 1;
fontsize1 = 18;

fig = figure;

% Adjust figure window size
set(fig, 'Position', [100 100 1400 800]);

% Set title
title(sTitle);

% Get states
[s, t] = load_data(some_data);

% Draw trajectory
plot(s(1,:), s(2,:), 'linewidth', linewidth);

% Labels and stuff
xlabel('x^W [m]', 'fontsize', fontsize1);
ylabel('y^W [m]', 'fontsize', fontsize1);
set(gca, 'fontsize', fontsize1)

% Axis font
set( gca                       , ...
    'FontName'   , 'Helvetica' );

set(gca, ...
  'Box'         , 'on'     , ...
  'TickDir'     , 'out'     , ...
  'TickLength'  , [.02 .02] , ...
  'XMinorTick'  , 'on'      , ...
  'XGrid'       , 'on'      , ...
  'XMinorGrid'  , 'off'     , ...
  'YMinorTick'  , 'on'      , ...
  'YGrid'       , 'on'      , ...
  'XColor'      , [.3 .3 .3], ...
  'YColor'      , [.3 .3 .3], ...
  'XTick'       , -5:1:5, ...
  'XTickLabelMode', 'auto', ...
  'YTick'       , -5:1:5, ...
  'LineWidth'   , 1         );

% Adjust view
axis([-2.5 2.5, -2.7 0.5]);

% Correct data aspect ratio
daspect([1,1,1])

% Print to PDF
width = 10;
height = 5;
set(gcf, 'PaperPosition', [0 0 width height]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [width height]); %Set the paper to have width 5 and height 5.
print('-dpdf', '-r600', sPdfFile);

A: According to this answer, this is an acknowledged bug, and the answerer provided a function to correct the issue for EPS files.
Since you are creating a PDF, I'd suggest using export_fig (requires a Ghostscript install) which, on the test script below, creates a smooth line in the produced PDF.
clc();
clear();

figure(1);

% Get states
n  = 800;
x = linspace(0,2*pi,n);
s = [x.*cos(x);x.*sin(x)] + 0.3*exp(-0.3*[x;x]).*(rand(2,n)-0.5) ;

% Draw trajectory
plot(s(1,:), s(2,:), 'linewidth', 1);
axis([-20,20,-20,20]);
daspect([1,1,1])

% Print to PDF
print('traj.pdf','-dpdf', '-r600');
export_fig('traj2.pdf','-dpdf','-r600');

print PDF output:

export_fig PDF output:


text:
Q: How to convert hexBinary (MsgId) to character in esql? I'm trying to put MQMD.MsgId to XMLNSC.MsgId field, like this:

SET OutputRoot.XMLNSC.Root.MsgId = InputRoot.MQMD.MsgId;

But I'm getting X'414d51204d39392e5352442e4330302e56c47bd4203b3708' instead of just 414d51204d39392e5352442e4330302e56c47bd4203b3708.
Also i've tried to cast MsgId to CHARACTER, but result is the same.
How to get rid of quotes and 'X'?

A: I don't have enough reputation to 'add a commment' yet, but working with so many languages, I've learned to dislike SUBSTRING and LENGTH type functions. In the case of answer 'Feb 28 2016 at 10:41' above (yes I found this answer in response to my own search - for the "CAST(InputRoot.MQMD.MsgId AS CHAR)" above, I chose to use this instead:
DECLARE MsgId CHAR RIGHT(LEFT(CAST(InputRoot.MQMD.MsgId AS CHAR),50),48);

This assumes MsgId is always 24 hex pairs long (24x2=48) and goes for LEFT 50 first (taking off the last single quote), then RIGHT 48 (taking off the first X char and the first single quote). Does anyone disagree with the assumption? It also has the bonus of condensing to one line as it's not necessary to have two references to "MsgId" in 'SUBSTRING'

A: You could try something like this:
DECLARE msgId CHARACTER CAST(InputRoot.MQMD.MsgId AS CHARACTER);
SET OutputRoot.XMLNSC.Root.MsgId = SUBSTRING(msgId FROM 3 FOR LENGTH(msgId) - 3);

A: With ESQL SUBSTRING you can also use BEFORE and AFTER
DECLARE MsgIdAsChar CHAR SUBSTRING(SUBSTRING(CAST(InputRoot.MQMD.MsgId AS CHAR) AFTER '''') BEFORE '''');

BEFORE and AFTER are also extremely handy when it comes to looking for things in strings.
DECLARE TheHaystack CHAR 'Where a value is 99 out of a maximum value of 100);
DECLARE TheValue CHAR SUBSTRING(SUBSTRING(TheHaystack AFTER 'value is ') BEFORE ' ');


text:
Q: Android Save RSA Private and Public Key I need to save my RSA private and public key. Here I create it.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();

Now I want to use both keys the next time. So they should be stored on the device.
        byte[] publicKeyBytes = publicKey.getEncoded();
        byte[] privateKeyBytes = privateKey.getEncoded();

So I can get the Byte Arrays and then I save them as a text file.
Then the next time i read it and convert it back to the byte Array.
Now my question: How can i convert a byte array back to a key?
This does not really work:
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
    publicKey = keyFactory.generatePublic(spec);
    spec = new X509EncodedKeySpec(privateKeyBytes);
    privateKey = keyFactory.generatePrivate(spec);

On LogCat, this is going to be display:

Must use RSAPublicKeySpec or PKCS8EncodedKeySpec; was
  java.security.spec.X509EncodedKeySpec

Any ideas whats wrong with this code?
Thanks for your help.

A: Try using PKCS8EncodedKeySpec for the private key.
RSAPublicKeySpec for the public key, instead of X509EncodedKeySpec for both.
Please also note that saving keys to a text file might not be the most secure idea. Android provides a nice KeyStore Api, which is easy to use.

A: You try encode the keys in Base64 and stored like a String, when you retrieved only need decoded the keys from Base64 to Byte arrays.


text:
Q: Get last date in variable in a long data format in R I have a long data format, where I need to create a variable with the last date for each id.
Example data
id <- c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3)

event_date <- c("2000.01.11",
                "2000.02.11",
                "2000.03.08", #id_max for id 1

                "2018.06.15",
                "2018.07.07",
                "2018.08.10", #id_max for id 1
                "2018.07.15",

                "2020.01.19",
                "2020.02.19", #id_max for id 1
                "2020.01.15")

df <- tibble::tibble(id, event_date)

# This is what I want:
df$id_max <- c("2000.03.08","2000.03.08","2000.03.08",
            "2018.08.10","2018.08.10","2018.08.10","2018.08.10",
            "2020.02.19","2020.02.19","2020.02.19")

Thanks in advance

A: Convert event_date to Date column and get max date for each id.
library(dplyr)

df %>%
  mutate(event_date = as.Date(event_date, '%Y.%m.%d')) %>%
  group_by(id) %>%
  dplyr::mutate(id_max = max(event_date))

#      id event_date id_max
#   <dbl> <date>     <date>
# 1     1 2000-01-11 2000-03-08
# 2     1 2000-02-11 2000-03-08
# 3     1 2000-03-08 2000-03-08
# 4     2 2018-06-15 2018-08-10
# 5     2 2018-07-07 2018-08-10
# 6     2 2018-08-10 2018-08-10
# 7     2 2018-07-15 2018-08-10
# 8     3 2020-01-19 2020-02-19
# 9     3 2020-02-19 2020-02-19
#10     3 2020-01-15 2020-02-19

A: I do not use to much dplyr or tibble. I prefer data.table. But this is made with base R.
id <- c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3)

event_date <- c("2000.01.11",
            "2000.02.11",
            "2000.03.08", #id_max for id 1

            "2018.06.15",
            "2018.07.07",
            "2018.08.10", #id_max for id 1
            "2018.07.15",

            "2020.01.19",
            "2020.02.19", #id_max for id 1
            "2020.01.15")
#Get max() number in date row
md<-aggregate(df$event_date,by=list(id),max)

####OPTIONAL###
#Force date conversion substituting (.)
df["good_date"]<-gsub("\\.","-",event_date)
########

#Finally Create column with max date
merge(df,md,by.x=1,by.y=1)
#    id event_date          x
#1   1 2000.01.11 2000.03.08
#2   1 2000.02.11 2000.03.08
#3   1 2000.03.08 2000.03.08
#4   2 2018.06.15 2018.08.10
#5   2 2018.07.07 2018.08.10
#6   2 2018.08.10 2018.08.10
#7   2 2018.07.15 2018.08.10
#8   3 2020.01.19 2020.02.19
#9   3 2020.02.19 2020.02.19
#10  3 2020.01.15 2020.02.19

#Or if you made de as.Date() conversion

md<-aggregate(df$good_date,by=list(id),max)
merge(df,md,by.x=1,by.y=1)
#    id event_date  good_date          x
#1   1 2000.01.11 2000-01-11 2000-03-08
#2   1 2000.02.11 2000-02-11 2000-03-08
#3   1 2000.03.08 2000-03-08 2000-03-08
#4   2 2018.06.15 2018-06-15 2018-08-10
#5   2 2018.07.07 2018-07-07 2018-08-10
#6   2 2018.08.10 2018-08-10 2018-08-10
#7   2 2018.07.15 2018-07-15 2018-08-10
#8   3 2020.01.19 2020-01-19 2020-02-19
#9   3 2020.02.19 2020-02-19 2020-02-19
#10  3 2020.01.15 2020-01-15 2020-02-19


text:
Q: Proper way to do polling in swift? I have lot of experience with other programming languages, but not so much in swift 3. I want to do polling loop. This is what i have written:
DispatchQueue.global(qos: .userInitiated).async {
            [unowned self] in
            while self.isRunning {
                WebService.getPeople(completion: nil)
                sleep(100)
            }
        }

This works fine for me, every 100 seconds, i do polling, and then make this thread sleep. What I am wondering, is this correct way to do this in swift 3?

A: Swift 5, iOS 10.0+
The code in the accepted answer no longer compiles, it can be modified (and simplified!) into:
DispatchQueue.global(qos: .userInitiated).async {
    let timer = Timer.scheduledTimer(withTimeInterval: 100, repeats: true) { timer in
        // Your action
    }
    timer.fire()
}

A: Swift 4 & Swift 5
 var timer: Timer? //declare outside function scope
 var runCount = 0

 self.timer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.fireTimer), userInfo: nil, repeats: true)

 guard let timer = self.timer else {return}
 RunLoop.main.add(self.timer, forMode: RunLoop.Mode.default)

 @objc func fireTimer() {
         print("Timer fired! \(runCount)")
        runCount += 1

        if runCount == 5 {
            timer?.invalidate() //stop the timer
        }
    }

OR
self.timer = Timer.init(timeInterval: 1.0, repeats: true, block: { (timer) in
        print("\n--------------------TIMER FIRED--------------\n")
        runCount += 1
        if runCount == 5{
          timer.invalidate()
    }
    })
guard let timer = self.timer else {return}

RunLoop.main.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode)

A: You have 2 options:

*

*Use NSTimer

*Use a DispatchSourceTimer
Using NSTimer is pretty easy, but it needs an active run loop, so if you need to poll on a background thread things could be a little bit tricky, because you will need to create a thread and keep alive a run loop on it (probably the timer itself will keep the run loop alive).
DispatchSourceTimer on the other hand works using queues. You can easily create a dispatch source timer from one of the system provided queues or create one.

    var timer: DispatchSourceTimer?
    let queue = DispatchQueue.global(qos: .background)
    guard let timer = DispatchSource.makeTimerSource(queue: queue) else { return }
    timer.scheduleRepeating(deadline: .now(), interval: .seconds(100), leeway: .seconds(1))
    timer.setEventHandler(handler: {
        // Your code
    })
    timer.resume()

The leeway arguments is the amount of time that the system can defer the timer.


text:
Q: C# & VSAEngine - Calculating a string expression with a exponent? i've a prob here, so i need a help:)
When i'm calculating expression like this "(10.5 + 3.5 / 2) * 2" with jscript vsa engine, it's ok, but now i 've a question...
if in the string like above, i want to calculate also an exponent (10.5 + 3.5 / 2) * 2 + exp(2), what is the best way to do it?
PS: Math.Exp(); -- is not an option.

A: If you are using jscript.net you can define exp function first and calculate expression after that. example was discussed for instance there

A: proper way to code this is to make your calculations in integer and then Convert.ToString() it


text:
Q: error C2665: 'cv::fillPoly' : none of the 2 overloads could convert all the argument types I get this strange error, where this code compiles (and displays a triangle correctly):
Point pts[3] = { Point(20, 20), Point(60, 20), Point(40, 40) };
const Point *ptsp = pts;
int npts[1] = {3};
fillPoly(img, &ptsp, npts, 1, Scalar(255, 255, 0));

But if I replace const Point *ptsp = pts; with Point *ptsp = pts, then I get this error:
1>C:\Workspace\ImageProcessing\Tutorials\src\main.cpp(16): error C2665: 'cv::fillPoly' : none of the 2 overloads could convert all the argument types
1>          C:\Workspace\ImageProcessing\opencv\build\include\opencv2/core/core.hpp(2632): could be 'void cv::fillPoly(cv::Mat &,const cv::Point **,const int *,int,const cv::Scalar &,int,int,cv::Point)'
1>          C:\Workspace\ImageProcessing\opencv\build\include\opencv2/core/core.hpp(2637): or       'void cv::fillPoly(cv::InputOutputArray,cv::InputArrayOfArrays,const cv::Scalar &,int,int,cv::Point)'
1>          while trying to match the argument list '(cv::Mat, cv::Point **, int [1], int, cv::Scalar_<_Tp>)'
1>          with
1>          [
1>              _Tp=double
1>          ]

But normally you should be able to pass non-const pointers where the function expects a const pointer, so why does it fail to work here?
I had used Point *ptsp = pts; at first, of course, and it took me quite some time and head-scratching to figure out it needs to be const, and it was totally unexpected for me.

A: This is explained here : http://www.parashift.com/c++-faq-lite/constptrptr-conversion.html

The reason the conversion from Foo** → Foo const** is dangerous is that it would let you silently and accidentally modify a const Foo object without a cast:
      class Foo {
      public:
        void modify();  // make some modification to the this object
      };
int main()
{
  const Foo x;
  Foo* p;
  Foo const** q = &p;  // q now points to p; this is (fortunately!) an error
  *q = &x;             // p now points to x
  p->modify();         // Ouch: modifies a const Foo!!
  ...
}

If the q = &p line were legal, q would be pointing at p. The next line, *q = &x, changes p itself (since q is p) to point at x. That would be a bad thing, since we would have lost the const qualifier: p is a Foo but x is a const Foo. The p->modify() line exploits p's ability to modify its referent, which is the real problem, since we ended up modifying a const Foo.


text:
Q: show div on other page angularjs I have a div with property information in india, if a user clicks on a button,
the page should be redirect on another page and my whole div should be copy
and open on another page

                            {{i.A}}

                            Available For {{i.B}}

                            Area {{i.C}} Security  Rs. {{i.F}}

                            Rental Unit In {{i.D}}

                                Features

                            {{i.E}}

this is my div
<button ng-click="click()">click to view data</button>

this is my button
what i need to do if i want to see the same data on other pages???

A: You need to create a server-side structural template which will generate the div. Example in PHP
function getViewData() {
    ?>
    <button ng-click="click()">click to view data</button>
    >?php
}

And you can add anywhere in your structure if you are using a PHP file like this:
<?php getViewData(); ?>

A: I will suggest you to go with a angular factory which contains the data that you are looking for and use the html template in the respective page.
Button code remains the same as
<button ng-click="click()">click to view data</button>

Create a new Angular Factory as below
angular.module('myApp').factory('appVariables',function(){
        var data2=[];
        return{
                data2,data2
        }
});

Your controller should contain the following click() method
angular.module('myApp').controller('appController',function($scope,appVariables){

        $scope.click=function(){
            appVariables.data2=$scope.data2;
        }
})

Go to the another page inject appVariables as a dependecy to the controller and you can get the same data2 across your app.
This code is genric as the information provided by you is very less.

A: I have put together a sample for you. I can't create multiple html pages. So you have to put them in different files.

var app = angular.module('sample', []);]
//JS1
app.controller('page1Controller', ['$scope','$http','$rootScope', function($scope, $http){

  $scope.page1 = {};
  $scope.page1.title  = "Page1";

  $scope.click = function(page){
    $rootScope.page = page;
  }

}]);

//JS2
app.controller('page2Controller', ['$scope','$http','$rootScope', function($scope, $http){

  $scope.init = function(){
    alert("alrt")
    $scope.page2 = $rootScope.page;
  }

}]);

{{page1.title}}

   <button ng-click="click(page1)">click to view data</button>

{{page2.title}}


text:
Q: Order by date when date is string in format is J F Y I'm trying to order query results in MYSQL by date. However the date is not in date format but a VARCHAR in J F Y e.g. 1st January 2020.
I've tried STR_TO_DATE() but that's not worked.
Any ideas?

A: Try the format - '%D %M %Y'
select str_to_date(yourdatecol,'%D %M %Y')


text:
Q: How do I make two independent actions inside one function? How can I make two independent action inside one function in Elm? Is there any pattern or explicit function?
Generally speaking I'm not sure how to implement ajax data loading inside Elm Architecture.
For example I'd like to make Http.get and return modified argument function like this
fetchCustomers model =
  Http.get parseCustomers "/customers" `andThen` setCustomers
  { model | fetchingCustomers <- True }

A: TL;DR
You do so by returning both in a tuple. Then you split the signal from your update in foldp, put the model part in the view function and put the tasks in a port to execute. This is alluded to in the Architecture post at the end under One Last Pattern.
Longer answer
Since you link to the Elm Architecture, let me link to that too, but in particular the last part: One Last Pattern.
What you want to do here is part of the "update" of your program, where you not only update your model but also do something else on the side. Therefore you do not just return the new model, but also the extra thing you want to do (in this case an Http request):
fetchCustomers model =
  ( { model | fetchingCustomers <- True }
  , Http.get parseCustomers "/customers" `andThen` setCustomers
  )

Instead of using StartApp like the architecture page does, you can paste in the start function from the package. Now you have access to the mailbox where the actions are coming from, so you can pass it to your update so you can send your Http results there too. And you can split the tuple that you're returning from the update function to actually execute the tasks:
start app =
  let
    actions =
      Signal.mailbox Nothing

    address =
      Signal.forwardTo actions.address Just

    model =
      Signal.foldp
        (\(Just action) (model,_) -> app.update actions action model)
        -- ignore task: ^     ^^^              ^^^^^^^^:add mailbox
        app.model
        actions.signal
  in
    (Signal.map (fst >> app.view address) model, Signal.map snd model)
--  ^           ^^^^^^^     :split model:      ^^^^^^^^^^^^^^^^^^^^^^^

fetchCustomers actions model =
  ( { model | fetchingCustomers <- True }
  , Http.get parseCustomers "/customers"
    `andThen` (SetCustomers >> Signal.send actions.address)
  -- use mailbox to send Http results as an input action again
  )

-- larger update function you probably have
update actions action model = case action of
  -- ...
  SetCustomers cust -> setCustomers cust
  -- ...
  -- fetchCustomers actions model

(output, tasks) = start { model: model, view: view, update: update }

-- task execution:
port httpGets = tasks

-- output your view
main = output

You can find more examples of doing Http on the website under "tasks".


text:
Q: Complex function mapping Suppose $f(z)$ is an entire function,
And let $\zeta$ be jordan arc s.t endpoints of the arc $z_1=0$ and $z_2=\infty$. Prove that function is constant if $f(\mathbb{C})\cap\zeta$=empty
I thought this was obvious, but after thinking for a while i need some clarifications:
1.by louvilles theorem entire+bounded=constant. Jordan arc is the image of bounded and closed set, so the image is also bounded and closed under continuous map.Then conditions of louville satisfied.
2.but the arc takes an infinite value.
Since the intersection of the arc with complex plane under mapping is empty. It means the interval of real line was mapped to the arc.
3.now how to proceed and show that f is constant?

A: Picard's Theorem says that that the range of any non-constant entire function is all of $\mathbb C$ or $\mathbb C \setminus \{c\}$ for some complex number $c$. Since your arc has more than one point the result follows.
Ref.: https://en.wikipedia.org/wiki/Picard_theorem


text:
Q: autocomplete filter by category id - jquery i try to make autocomplete filter by category, like this

autocomplete has been success showing result when i entire id by manual, but when i try to get id by category id, id can't get id
this is my code javascript
$(function() {
  $(".keyword").autocomplete({
    source: function(request, response) {
      $.ajax({
          url: "search/autocomplete",
          type: "GET",
          dataType: "json",
          data: {'id':$("#cate").change(function () {
            var end = this.value;
        })
        },
          success: function(data) {
              response($.map(data, function(item) {
                return {
                  label: item.value,
                  value: item.value
              };
              }));
          }
      });
    },
    select:function(event,ui) {
      $(".keyword").val(ui.item.label);
      return false;
    },
    minLength: 2,
    select: function(event, ui) {
      window.location = "/lessons/" + ui.item.value;
  }
  }).bind('focus', function () {
    $('.ui-autocomplete').css('z-index','9999').css('overflow-y','scroll').css('max-height','300px');
    // $('.ui-autocomplete').css('background','#09121a').css('color','#fff');
    // $('.ui-menu .ui-menu-item-wrapper').css('padding','11px 1em 3px 1.4em !important');
    // $(this).autocomplete("search");
    // var btncategory = $('.btn-category').width();
    // var left = '-'+btncategory+'px';
  });
});

this is my html

             id.'" href="javascript:void(0)"  onclick="changeCategory(''.$category->title.'')">'. $category->title.'

              Semua Kategori

can anyone help me?

A: You are trying to set the id to the result of adding a change handler which isn't going to work. The data for the $.ajax call can only be an object, string, or array. What you should do is setup the event handler separately to handle the change, store the data, and trigger the autocomplete manually. Give this a try:
let autocompleteData = {};

$("#cate").change(function () {
    autocompleteData.id = this.value;
    $(".keyword").autocomplete("search");
};

$(".keyword").autocomplete({
    source: function(request, response) {
    $.ajax({
        url: "search/autocomplete",
        type: "GET",
        dataType: "json",
        data: autocompleteData
    },

The idea is to have your data be an object that always exists. It is initially set to an empty object so it will have no result. Whenever your category id changes, it sets the id property of that object to its value and triggers an autocomplete event. Whenever the autocomplete code is run it just uses whatever the current state of the autocompleteData object is, so it should always be passing the category id as part of the call.


text:
Q: Download in angular 8 a txt Good, I wanted to have a button on the page that when I pressed it would download a file in txt that I have saved, I have found the function saveAs but it gives me errors, is there another way to make it easier?
Code:
uploader: FileUploader;
    download(){
       saveAs(this.uploader, 'data.txt');
     }

HTML:
<button (click)="download()" class="btn"><i (click)="download()" class="fa fa-download"></i> Download</button>

The error that gives me with the saveAs:

TextAnomComponent.html:42 ERROR TypeError: Failed to execute
  'createObjectURL' on 'URL': No function was found that matched the
  signature provided.

A: First, you need to make sure that this.uploader is blob type.
If everything is right, then you to check window.navigator.msSaveOrOpenBlob existing on your browser or not
if not then create a link to do download.
if (window.navigator.msSaveOrOpenBlob) {
  window.navigator.msSaveBlob(this.uploader, "data.txt");
}else {
  const downloadLink = window.document.createElement('a');

  // get the this.uploader file type and put in type below
  downloadLink.href = window.URL.createObjectURL(new Blob([this.uploader], { type: ... }));

  downloadLink.download = "data.txt";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

Hope this help!


text:
Q: Searching an NSArray o strings with an NSDate Hard to get the headline correct since there is so much to tell.
I got this NSArray (A portion of it):
Mon, 06:00, Radioshow Morning, Mon, 10:00, Lunch radio, 14:00, Afternoon Radio and so on.
The NSArray is from an plist in the app.
What I need to build (and failed with) is a search function that shows me the right program with these search values:
searchDay and searchTime
Both those values are from NSDate.
I've been Googling for about and hour now and hasn't come up with anything usefull so my last hope stands to stackoverflow to show me what I am missing.
I've been dabbling with dateFromString, compare, timeIntervalSinceNow but for some reason failed to achive what I am about to do.
Greatful for any help givven.
TIA
Mattias

A: You should use an NSArray of NSDictionary objects instead of various object types in your NSArray:
NSDictionary *morningShow = [NSDictionary dictionaryWithObjectsAndKeys:@"Mon",@"day","10:00",@"time","morning",@"name",nil];

Then add that to your array.  Then, when you are searching, you have a uniform data structure to search inside of.

A: I think I have solved it.
But I must say I am intrigued by phooze answer.
The way I am doing it now is reading the values (NSString) from the array converting them into an NSDate object and comparing those with timeIntervalSinceDate.
By that I can figure out if currentTime is between two times in the array and such I know what show is on. I've just come up with the solution, the base code is working but the whole code isn't done yet, just on paper/in my mind.
But it feels like a somewhat ugly code... lots of doing small things.
But I will pre sue this to the end and if it still looks inefficient and ugly I will look in to other solutions.


text:
Q: grid kendo ui edit create delete I have page  mvc   cshtml
it contains an begin  beginform:
@using (Html.BeginForm("ValiderLeChangement", "FichePersonnel", FormMethod.Post , new { id = "FormValider" }  ))
{
}

inside this form i have put grid kendo ui  in this kendo grid  i want to use
create add and delete like example in Kendo  UI DEMO   ( http://demos.kendoui.com/web/grid/editing-inline.html)
i ve probleme  with the action of  create or  delete or edit don't fire on server
my code  is  :
@(Html.Kendo().Grid(Model.ListeContact)
    .Name("Grid")
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .ToolBar(toolbar => toolbar.Create())
    .Columns(columns =>
    {
        columns.Bound(p => p.Nom).Title("Nom").Width(20);
        columns.Bound(p => p.Prenom).Title("Prenom").Width(20);

        //columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20).ClientTemplate(????? );
        columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20);

        columns.Bound(p => p.Tel).Title("Telephone").Width(20);

        columns.Command(command => { command.Edit(); }).Width(30);
        columns.Command(command => { command.Destroy(); }).Width(30);
      /////////  columns.Bound(p => p.IdContact).ClientTemplate("#= Delete(data) #").Title("Supprimer").Width(5);
    })
    .Sortable()
    .DataSource(dataSource => dataSource
    .Ajax()
    .Batch(true)
    .ServerOperation(true)
    .Events(events => events.Error("error_handler"))
    .Read(Read => Read.Action("ListeContact_Read", "FichePersonnel"))
        .Model(model => model.Id(p => p.IdContact))
        .Create(create => create.Action("EditingInline_Create", "FichePersonnel"))
        .Update(update => update.Action("EditingInline_Update", "FichePersonnel"))
        .Destroy(delete => delete.Action("EditingInline_Destroy", "FichePersonnel"))

    )
)

A: How have you implemented your controller action method? Does it handles the request and return properly? It should be something like this:
public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
    {
        if (product != null && ModelState.IsValid)
        {
            SessionProductRepository.Insert(product);
        }

        return Json(new [] { product }.ToDataSourceResult(request, ModelState));
    }

Note the first argument DataSourceRequest and teh return type Json. Maybe that's what you're missing. Also I noticed that you're indicating ServerOperation(true). As far as I understand, you should not need that if you are using AJAX Binding as you are.
EDIT:
And so for the controller code, something like this:
    public partial class TextosController : EditorImageBrowserController
{
    public ActionResult ReadTextos([DataSourceRequest]DataSourceRequest request)
    {
        CostSimulatorModel modelo = new CostSimulatorModel(new Uri(@"http://localhost:53212/CostSimulatorModelService.svc/"));

        IQueryable<Texto> textos = modelo.Textos;
        DataSourceResult resultado = textos.ToDataSourceResult(request);
        ViewData["Textos"] = textos;
        return Json(resultado, JsonRequestBehavior.AllowGet);
    }
    public ActionResult CreateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
    {
        if (ModelState.IsValid)
        {
            CostSimulatorModel modelo = new CostSimulatorModel(new Uri(@"http://localhost:53212/CostSimulatorModelService.svc/"));

            // Create a new Product entity and set its properties from the posted ProductViewModel
            Texto entity = new Texto
            {
                TextoID = texto.TextoID,
                Titulo = texto.Titulo,
                Corpo = texto.Corpo,
                IsPrivado = texto.IsPrivado,
                TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
                TiposTexto = texto.TiposTexto
            };
            modelo.AddToTextos(entity);
            // Insert the entity in the database
            modelo.SaveChanges();
            // Get the ProductID generated by the database
            texto.TextoID = entity.TextoID;
            return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
        }
        // Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
        return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
    }

    public ActionResult UpdateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
    {
        if (ModelState.IsValid)
        {
            CostSimulatorModel modelo = new CostSimulatorModel(new Uri(@"http://localhost:53212/CostSimulatorModelService.svc/"));

            // Create a new Product entity and set its properties from the posted ProductViewModel
            var entity = new Texto
            {
                TextoID = texto.TextoID,
                Titulo = texto.Titulo,
                Corpo = texto.Corpo,
                IsPrivado = texto.IsPrivado,
                TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
                TiposTexto = texto.TiposTexto
            };
            // Attach the entity
            modelo.AttachTo("Textos", entity);
            modelo.UpdateObject(entity);
            // Update the entity in the database
            modelo.SaveChanges();
            return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
        }
        // Return the updated product. Also return any validation errors.
        return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
    }

    public ActionResult DestroyTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
    {
        if (ModelState.IsValid)
        {
            CostSimulatorModel modelo = new CostSimulatorModel(new Uri(@"http://localhost:53212/CostSimulatorModelService.svc/"));

            // Create a new Product entity and set its properties from the posted ProductViewModel
            var entity = new Texto
            {
                TextoID = texto.TextoID
            };
            // Attach the entity
            modelo.AttachTo("Textos", entity);
            // Delete the entity
            modelo.DeleteObject(entity);

            // Delete the entity in the database
            modelo.SaveChanges();
            return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
        }
        // Return the removed product. Also return any validation errors.
        return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
    }
}


text:
Q: delete operator for instances holding other instances I have a question regarding delete operator. In case there are 3 instances each holding the next/previous instance how to delete it?
class A : public Parent
{
privte:
  A* next;
  A* previous;
public:
  void setNext(A*);
  void setPrevious(A*);
};

..
int main()
{
  A* obj1 = new A();
  A* obj2 = new A();
  A* obj3 = new A();

  obj1->setNext(obj2);
  obj2->setNext(obj3);
  obj3->setNext(nullptr);

  obj1->setPrevious(nullptr);
  obj2->setPrevious(obj1);
  obj3->setPrevious(obj2);

  return 0;
}

if I delete obj1.. obj2 and obj3 get deleted auotmatically. Why? Is this a memory leak? Are they actually deleted? I don't understand such behaviour. Shouldn't there be a delete for every new?

A: You have to think of resource ownership issues. You have make some policy decisions. Then write code that confirms to that policy.
After you execute:
obj1->setNext(obj2);

who owns obj2? Is obj2 owned by obj1? Is it owned by the calling function or a higher level object?
If your policy says that obj1 owns obj2, then, you have to delete obj2 when you delete obj1.
If your policy says that the calling function or a higher level object owns obj2, then you must not delete obj2 when you delete obj1.
You asked:

if I delete obj1.. obj2 and obj3 get deleted auotmatically. Why?

Because you did not write the code to delete them.

Is this a memory leak?

Yes.

Are they actually deleted?

No.

I don't understand such behaviour. Shouldn't there be a delete for every new?

Yes. there should. However, you have to make sure that delete is called on each object returned from new.
If your policy is that obj1 owns obj2 after the above mentioned call, you have to implement the destructor of A to delete next and previous. However, you have to make sure that the links are properly taken care of before you do that. Otherwise, you will run into pointers that have already been deleted, you will run into memory leaks if you don't take care of traversing the links correctly.
~A()
{
   // Hopefully next->previous points to this.
   // You have to unlink next from this. Otherwise, 'delete next' will end up calling
   // delete on 'this`.
   // Similarly with previous

   if ( next != nullptr )
   {
       next->previous = nullptr;
      delete next;
   }

   if ( previous!= nullptr )
   {
       previous->next= nullptr;
      delete previous;
   }
}

You still have to call
delete obj1;

in main to make sure that all the objects are deleted.
If your policy is that the calling function or a higher level object owns objt2 after the statement
obj1->setNext(obj2);

you have to call delete on all the objects from the calling function.
int main()
{
  A* obj1 = new A();
  A* obj2 = new A();
  A* obj3 = new A();

  obj1->setNext(obj2);
  obj2->setNext(obj3);
  obj3->setNext(nullptr);

  obj1->setPrevious(nullptr);
  obj2->setPrevious(obj1);
  obj3->setPrevious(obj2);

  delete obj3;
  delete obj2;
  delete obj1;

  return 0;
}

To make this a little cleaner, you should deal with a higher level container that is analogous to std::list. You add and remove items from the list. When the list is deleted, it has to make sure that all the contained elements are deleted too.


text:
Q: volume of the parallepiped spanned by the vectors Hi I am having difficulty with part (2) of the following proposition.
Suppose that $x,y,z\in\mathbb{R}^3$, then
(1) $\|x\times y\|=\|x\|\|y\|\sin\theta$ is the area of the parallelogram spanned by the vectors $x$ and $y$, where $\theta$ is the angle between them.
(2) $$ |(x\times y)\cdot z|=\left|\text{det}\left( \begin{array}{ccc}
z_1 & z_2 & z_3 \\
x_1 & x_2 & x_3 \\
y_1 & y_2 & y_3 \end{array} \right)\right|$$ is the volume of the parallelepiped spanned by th vectors.
The solution is the following

I am fine with everything except the last two lines of the proof of (2). Could anyone help me to see how could
$$A\cdot\frac{(x\times y)\cdot z}{\|x\times y\|}=A\|z\|\cos \alpha?$$

A: $u \cdot v = \|u\|\|v\|\cos \alpha$, where $\alpha$ is the angle between $u$ and $v$ is a well-known formula. Indeed, I have often seen it used as the definition of the dot product. In this case $ u = x \times y$ and $v = z$.


text:
Q: iCloud Photo Library on Macbook Pro, where? I have iCloud Photo Library enabled on both iPhone 5S (IOS 8.02) and Macbook Pro (Yosemite)
iPhone settings for iCloud (Photo Library) reports that I have 3 photos in iCloud
(gallery only shows 1 photo (?), but otherwise it seems to sync to icloud fine when taking a new picture)
Where are these photos located excactly (icloud), and how can I see/use them on my Macbook?

A:
iCloud Photo Library is available starting 2015 on OS X

Until now, you have the chance to

*

*sync between iOS devices running both iOS 8 and have Photo Library activated.

*activate Photo stream and see your photos in iPhoto

iCloud Photo Library is still Beta, and will come to the Mac in 2015, and to the icloud.com as well.

A: As for now, the only way to access iCloud Photo Library on a non-iOS device is https://beta.icloud.com/.


text:
Q: Bazel options in BUILD file I need to set some build options every time I invoke bazel for a specific target. For example, bazel build --collect_code_coverage //:target. How can I avoid providing the build options at the command line explicitly, so that bazel build //:target implicitly has the build option --collect_code_coverage applied?
The closest solution I found was using the bazelrc file, but it does not allow me to configure build options at a target level.

A: This is doable with user defined transitions, there are some performance considerations here that are worth reading over. It's also relatively complicated.
# transition.bzl
def _platform_transition_impl(settings, attr):
    _ignore = settings
    return {"//command_line_option:collect_code_coverage": True}

coverage_transition = transition(
    implementation = _coverage_transition_impl,
    inputs = [],
    outputs = ["//command_line_option:collect_code_coverage"],
)

def _coverage_impl(ctx):
    executable = ctx.actions.declare_file(ctx.attr.name)
    ctx.actions.symlink(output = executable, target_file = ctx.file.target)
    return [DefaultInfo(executable = executable)]

build_with_collect_coverage = rule(
    implementation = _coverage_impl,
    attrs = {
        "target": attr.label(mandatory = True, allow_single_file = True, cfg = coverage_transition),
        "_allowlist_function_transition": attr.label(
            default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
        ),
    },
)

Then add the transition rule to BUILD.bazel e.g.
load(":transition.bzl", "build_with_collect_coverage")
cc_binary(
   name = "target"
   #...
)

build_with_collect_coverage(
   name = "target_with_coverage_collection",
   target = ":target",
)

Note: While this is a generic solution that is incredibly powerful and supports any language you might simply be able to get away with using the features attribute e.g.
cc_binary(
   name = "target",
   #...
   features = ["coverage"],
)


text:
Q: How to get the options elementId in Java Script, when the Id are Dynamically created by PHP?
Possible Duplicate:
How to get the selected value of dropdownlist using JavaScript?

I have a drop down list box, whose entries are dynamically populated from mysql using php.
Here is the snippet.
   <?php
        //include '../db/interface/DB_Manager.php';
        $connect = mysql_connect("localhost", "root", "infinit") or die(mysql_error());
        mysql_select_db("serverapp") or die(mysql_error());

        $query = "select id,name from rpt_shift_def"; //Write a query
        $data = mysql_query($query);  //Execute the query
    ?>
    <select id="selectShift" name="selectShift" onchange="ready(this.value)">
    <?php
    while($fetch_options = mysql_fetch_array($data)) { //Loop all the options retrieved from the query
    ?>

    <option id ="<?php echo $fetch_options['id']; ?>"  value="<?php echo $fetch_options['name']; ?>"><?php echo $fetch_options['name']; ?></option><!--Echo out options-->
    <?php
        }
    ?>
    </select>

Now i want the values in the option id's to pass it to the Mysql query to use those values as filters(those ID's are UUID of Mysql used here as Primary Keys).
If the id's are static i can use document.getElementById("ID"); to get those values, since it was PHP echo's, i can not use document.getElementById().
How to get the values in echo'ed in the ID in Javascript.

A: Thanks to Marwan Alsabbagh, The use of options[e.selectedIndex].value solves my Problem.
   select = document.getElementById("selectShift");
   select.onchange = function(){
        var options = this.getElementsByTagName("option");
        optionHTML = options[this.selectedIndex].value;
   }


text:
Q: MySql insert syntax error Sry but I just don't understand what is wrong in my syntext, can you help me?
"insert into users2(id,first_name,last_name,full_name,email,password,validation_key) ('1a9a14aa-cc87-4365-ab6a-2501b4e70d06','Name','Pass','NamePass','koko@lolol.com','OYJBYZw9IW0gLbkKSTXJeKTBYcRaNw0=','054eb292-0b9f-4219-830d-fadd1a8af7ad')"

A: You are missing VALUES
INSERT INTO users2
            (id,
             first_name,
             last_name,
             full_name,
             email,
             password,
             validation_key)
VALUES      ('1a9a14aa-cc87-4365-ab6a-2501b4e70d06',
             'Ilya',
             'Gazman',
             'IlyaGazman',
             'koko@lolol.com',
             'OYJBYZw9IW0gLbkKSTXJeKTBYcRaNw0=',
             '054eb292-0b9f-4219-830d-fadd1a8af7ad')

A: You forgot the values before the values.

A: You forgot VALUES:
INSERT INTO users2 (id, first_name, last_name, full_name, email, password, validation_key)
VALUES ('1a9a14aa-cc87-4365-ab6a-2501b4e70d06','Name','Pass','NamePass','koko@lolol.com','OYJBYZw9IW0gLbkKSTXJeKTBYcRaNw0=','054eb292-0b9f-4219-830d-fadd1a8af7ad')


text:
Q: Do we have any control over dates when using native datepickers in html5 web apps? Here's the scenario..
I am building a responsive website, which will take bookings - and as such I will need to restrict the dates available (not too complex, simply disable a handful of dates a month).
I traditionally achieve this functionality with Jquery Datepicker, but when trying to create a smooth experience for mobile users - the native datepickers (eg iphone spinning wheels) provide a much nicer interface than Jquery Datepicker on the mobile platform.
So my question is, is there any way at all to manipulate the dates that are shown (like disable a specific date) within native datepickers?
If not, can anyone recommend a good cross browser datepicker as a fallback for mobile devices that doesn't weigh a tonne.

A: sadly the native HTML5 <input type="date"...> doesn't support any formatting or restrictions. You are best sticking with jQuery or similar to control both styling and validation


text:
Q: video not displaying on the the vfpage Video not display on the page
    <apex:page docType="html-5.0">
      <head>
          <script src="//api.html5media.info/1.1.8/html5media.min.js"></script>
      </head>
      <body>
          <video width="100%" controls="controls" autoplay="true">
              <source src="{!URLFOR($Resource.Video,'sample.mp4')}" type="video/mp4" />

          Your browser does not support the video tag.
    </video>
  </body>
</apex:page>

A: Try this code
<apex:page >
    <apex:iframe scrolling="true" frameborder="true" src="{!URLFor($Resource.videotest,'VideoTest.mp4'}"/>
</apex:page>

It is working fine for me


text:
Q: Inputs along with characters in C++ I have been trying to write a prog which accepts college fees as input in the form Rs50000 and i would like to use only the integral part for the computation. How can i do that??
Is this possible??
#include<iostream>
using namespace std;
int main()
{
   int fee;
   cin >> Rs >> fee;
   return 0;
}

A: In order to read the string and process it as you've described, the following should work.
std::string input;
std::cin >> input;
int fee = atoi(input.substr(2).c_str());

This code takes input from stdin. Then it parses the fee (3rd character to end) as an int.
There are, of course, other ways to do this. I am a fan of c_str() and atoi() because of a background in C, however a stringstream is just as capable.
A note on your original code. It may be natural to think that you would stream in twice:
std::cin >> Rs >> fee; because one part is a string and the other is an int. However, std::cin streams are delimitated by whitespace.
Hope this helps!

A: Yes it's possible and there are lots of ways to do what you want, here's one way.
Take input as a string and remove "Rs" using substr(). Then convert it to int.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    stringstream stream;
    string amount,str;
    int fee;
    getline (cin, amount);
    str = amount.substr(2);
    stream << str;
    stream >> fee;

    cout << "Fee is : " << fee+1 << "\n"; //fee
    return 0;
}


text:
Q: How to use postman or http request to pass a user I have an asp.net core project, and one of my fields is set via User?.Identity?.Name.  I am wondering if there is a way to pass the identity through an http request, rather than logging into the site.  I've asked around quite a bit and nobody seems to have done this, although it makes sense to me that it's possible given that the web is stateless.  Any insight would be of interest.  Thanks!

A: It depends what Auth service are you using, if you're using OAuth 2.0 on .net core you need to loggin sending the params like Username and Password on the http request and then get the Access Token for the others http requests so postman has that option:

A: There's a ton of unknowns here, because your question isn't specific about really anything. Generally speaking, auth is typically handled by one of two principle means: a cookie or an Authorization header.
Cookie-based auth is the more traditional form of web auth. You submit a form on a login page with a username and password, the server receives that request and handles it by verifying the credentials, and if correct, sets a cookie via the Set-Cookie response header with an encrypted authentication ticket. On each subsequent request, the browser sends this cookie back to the server via the Cookie request header, decrypts and validates the authentication ticket, and if it's still valid, "restores" the authenticated session: i.e. recognizes the authenticated user.
APIs will typically auth via the Authorization request header, instead. The client generally first sends a request to an authentication endpoint with some set of credentials. That could be a username/password or it might be a client id/secret pair, etc. The server again validates the credentials, and if valid, returns a response containing a token. That token then is sent along with the actual request the client wants to make via the Authorization header like Authorization: Bearer {token}. There's other forms the header can take though. For example, you might instead use basic authentication, and instead of hitting an auth endpoint, first, you'd simple pass the username and password as a Base64 encoded string like Authorization: Basic {base64-encoded user:pass}.
Long and short, yes, something is always sent with the request to "authorize" it, whether a cookie or an Authorization header. However, what you send and how its handled is a function of how the app has been set up to handle authentication, and you haven't detailed any of that here. You can't just send an Authorization header with basic authentication, for example, if your app isn't explicitly set up to know that it needs to look for that and actually knows how to process it.
If you're using a cookie-based auth approach, you can mimic submitting the form by passing the same data the HTML form would to the same URL in the same way (x-www-form-urlencoded). The response would be the HTML of whatever page the user is taken to after, but the cookie will be in the Set-Cookie handler. You can capture this, and then send that along in the Cookie header of your request. You can do all this through something like Postman, but you still have to go through the authentication process, either way.
If you're dealing an API, then you should be using some other form of auth: basic, bearer, etc. However, again, you'll need to actually set this up.


text:
Q: SQLite merging multiple rows with different column values into one entry I am trying to merge the column values of multiple rows into one entry using SQLite:
ID   date        test Val1  Val2 Val3 val4  Val5 Val6

S1   2020/01/01  ECT   5     5     5     0    0    0

S2   2020/02/01  FCT   2     2     2     0    0    0

S1   2020/02/02  ECT   0     0     0     5    5    5

S2   2020/03/01  FCT   0     0     0     2    2    2

the result should be:
 ID    test Val1  Val2 Val3 val4  Val5 Val6

 S1    ECT   5     5     5     5    5    5

 S2    FCT   2     2     2     2    2    2

I tried group_concat but I can't get it to work. I don't want to create a view, rather I want to reduce to number of incomplete or "half-completed" entries for the same ID in the DB.
Also, if it helps, I am using python to store the values in the SQLite DB. So if there is a way of doing it through python instead, that would also be great. Any help/comments are welcome
I am quite new to SQL so any advice would greatly be appreciated!
Thank you

A: For this dataset, aggregation does what you want:
select id, test, max(val1) val1, max(val2) val2, max(val3) val3, max(val4) val4, max(val5) val5, max(val6) val6
from mytable
group by id, test

A: I am guessing that you have an aggregation query with date in the group by.  Something like this:
select ID, date, test, . . .
from . . .
group by ID, date, test;

Change the query to remove date from both the select and group by:
select ID, test, . . .
from . . .
group by ID, test;

A: You can use Data Dictionary in order to select dynamically the columns with val prefix within the first auxiliary query :
import sqlite3
con = sqlite3.connect('db123.db')
cur = con.cursor()

query1 = "SELECT cl.name FROM sqlite_master sm CROSS JOIN pragma_table_info(sm.name) AS cl "
query1+= " WHERE sm.type='table' AND sm.name='tab' AND UPPER(cl.name) like 'VAL%' "
cur.execute(query1)
ls=cur.fetchall()

agr=''
col=''
for i in ls:
    col=str(i[0])
    agr+=",MAX("+col+") AS "+col

query2  = "SELECT ID, test {} FROM tab GROUP BY ID, test".format(agr)
cur.execute(query2)

print(cur.fetchall())

con.close()

>>>

[('S1', 'ECT', 5, 5, 5, 5, 5, 5), ('S2', 'FCT', 2, 2, 2, 2, 2, 2)]


text:
Q: Laplace Transform of $f(t)=c$: Evaluating the limit of a product of functions, when one function has a complex number? When evaluating the Laplace Transform of $f(t)=c$, assuming $s$ is some complex number $s=\sigma+i\omega$
$F(s)=\frac cs(1-\lim_{T\to \infty}e^{-\sigma T}(\cos\omega T-i\sin\omega T)$
I can see that $e^{-\sigma T}$ will approach zero as long as $\sigma>0$ but $\cos\omega T-i\sin\omega T$ doesn't approach anything.
I know that the limit of $f(x)\cdot g(x)$ is the limit of $f(x)$ multiplied by the limit of $g(x)$, provided that both functions have a limit.
But in this case, only one of them has a limit (equal to zero), while the other is undefined.
My textbook says that $\lim_{T\to \infty}e^{-\sigma T}(\cos\omega T-i\sin\omega T)=0$  provided that $\sigma >0$
I don't have experience evaluating limits like this, what am I missing?

A: Since $|e^{xi}| = 1$ for all $x \in \mathbb R$ and $|e^a| = e^a$ for all $a \in \mathbb R$,
$$|e^{-\sigma T}e^{-\omega T i}| = |e^{-\sigma T}||e^{-\omega T i}| = e^{-\sigma T}$$ and this shows that the distance from $e^{-\sigma T}e^{-\omega T i}$ to the origin can be make arbitrarily small taking $T$ sufficiently large.


text:
Q: Integration of D365 with RabbitMQ using C# to Read and Write data in Queue I want to integrate RabbitMQ with D365 CRM to write/read data from/to Queue from D365
Is there any plugin or alternate to achieve this ?

A: Using RabbitMQ as a message broker in Dynamics CRM data interfaces
https://github.com/lucasalexander/Crm-Sample-Code#crmmessagequeuing


text:
Q: Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes? I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using random_bytes:
var_dump(bin2hex(random_bytes(12)));

--> string(24) "338f489ec37a2c2b4943905d"

and using openssl_random_pseudo_bytes:
var_dump(bin2hex(openssl_random_pseudo_bytes(12)));

--> string(24) "1c7febea20029bd524fba8e7"

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it's been around longer), and random_bytes is PHP 7. I'm using PHP 7 so I can use either.
So is there any major (or minor for that matter) difference between the two? If not, I'm tempted to go with random_bytes simply because it has an easier name ( = code that's easier to read).

A: Just to update, the cryptographic insecurity in openssl_random_pseudo_bytes was fixed in 2016. More details here:
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-8867
It usese RAND_bytes now, which OpenSSL recommends in its wiki:
https://wiki.openssl.org/index.php/Random_Numbers#FIPS_Mode

A: openssl_random_pseudo_bytes is part of the OpenSSL extension, which must be explicitly configured and included in the PHP compilation process and requires external dependencies.
random_bytes is new in PHP 7 as the native always-available PHP method to generate random bytes, which chooses its internal source of randomness depending on the platform it's on.
The main reason for introducing random_bytes was that generating pseudo-random data was always a bit of a headache in PHP, requiring developers to be platform-aware and possibly using several different fallback methods depending on which extensions or system-level functions are available. This often led to bugs in individual implementations, which is particularly concerning in security-relevant code. random_bytes simplifies this by providing one function which is always available and uses the best possible source of randomness available. If you can target PHP 7+ exclusively, it should be your go-to method.

A: According to php manual
random_bytes : Generates cryptographically secure pseudo-random bytes
openssl_random_pseudo_bytes : Generate a pseudo-random string of bytes
so main difference is the cryptographically secure

The openssl_random_pseudo_bytes() PHP function calls the
  RAND_psuedo_bytes() OpenSSL function, which the OpenSSL docs say
  should only be used for non-cryptographic purposes:

https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php


text:
Q: WPF Image doesnt show in application but doesnt have error in the code I am making an application where users can make an account and add a profile image. In my Main_Page I have an Image in the Main_Page.xaml.cs I am setting Image.Source = image. image is a BitmapImage. I get no compile errors so the image should be displayed. I did a watch on the path to the image and its correct! I will include code for reference.
 public Main_Page()
    {

        BitmapImage image = new BitmapImage(new Uri(Environment.CurrentDirectory + @"\Images\" + ApplicationServices.User.XMLFile.SelectSingleNode(@"User/ProfilePicture").InnerText.Trim(), UriKind.Relative));
        Profile_Image_Exercise.Source = image;
        Profile_Image_Nutrition.Source = image;
        Profile_Image_Statistics.Source = image;

    }

@EdPlunkett made a good point im new to WPF so could this be causing my issues?


text:
Q: Is it possible in nginx to rewrite a POST request into GET one? I want to get the POST variables with JS, but it can only catch GET variables. My idea is to rewrite an POST request into GET one. Is it possible?  The file is static html, and i don't wannt to use php or some script-language to do this.

A: Use reverse proxy. But its an extremely bad fix.


text:
Q: TCPServer socket in ruby I would like to establish a connection between 2 computers using socket. For this purpose one of them is a server and this is the code I've write:
sock= TCPServer.open('localhost', 6666)
sock.accept

the client try to establish the connection:
client = TCPSocket.open(ip_server, 6666)

but is not working. I've notice scanning server's ports that the server does not open the port to the network, only works in local mode.
Any suggestion, thk in advance

A: I've used this code successfully.  Server side:
serverSocket = TCPServer.new( "", port )
serverSocket.accept

and on the client
t = TCPSocket.new(server_ip, port.to_i)

However, recently I've started using the 'EventMachine' gem, which made handling sockets 10 times easier

A: It's already been said that the service is running in "Local Mode" using the loopback "localhost".
sock= TCPServer.open('localhost', 6666)
sock.accept

TCPServer is a handy interface for the underlying file descriptor. Frankly, it almost makes socket programming too easy.
Like what has already been said, 'localhost' is a loopback to 127.0.0.1. Therefore, your statement is equivalent to:
sock= TCPServer.open('127.0.0.1', 6666)
sock.accept

If you will be using the network connection on a local network, assuming the server has an assigned IP of 192.168.0.1, you can assign a local IP address to listen on:
sock= TCPServer.open('192.168.0.1', 6666)
sock.accept

For an open port, conceivably open to all, use:
sock= TCPServer.open(6666)
sock.accept

Remember that everything is a file – the connection you're making is reading and writing to the same file or series of files from two (or more) locations. It's important to control who might have access to those files, and to what extent.

A: Yes, and it allright so, because you said it should bind the server port to the interface of 'localhost' and this is 127.0.0.1 and is bind to your loopback interface and not to any real interface connecting to the realworld.
You should try
sock = TCPServer.new(6666)
sock.accept

A: It works in "local mode" because it listens on localhost wich is loopback address for the computer the server is launched in. The IP address of your server should be address your computer has on local network (something like 192.168.x.x).


text:
Q: How to make an object randomly spawn inside of the stage only My stage size is 640 x 1136
I want to spawn my objects randomly but only inside of the stage.
I used this
object.x = Math.random() * stage.stageHeight;

How can I make the x position spawn within the stage area?

A: You would want a "random in range" function like the one here
(included below).
However, if you are doing a game you may not be satisfied with the result of randomly spawning objects (e.g. objects piling up on each other, etc.) and want to exert more control. Lots of ways to be clever with that – like defining a set of regions or quadrants, picking one of those randomly and then generating random coordinates within that region, or having an array of defined "good" points and randomly selected from it. Actual randomness is often less interesting than the idea or appearance of randomness.
public function randRange(minNum:Number, maxNum:Number):Number {
   return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

A: TOMATO answer is the same as what you actually do so it's not really helpful. What you need to do is account for the object size. If you have an object that is at maximum 100 pixel wide then:
var size:Number = object.width;
object.x = size + Math.random() * (stage.stageWidth - size * 2);

This make sure the object spawn on the x axis inside the stage x axis. Same operation needs to be repeated for the y axis of course.


text:
Q: Q: go-jira: slice is not slicing strings in templates I try to get the date (2020-03-09) from "2020-03-09T08:09:40.000+0000" with this template line:
...   [Ticket:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ slice .fields.created 0 10 }} and ends {{ slice .fields.resolutiondate 0 10 }}   ...
--> Invalid Usage: template: gojira:7:62: executing "gojira" at <slice .fields.created 0 10>: error calling slice: list should be type of slice or array but string
Documentations says:

slice
slice returns the result of slicing its first argument by the
remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
is x[1:2:3]. The first argument must be a string, slice, or array.

Here the complete template I use with go-jira:
@startgantt
{{ range .issues -}}
[Ticket:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ slice .fields.created 0 10  }} and ends {{ slice .fields.resolutiondate 0 10 }}
[Ticket:{{- .key -}}:{{ .fields.resolution.name }}] is colored Yellow
{{ if (and .fields.customfield_11202 .fields.customfield_11203) -}}
[Planned:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ .fields.customfield_11202 }} and ends {{ .fields.customfield_11203 }}
[Planned:{{- .key -}}:{{ .fields.resolution.name }}] is colored LightBlue
{{ end -}}
{{ end -}}
@endgantt

A: I don't think you want the quotes around .fields.created as you'll end up with that string, not the date you want, so that needs fixed but shouldn't cause this error.
This full template (with a few minor changes) does work with the latest go at least:
https://play.golang.org/p/fkK8DKyj9jy
t := template.Must(template.New("").Parse(`[Ticket:{{- .key -}}:{{ .fields.resolutionname }}] starts {{ slice .fields.created 0 10 }} and ends {{ slice .fields.resolutiondate 0 10 }} `))
data := map[string]interface{}{
    "key":"key",
    "fields":map[string]string{"created":"2020-03-09T08:09:40.000+0000",
    "resolutionname":"name",
    "resolutiondate":"2020-03-09T08:09:40.000+0000"},
}

err := t.Execute(os.Stdout, data)

Which library are you using to output this template, I assume text/template?
The introduction of the slice function is relatively recent but it doesn't give that error anyway. Are you sure you haven't redefined slice in your func map? That seems the most likely explanation as the slice function doesn't give the error you quote in any circumstances.
Can you try a simple test of that slice function with a string separately, like the play.golang.org link above, but with your template?

A: The slice function was added in Go 1.13, so if you're using Go 1.10.4 as you indicated in your comments, this function is not known to the parsing engine. Go-jira might add a function with this name, but that may not support slicing strings.
Best is if you upgrade to Go 1.13 or newer, and this slice function will be ready to slice your strings as can be seen in this example:
t := template.Must(template.New("").Parse(`{{slice . 1 3}}`))
if err := t.Execute(os.Stdout, "012345"); err != nil {
    panic(err)
}

Which outputs (try it on the Go Playground):
12


text:
Q: Can I use `sed` to translate characters like with `tr`? I would like to replace a set of characters with corresponding characters from another set, something like this:
original set: ots
"target" set: u.x

foobartest → fuubar.ex.

Translations/transliterations like this are the specialty of the tr command:
$ echo 'foobartest' | tr 'ots' 'u.x'
fuubar.ex.

Unfortunately tr doesn't support changing files in-place like sed does.
I would like to use sed so I don't have to reinvent the wheel of juggling temp files.

A: If like in your case, you're transliterating characters without changing their size (anyway, some implementations like GNU tr only support single-byte characters), you can do:
tr 'ots' 'u.x' < file 1<> file

That is, have tr overwrite the file over itself.
That's better than sed -i on several accounts:

*

*it doesn't need extra disk space (except for some sparse file, copy-on-write special cases)

*it preserves inode numbers, ownership, permissions, ACLs...

*it works OK with symlinks, it doesn't break hard links

*it doesn't leave temp files lying about when killed.

One drawback is that if it's interrupted, the file will end up being half-translated (in this case, though, you can run it again to finish it). Some sed implementations would handle that correctly by making sure the original file remains unchanged unless the command succeeds.

A: As another alternative, if your main issue is the lack of support for changing files in-place, you might be interested in the sponge tool from the moreutils package:
tr 'ots' 'u.x' < file | sponge file

will write to file, but only open file for writing once the input is complete.  From the manpage:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constructing pipelines that read from and write to the same file.

Unless you have really large files which cannot be held in memory, sponge could work for you.

A: sed has the y command that works just like tr at least in most implementations:
$ echo 'foobartest' | sed 'y/ots/u.x/'
fuubar.ex.

The y command is part the POSIX sed specification, so it should work on just about any platform.
And since it's sed, you can have it replace a file with its edited version, sparing you the bothersome temp file business (provided your implementation of sed supports the -i option, which is not specified by POSIX):
$ sed -i 'y/ots/u.x/' some-file.txt

Currently BSD implementation of sed does not actually mirror the behavior of tr in some corner cases


text:
Q: PHP and the mail() function I am using a PHP script to send e-mails to a list of friends.  This used to work successfully but now the only e-mails that are sent successfully are those inside my domain ("mycompany.com").  Any e-mails outside my domain fail to be sent.  Is this a problem with permissions?  Could I fix it by changing the headers I use when I call the mail() function?  Here is the PHP script:
$name = "Joe Smith";
$email = "jsmith@mycompany.com";
$to = "ajones@mycompany.com, tom@abc.com, ted@def.com, mary@ghi.com";
$subject = "Dinner Invitations";
$message = "Invitation to Dinner";
$headers  = "From: ".$name."<".$email.">\r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "Return-Path: ".$email."\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n";
mail($to, $subject, $message, $headers);

Only ajones@mycompany.com was sent out by the server.  tom@abc.com, ted@def.com, and mary@ghi.com did not get sent.
Any suggestions would be deeply appreciated!


text:
Q: Mqtt Pub-Sub with Quality of Service=2 in java I have some doubts regarding QoS=2 settings.
Mqtt publisher-subscriber am using Qos=2. Up to my knowledge by setting Qos=2 avoid duplication of message delivery among subscribers. In publisher i have set the Qos=2. I have two subscribers listening the same TOPIC. My code is running correctly but both subscribers getting the same message.
By setting Qos=2 Only one subscriber can get the message right?
How to solve this issue?
public class PubSync {
    public static void main(String[] args) {
        try {
            MqttClient client = new MqttClient(TCPAddress,MqttClient.generateClientId());
            MqttTopic topic = client.getTopic(MYTOPIC);
            MqttMessage message = new MqttMessage(msg.getBytes());
            message.setQos(2);
            client.connect();

            MqttDeliveryToken token = topic.publish(message);
            token.waitForCompletion();

            client.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: QOS 2 means the that each subscriber will only receive 1 copy of any given message.
This differs from QOS 1 where it is possible that a subscriber may receive multiple copies of the same message as the broker ensures that message is delivered.
The QOS levels do not change in any way how many subscribers will see a message.

A: Depending on the MQTT messaging provider you are using, you should be able to share a subscription to a topic across multiple subscribers so that only one subscriber receives each message. In this case the messaging provider handles distributing the workload evently across all the subscribers.
This is known as shared subscriptions and you can read more about how it works in IBM's MessageSight product here: http://pic.dhe.ibm.com/infocenter/ism/v1r0m0/topic/com.ibm.ism.doc/Overview/ov30010.html


text:
Q: h1 on body is centered even when i float:left; I'm new to HTML and CSS, I don't know where is the mistake in my code.
So I have a class header-text to show "Welcome to MOK VPS" with h1.
I used float:left; on my CSS code but it stills show the text on the center. But if I use float:right; it moves to the right.
I'm just messing around with HTML and CSS after learning it a few hours and reviewing what I learned.

* {
  margin: 0;
  padding: 0;
  border: none;
  font-family: Arial, sans-serif;
}

.header-home {
  height: 75px;
  background-color: rgba(23, 32, 42, 0.7);
  color: #CCD1D1;
}

.header-logo {
  float: left;
  padding: 20px;
  margin-right: 20%;
}

.header-list li {
  list-style: none;
  float: left;
  padding: 25px;
}

.header-login {
  padding-top: 25px;
  padding-right: 45px;
  float: right;
}

.body-text {
  float: left;
}

MOK VPS

Home

Features

Contact

LOGIN

Welcome to MOK VPS

A: I've added borders around the elements to illustrate what is happening here. Click Run code snippet to see.

* {
  margin: 0;
  padding: 0;
  border: none;
  font-family: Arial, sans-serif;
  /* adding for demonstration */
  border: 1px solid;
}

.header-home {
  height: 75px;
  background-color: rgba(23, 32, 42, 0.7);
  color: #CCD1D1;
}

.header-logo {
  float: left;
  padding: 20px;
  margin-right: 20%;
}

.header-list li {
  list-style: none;
  float: left;
  padding: 25px;
}

.header-login {
  padding-top: 25px;
  padding-right: 45px;
  float: right;
}

.body-text {
  border-color: lime;
  float: left;
}

MOK VPS

Home

Features

Contact

LOGIN

Welcome to MOK VPS

If you look closely, you'll see that the body-text div is actually caught on the header-home div. To prevent that, use clear to cause your div to go to the next line, after any previously floated elements.

* {
  margin: 0;
  padding: 0;
  border: none;
  font-family: Arial, sans-serif;
  /* adding for demonstration */
  border: 1px solid;
}

.header-home {
  height: 75px;
  background-color: rgba(23, 32, 42, 0.7);
  color: #CCD1D1;
}

.header-logo {
  float: left;
  padding: 20px;
  margin-right: 20%;
}

.header-list li {
  list-style: none;
  float: left;
  padding: 25px;
}

.header-login {
  padding-top: 25px;
  padding-right: 45px;
  float: right;
}

.body-text {
  border-color: lime;
  float: left;
  clear: left;
}

MOK VPS

Home

Features

Contact

LOGIN

Welcome to MOK VPS

A: Just change in your CSS for class body-text. "Absolute positioned" element has no positioned ancestors, it uses the document body, and moves along with page scrolling.:
.body-text {
  position:absolute;
}

A: You can simple add the position:absolute on your class body-text. Just add that get you problem fixed. But you also can make this:
.body-text {
    position: absolute;
    left: *****  Here you define how much you wanna move the tag, for example 20px***
  }

A: You need to style
. Like text-align: left;.
h1{
  float: left;
  text-align: left;
  display: inline-block; /*use this code if needed. It can be replaced with text-align*/
}