text:
Q: Using math accents/diacritics as standalone symbols Suppose I have an operation on a set X which I want to denote with something like $X^\prime$, $X^\bullet$, or $X^\circ$, except with a different symbol. I found out that some of the diacritics available in math mode (see here) make a decent candidate when used "standalone", for instance as $X \: \tilde{}$ or $X \: \hat{}$. This might not be the intended use for these characters, but the result looks very nice IMHO (certainly much nicer than, say, $X^\sim$ or $X^\wedge$).
However, in doing so, I will inevitably run into problems. One of these is easy to solve: a bit of extra space should be inserted before the standalone diacritic to make it look nice (a small space like \: seems to do the trick). However, if the diacritic is preceded by a subscript, I would like it to behave like a superscript, so it starts above the subscript, not after it. This is illustrated by the following MWE:
\documentclass[margin=2mm]{standalone}
\usepackage{amsmath}

\newcommand{\myhat}{\ensuremath{\:\hat{}}}
\newcommand{\mytilde}{\ensuremath{\:\tilde{}}}
\newcommand{\mybreve}{\ensuremath{\:\breve{}}}
\newcommand{\mycheck}{\ensuremath{\:\check{}}}

\begin{document}
\renewcommand{\arraystretch}{1.3}
\begin{tabular}{|c|c|c|c|}
    \hline
    command & no subscript & short subscript &  long subscript \\
    \hline
    hat     & $X\myhat$    & $X_1\myhat$     &  $X_{\omega(k)}\myhat$   \\
    tilde   & $X\mytilde$  & $X_1\mytilde$   &  $X_{\omega(k)}\mytilde$ \\
    breve   & $X\mybreve$  & $X_1\mybreve$   &  $X_{\omega(k)}\mybreve$ \\
    check   & $X\mycheck$  & $X_1\mycheck$   &  $X_{\omega(k)}\mycheck$ \\
    \hline
\end{tabular}
\end{document}

My question is this: how can I make these "standalone" diacritics behave more like superscripts, without having to resort to adding negative horizontal space manually for each occurrence? Alternatively, can identical symbols also be generated in a different way, so that they may be used simply as $X^\standalonetilde$, $X^\standalonehat$, $X^\standalonebreve$, and $X^\standalonecheck$?

A: Not very efficient, but it seems to work.
\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand\makesymbolaccent[2]{%
  \edef#1{{\mkern-1mu\noexpand\symbolaccent{\mathchar"\expandafter\@gobblethree#2}}}%
}
\newcommand{\symbolaccent}[1]{\mathpalette\symbol@accent{#1}}
\newcommand{\symbol@accent}[2]{%
  \sbox\z@{$\m@th\demote@style{#1}#2$}%
  \sbox\tw@{$\m@th\demote@style{#1}{}^{\demote@style{#1}#2}$}%
  \raisebox{\dimexpr\ht\z@-\ht\tw@}[\height][0pt]{\copy\z@}%
}
\newcommand\demote@style[1]{%
  \ifx#1\scriptstyle\textstyle\else\scriptstyle\fi
}
\makeatother

\makesymbolaccent{\ehat}{\hat}
\makesymbolaccent{\etilde}{\tilde}
\makesymbolaccent{\ebreve}{\breve}
\makesymbolaccent{\echeck}{\check}

\begin{document}

\begin{tabular}{|c|c|c|c|}
    \hline
    command & no subscript & short subscript &  long subscript \\
    \hline
    hat     & $X^\ehat$    & $X_1^\ehat$     &  $X_{\omega(k)}^\ehat$   \\
    tilde   & $X^\etilde$  & $X_1^\etilde$   &  $X_{\omega(k)}^\etilde$ \\
    breve   & $X^\ebreve$  & $X_1^\ebreve$   &  $X_{\omega(k)}^\ebreve$ \\
    check   & $X^\echeck$  & $X_1^\echeck$   &  $X_{\omega(k)}^\echeck$ \\
    \hline
\end{tabular}

\end{document}


text:
Q: Error on adding a web service to project library as a service reference I am adding a webservice to a web project as a service reference. The error on adding which occurs on adding is

The HTML document does not contain Web service discovery information.
  Metadata contains a reference that cannot be resolved.

Before adding the webservice as a  service reference I tried adding it as web reference.On doing it there was no error but, i was not able to access a class through the web reference.
So I went for the option of service reference.
I was able to add service reference to a web project and every thing works fine but I am unable to do the same in a class library.
Your help will be appreciated..
Thanks

A: Right click on your service in Solution Explorer and select View in browser.
you may have some errors in your service and in this way you can find out the errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scan for surrounding WiFi devices and store MAC addresses in database in Python The ultimate goal here is to be able to use a Raspberry Pi with a wireless adapter set to monitor mode, to scan all surrounding WiFi devices (even if they only have WiFi turned on and not associated), and keep a log of MAC addresses and timestamps in a local database (e.g. MySQL).
I have been using Python (specifically subprocess) and airodump-ng (and airmon-ng) to try to accomplish this, I am wondering if there are any better ideas or tools which can help me achieve this, even another language, C or Java or some other tool.

A: Well i hope you know about wireshark tool ,but what you want is the details about your neigboring access points and save it into a file. So lets start,

*

*first you need to capture the packets floating around and filter it, right? you can do it by with help of pcap.

*When you capture the packets, the radiotap header will have all the information you need, with some google search you learn more about it or go through each packets in wireshark.The packets are like different layers of wrapping. i can give you a sample code of unwrapping a packet..
static int count = 1;    /* packet counter */

/* declare pointers to packet headers */
const struct ieee80211_hdr  *ethernet;  /* The ethernet header [1] */
const struct ieee80211_radiotap_header *rt;
uint8_t *llc;

unsigned int radioTapSize ;
int ieee80211Size = 24;

rt = (struct ieee80211_radiotap_header*)(packet);

//Hex to Dec
std::stringstream ss;
ss << std::hex << rt->it_len;
ss >> radioTapSize;
//std::cout << radioTapSize << std::endl;

ethernet = (struct ieee80211_hdr*)(packet+radioTapSize);
llc = (uint8_t *)(packet+radioTapSize+ieee80211Size);

// LLC Value = aa:aa:03:00:00:00:08:00
//printf("%x\n",llc[0]);
if(llc[0] == 0xaa && llc[1] == 0xaa && llc[2] == 0x03 && llc[3] == 0x00 && llc[4] == 0x00
        && llc[5] == 0x00 && llc[6] == 0x08 && llc[7] == 0x00)
{
        printf("\nPacket number %d:\n", count);
            count++;
        //radioTapSize = rt->it_len;
        printf("Radiotap Length : %x\n",radioTapSize);
        std::cout << "Radiotap Length : " << radioTapSize  << std::endl;
        printf("Radiotap pad : %x\n",rt->it_pad);
        printf("Radiotap present : %x\n",rt->it_present);
        printf("Radiotap version : %x\n",rt->it_version);

        int i=0;
        printf("Farme Control : %x\n",htons(ethernet->frame_control));
        printf("Duration ID : %x\n",htons(ethernet->duration_id));

        printf("Address 1: ");
        for (i = 0; i < 6; ++i)
        {
            if(i != 5)
                printf(" %x:",ethernet->addr1[i]);
            else
                printf(" %x\n",ethernet->addr1[i]);
        }

        printf("Address 2: ");
        for (i = 0; i < 6; ++i)
        {
            if(i != 5)
                printf(" %x:",ethernet->addr2[i]);
            else
                printf(" %x\n",ethernet->addr2[i]);
        }

        printf("Address 3: ");
        for (i = 0; i < 6; ++i)
        {
            if(i != 5)
                printf(" %x:",ethernet->addr3[i]);
            else
                printf(" %x\n",ethernet->addr3[i]);
        }

        printf("LLC: ");
        for (i = 0; i < 8; ++i)
        {
            if(i != 7)
                printf(" %x:",llc[i]);
            else
                printf(" %x\n",llc[i]);
        }

}

look, this is just an example how a packet is unwrapped.
go through pcap stuff and you can easily filter all the informations from a packet sent by your neigbors. i can give you links to some useful things
to know more about sending and receiving packets.
I hope you understand it else feel free to ask.


text:
Q: Cutting the unit square into pieces with rational length sides The following questions seem related to the still open question whether there is a point(s) whose distances from the 4 corners of a unit square are all rational.

*

*To cut a unit square into n (a finite number) triangles with all sides of rational length. For which values of n can it be done if at all?

*To cut a unit square into n right triangles with all sides of rational length. For which values of n can it be done, if at all?
Remark: If one can find a finite set of 'Pythagorean rectangles' (rectangles whose sides and diagonal are all integers) that together tile some square (of integer side), that would answer this question.
3.To cut a unit square into n isosceles triangles with all sides of rational length. For which values of n can it be done, if at all?
Now, one can add the requirement of mutual non-congruence of all pieces to all these questions. Further, one can demand rationality of area of pieces or replace the unit square with other shapes (including asking for a triangulation of the entire plane into mutually non-congruent triangles all with finite length rational length sides)...
Note: From what has been shown by Yaakov Baruch in the discussion below, cutting the unit square into mutually non-congruent rational sided-right triangles can be done for all n>=4. Indeed, he has shown n=4 explicitly; for higher n, one can go from m non-congruent pieces to m+1 pieces by recursively cutting any of the m right triangular pieces n by joining its right angle to the hypotenuse to cut it into two smaller and mutually similar but non-congruent pieces.  That basically settles questions 1 and 2 - the non-congruent pieces case. However, if we need all pieces to be non-congruent and non-similar, the n=4 answer has no obvious generalization to higher n.
References:
1. https://nandacumar.blogspot.com/2016/06/non-congruent-tiling-ongoing-story.html?m=1

*On dissecting a triangle into another triangle

A: @YaakovBaruch's beautiful construction for $n=4$:

Edit by Yaakov Baruch. A partition with 8 isoceles triangles (I'm sure not minimal):


text:
Q: php graphQl "Field \"person\" argument \"id\" of type \"ID!\" is required but not provided.", I am trying to fetch person object by the example there: https://github.com/webonyx/graphql-php/tree/master/examples/01-blog
How should I debug this?
IndexController.php
    public function indexAction()
    {
        if (!empty($_GET['debug'])) {
            // Enable additional validation of type configs
            // (disabled by default because it is costly)
            Config::enableValidation();
            // Catch custom errors (to report them in query results if debugging is enabled)
            $phpErrors = [];
            set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
                $phpErrors[] = new ErrorException($message, 0, $severity, $file, $line);
            });
        }
        try {
           /* // Initialize our fake data source
            DataSource::init();*/
            // Prepare context that will be available in all field resolvers (as 3rd argument):
            $appContext = new AppContext();

            // here we can change to repository which returns user object
            //$appContext->viewer = DataSource::findUser('1'); // simulated "currently logged-in user"
            $appContext->rootUrl = 'http://localhost:8080';
            $appContext->request = $_REQUEST;
            // Parse incoming query and variables
            if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
                $raw = file_get_contents('php://input') ?: '';
                $data = json_decode($raw, true);
            } else {
                $data = $_REQUEST;
            }
            $data += ['query' => null, 'variables' => null];
            if (null === $data['query']) {
                $data['query'] = '{hello}';
            }
            // GraphQL schema to be passed to query executor:
            $schema = new Schema([
                'query' => Types::query()
            ]);
            $result = GraphQL::execute(
                $schema,
                $data['query'],
                null,
                $appContext,
                (array) $data['variables']
            );
            // Add reported PHP errors to result (if any)
            if (!empty($_GET['debug']) && !empty($phpErrors)) {
                $result['extensions']['phpErrors'] = array_map(
                    ['GraphQL\Error\FormattedError', 'createFromPHPError'],
                    $phpErrors
                );
            }
            $httpStatus = 200;
        } catch (\Exception $error) {
            $httpStatus = 500;
            if (!empty($_GET['debug'])) {
                $result['extensions']['exception'] = FormattedError::createFromException($error);
            } else {
                $result['errors'] = [FormattedError::create('Unexpected Error')];
            }
        }
        header('Content-Type: application/json', true, $httpStatus);
        echo json_encode($result);
        die;
    }

PersonType.php
namespace Application\GraphQL\Type;

use Application\GraphQL\Types;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;

class PersonType extends ObjectType
{
    public function __construct()
    {
        $config = [
            'name' => 'Person',
            'description' => 'Persons',
            'fields' => function() {
                return [
                    'id' => Types::id(),
                    'firstName' => [
                        'type' => Types::string(),
                    ],
                ];
            },
            // todo what is this
            'interfaces' => [

                Types::node()
            ],
            'resolveField' => function($value, $args, $context, ResolveInfo $info) {
                if (method_exists($this, $info->fieldName)) {
                    return $this->{$info->fieldName}($value, $args, $context, $info);
                } else {
                    return $value->{$info->fieldName};
                }
            }
        ];
        parent::__construct($config);
    }

}

Query type:
namespace Application\GraphQL\Type;

use Application\GraphQL\Types;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;

class QueryType extends ObjectType
{
    public function __construct()
    {
        $config = [
            'name' => 'Query',
            'fields' => [
                'person' => [
                    'type' => Types::person(),
                    'description' => 'Returns person by id',
                    'args' => [
                        'id' => Types::nonNull(Types::id())
                    ]
                ],
                'hello' => Type::string()
            ],
            'resolveField' => function($val, $args, $context, ResolveInfo $info) {
                return $this->{$info->fieldName}($val, $args, $context, $info);
            }
        ];
        parent::__construct($config);
    }

    public function person($rootValue, $args)
    {
        // todo ?
    }

    public function hello()
    {
        return 'Your graphql-php endpoint is ready! Use GraphiQL to browse API aaa';
    }
}

I am sending query:
{
  person {
    id
  }
}

Why I am getting that error?

A: While writing question and trying to minimize code, as often I found myself why I was getting the error:
It is becuase in QueryType.php __construct() function there is lines:
'args' => [
                'id' => Types::nonNull(Types::id())
          ]

So the code requires that id would be passed, but we are not passing it. Our query should be like this:
{
  person(id: "1") {
    id

  }
}


text:
Q: Android run 2 activities next to each other in task list Is it possible within Android to run 2 activities side by side in task manager? I can now generate 2 separate icons and they both work properly but I can only open 1 Window at a time . As soon as I open the other icon, the current one is replaced with the new activity. I would have liked it to have its own screen if possible. I've tried various options but failed. Is it even possible within Android?
This is what my manifest looks like without the adjusments.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.allpics">

    ...

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AllPics">

        <activity
            android:exported="true"
            android:name=".MainActivity"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:exported="true"
            android:name=".GalleryActivity"
            android:label="Gallery"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        ...

    </application>

</manifest>

A: In the AndroidManifest, make sure to set the android:taskAffinity attribute of the element differently for each Activity. For example:
<activity
    android:name="com.example.ActivityA"
    android:label="Activity A"
    android:launchMode="singleInstance"
    android:taskAffinity="com.example.AffinityA" >
</activity>
<activity
    android:name="com.example.ActivityB"
    android:label="Activity B"
    android:launchMode="singleInstance"
    android:taskAffinity="com.example.AffinityB" >
</activity>


text:
Q: Difference between Make Project, Make Module app, Build APK and Generate Signed APK What is the difference between Make Project, Make Module app, Build APK and Generate Signed APK options that you can find in menu bar->Build and when to use each one?

A: According to IntelliJ :
Project:
In the IntelliJ Platform, a project encapsulates all your source code, libraries, and build instructions into a single organizational unit. Everything you do using the IntelliJ Platform SDK is done within the context of a project. A project defines collections referred to as modules and libraries. Depending on the logical and functional requirements to the project, you can create a single-module or a multi-module project.
Module:
A module is a discrete unit of functionality that can be run, tested, and debugged independently. Modules includes such things as source code, build scripts, unit tests, deployment descriptors, etc. In the project, each module can use a specific SDK or inherit SDK defined on the project level (see the SDK section later in this document). A module can depend on other modules of the project.
signed APK:
signed packages to deploy and run your applications on physical devices. Based on this signature, the Android system identifies the author of every deployed application. You do not need to apply for a personal signature to any authority, a signature generated by IntelliJ IDEA is quite sufficient.
Build APK:
In debug mode, you sign your app with a debug certificate generated by the Android SDK tools. This certificate has a private key with a known password, so you can run and debug your app without typing the password every time you make a change to your project.
Android Studio signs your app in debug mode automatically when you run or debug your project from the IDE.

A: Make Project: Means you create a real application which is working on a device
    and has an executable file like an APK.
Make Module: Means you create a library project for you application which is executed with that project and has no executable file like an APK but has a .jar  file which works as a library.
Build APK: When you normally run your application, an APK file is generated locally which is like a ZIP file and is easily unzippable, no security is implemented, and you can get the code from that APK file. It is used basically for local testing.
Signed APK: It is that APK you can create with a password and security and it is not easily unzippable and is used for production.

A: Make Project:- Here Android studio consider this as workspace as in Eclipse. All modules which are required in application reside in project directory.
Module :- You make module when you want to create your own library. You can import module if you want to include library into your application where you can do changes as well. Other options are dependency or JAR file. But they are pre-compiled code and you can not do changes in that. Module allows you to made changes in code and compile when you run the application.
Build APK :- When we run the application then code gets compiled and APK file is generated. It is not secure it can be decompiled easily and anyone can get code from it. There are several ways to do so. So here comes Signed APK.
Signed APK :- Signed APK is necessary for uploading your apk to play store for security purpose. For building this you need to make it signed using Keystore and make that password protected. It assure you that your code is secure and hasn't tampered.

A: Note: if U want to build debug or release output with sign key like "Generate Signed APK" command  and test it on emulatotor, add your sign key to build.gradle(app) like this:
signingConfigs {
release {
storeFile file("../key.jks")
storePassword "..."
keyAlias "..."
keyPassword "..."
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}

A: Note: Running your project with Shift+F10 automatically triggers an up-to-date build, so you don't need to execute Make-Project with Ctrl+F9 before launching with Shift+F10.
But if you just want the 'can it build?' check, and would like to AVOID the overhead of launching your app, Ctrl+F9 is useful.
(I arrived at this thread, to figure out if I had to do both C-F9 & S-F10 everytime.)


text:
Q: std::swap not working with std::array I have some code that requires me to put some data into a std::array. I thought I could do this by swapping two arrays and discarding one of them. Here's the code
int main()
{
    std::array<double, 10> a;
    std::array<double, 5> b;
    /*populate b*/
    /*swap them round*/
    std::swap(a, b);
}

But I get a very strange compiler error (MSVC2013).
CashFlows.cpp(27): error C2665: 'std::swap' : none of the 3 overloads could convert all the argument types
include\exception(502): could be 'void std::swap(std::exception_ptr &,std::exception_ptr &)'
include\tuple(572): or 'void std::swap(std::tuple<> &,std::tuple<> &)'
include\thread(232): or 'void std::swap(std::thread &,std::thread &) throw()'
while trying to match the argument list '(std::array<_Ty,_Size>, std::array<_Ty,_Size>)'
with
[
  _Ty=double,
  _Size=0x0a
]
and
[
  _Ty=double,
  _Size=0x05
]

which I don't understand. What does std::tuple<> etc. have anything to do with this?

A: The objects a and b are fundamentally different types as they are different template instantiations.
Therefore you can't use them together in std::swap as the arguments must be the same type.
Your compiler can't find an appropriate overload (granted, the ones it shows you do seem odd), so issues the error that you see.

A:
which I don't understand. What does std::tuple<> etc. have anything to do with this?

You just sort out reading error messages a bit further upon hints. The compiler just lists the available constructor declarations that could be possibly appropriate:

could be
void std::swap(std::exception_ptr &,std::exception_ptr &)

or
void std::swap(std::tuple<> &,std::tuple<> &)

or
void std::swap(std::thread &,std::thread &) throw()

You can see these also documented here.


text:
Q: BackgroundWorker.ReportProgress exception if run in another module My BackgroundWorker works perfectly in my main form frmMain. But when I run the ReportProgress method in another module, I get exception "This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress." This IS set to report progress; this works fine when run the same way in the main module.
Basically, from a module called by my BackgroundWorker, I want to show progress on my main form.
How can I fix this? The only idea I have is to move the code from the module into my main form, but this seems a backward step, which would involve extra work. Am hoping there are easier ways!
Calling code in class frmMain:
Friend WithEvents BackgroundWorker As New System.ComponentModel.BackgroundWorker

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
    ' Specify that we do NOT want the background operation to allow cancellation
    BackgroundWorker.WorkerSupportsCancellation = False
    ' Specify that we want the background operation to report progress.
    BackgroundWorker.WorkerReportsProgress = True
    ' Start running the background operation by calling the RunWorkerAsync method.
    BackgroundWorker.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker_DoWork(ByVal sender As Object, _
        ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
    Dim result As Boolean
    result = MyTest()
End Sub

Private Sub BackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker.ProgressChanged
    Me.Text = e.ProgressPercentage.ToString() & "%"
    sspStatus.Text = e.UserState.ToString
End Sub

Private Sub BackgroundWorker_RunWorkerCompleted(ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles BackgroundWorker.RunWorkerCompleted
    If e.Cancelled = True Then
        '  The background operation was cancelled
        Me.Text = "Cancelled!"
    ElseIf e.Error IsNot Nothing Then
        '  The background operation encountered an error
        Me.Text = "Error: " & e.Error.Message
    Else
        '  The background operation completed successfully
        Me.text = "Done!"
    End If
End Sub

Code which generates the exception in separate module Invoices:
Public Function MyTest() As Boolean
    frmMain.BackgroundWorker.ReportProgress(0)
End Function

Am using VB.NET in VS 2010, with .NET 3.5.

A: Try to set it up as
Public Function MyTest(worker as BackgroundWorker) As Boolean
    worker.ReportProgress(0)
End Function

to make sure you are talking to the right worker instance.
(And aside: avoid using classnames for instance fields).


text:
Q: Is there an Alternative to using ActiveInspector and ActiveExplorer when getting a selected Email's ID? im working on a small outlook project and i just wanted to know, If i wanted to get the details of a selected email in the inbox such as the EmailID is there other ways to get those details besides ActiveExplorer and ActiveInspector. I am using this method to get the details i want right now:
Outlook.MailItem mailItem   = null;
Outlook.Inspector inspector = Application.ActiveInspector();

mailItem       = inspector.CurrentItem as Outlook.MailItem;
string EntryID = mailItem.EntryID;


text:
Q: Ordering Disabled in TFS Backlog I am managing an agile project in TFS.  When I click on the current sprint on the left hand side of the TFS web app, the stories in the sprint are listed out as normal, but there is now a message stating that:
Ordering backlog items is disabled, because this iteration contains nested backlog items. Learn how to fix this.
When I click on the "Learn how to fix this." link, the MS page that comes up speaks about nested work items in the backlog, but doesn't really give any clue about how to detect the nested backlog items.  Each story in my list naturally has Tasks created for each story, but as far as I can detect this is the only level of nesting there is.  This should not be enough to disable ordering, however, because my other TFS project also has stories broken down into tasks and ordering is NOT disable for that project.
Any idea what could be going on here?

A: The problem turned out to be that one of the bugs in the sprint was a child of one of the stories in the sprint.  I changed the relationship from parent to related and then I was able to reorder the work items again.


text:
Q: Ancestry Gem 'undefined method' error I am using the Ancestry Gem and I am getting an undefined method "arrange" for #<Array:0x007f8d58e58700> error with the following code:
<%= @shipmgr_carriers.arrange(:order => :name) %>

However, When I just output @shipmgr_carriers I get an array with ancestry:
[#<Shipmgr::Carrier id: 9, name: "testing", status: nil, created_at: "2012-01-16 22:44:28", updated_at: "2012-01-16 22:44:28", ancestry: nil>, #<Shipmgr::Carrier id: 10, name: "test", status: nil, created_at: "2012-01-16 22:44:28", updated_at: "2012-01-16 22:44:28", ancestry: "9">]

Can anyone tell me why I am unable to call the .arrange method on the array variable?

A: I haven't used Ancestry but it looks like it adds the arrange method to ActiveRecord::Base. It doesn't add this method to Array and so you shouldn't expect it to work on an array.
I'm assuming you're declaring @shipmgr_carriers in your controller something like this:
class SomeController < ActionController::Base
  def some_action
    @shimgr_carriers = SomeModel.find(...).carriers
  end
end

Try this instead:
def some_action
  @shipmgr_carriers = SomeModel.find(...).carriers

  @shipmgr_carriers_arranged = @shipmgr_carriers.arrange(...)
end

My hunch is that by the time @shipmgr_carriers gets to your view the query has already been run, transforming it into an array of results instead of a relation.
This is logic that should probably be done in the controller anyway, so moving it out of the view is a good idea regardless.

A: The arrange() method acts either at the class level or on a named scope, not on a returned array of values. For example, if you want to call arrange() on a table called 'Activity', this would work and return the entire table in an arranged format:
Activity.arrange

However, if you want to call arrange on a specific tree in the table you would go:
Activity.find(...).subtree.arrange

'subtree' is a named scope provided by the has_ancestry gem. Therefore, the arrange() method should work for the following named scope:

*

*ancestors

*children

*sibblings

*descendants

*subtree


text:
Q: java.lang.OutOfMemoryError Very odd behaviour with playing audio So i was playing around with playing audio a bit and i found a question on this site which i found some code on which i slightly adapted that answered playing audio but when i tried to use the code i got a java.lang.OutOfMemoryError.
Then i tried starting it with two gigabytes of ram and it still gave me the error,
I honestly have no idea what's going on my code is as follows:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class PlaySoundTest {

public static void main(String[] args){
    playSound("audio.wav");
}

public static synchronized void playSound(final String url){
      new Thread(new Runnable(){
        public void run(){
          try {
            Clip clip = AudioSystem.getClip();
            InputStream bufferedIn = new BufferedInputStream(new FileInputStream(new File(url)));
            AudioInputStream audioSrc = AudioSystem.getAudioInputStream(bufferedIn);
            clip.open(audioSrc);
            clip.start();
          }catch (Exception e){
            System.err.println(e.getMessage());
          }
        }
      }).start();
    }
}

And the entire stacktrace is this
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1131)
at PlaySoundTest$1.run(PlaySoundTest.java:24)
at java.lang.Thread.run(Thread.java:722)

This is really confusing me because to me this code looks fine.
Just to clarify the size of audio.wav is 1.5 MB so with 2 gigabytes allocated this really should not be an issue.
I'm thinking maybe a Memory leak somewhere but i couldn't think why.
I would be happy if anyone could shed some light on this.


text:
Q: Removing any and all inline styles from the_content() For one of my current projects, I had to transfer blogposts from an old Wordpress site to my project.
Things went smoothly until I've seen that all the posts were copy pasted from Word, leaving this before pretty much every paragraph:

And at some places things like these:

So because I don't have the 40 hours (even less the patience) to just go into every post (there's about 100) and remove those unwanted tags, I'm looking for a filter that would just remove all style (except maybe if it contains text-decoration:underline) elements before outputting the_content()
Is there such a thing?

A: Just add this to your functions.php.
Note: This filter works at the time of saving/updating the post.

add_filter( 'wp_insert_post_data' , 'filter_post_data' , '99', 2 );

function filter_post_data( $data , $postarr ) {

    $content = $data['post_content'];

    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#(.*?)#i', '\1', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);

    $data['post_content'] = $content;

    return $data;
}

Note: This filter works at the time when function the_content() is executed.

add_filter( 'the_content', 'the_content_filter', 20 );

function the_content_filter( $content ) {
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#(.*?)#i', '\1', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    $content = preg_replace('#
(.*?)
#i', '
\1
', $content);
    return $content;
}

A: I tried the method above with the saving/updating but didn't worked for me so I went from another approach. I exported the whole wp_posts table, opened it in Sublime and did a regex replace. I used style="*.*?" to find all cases and replaced them with emptyness. Then droped the old table's content and imported the new one.
If any one try this method - please make sure you have a clear back up in case there are some other post types in the wp_post table and the things got bit messy.

A: If we want to remove all inline styles, then just simply need to add the following code in functions.php.
add_filter('the_content', function( $content ){
    //--Remove all inline styles--
    $content = preg_replace('/ style=("|\')(.*?)("|\')/','',$content);
    return $content;
}, 20);

A: I would check out the content_save_pre filter, and probably apply some fancy regex at that point.


text:
Q: I want to make a command handler for embeds, but only one embed works and the others don't Ok, so
The command handler works, and I know it because I have 3 commands (2 are text only and one is an embed) that work. I've made this for embeds:
case "menta":
          bot.commands.get('menta').execute(msg, args)
break;

I have other embeds that I've made in the same way as the one that works, but they do not work.
Here's the embed that works:
const Discord = require("discord.js");

module.exports = {
    name: 'menta',
    description: 'Info sulla menta',
    execute(msg, args) {
        const menta = new Discord.MessageEmbed()
             .setTitle('ERBE')
             .addField('Nome', 'Menta')
             .addField('Proprietá', 'Rompere gli incantesimi e acquisire forza mentale durante i periodi di difficoltà')
             .setColor('#66CD00');
             msg.channel.send(menta);
    },
};

That works by typing mb! menta.
I've made other 2, and those do not work. Here is one of them:
const Discord = require("discord.js");

module.exports = {
    name: 'alloro',
    description: 'Info sull alloro',
    execute(msg, args) {
        const menta = new Discord.MessageEmbed()
             .setTitle('ERBE')
             .addField('Nome', 'Alloro')
             .addField('Proprietá', 'Visioni psichiche e sogni, respinge la negatività e il male.')
             .setColor('#66CD00');
             msg.channel.send(alloro);
    },
};

I get this error message:
C:\Users\U\Desktop\discord bot\commands\aloe_vera.js:12
             msg.channel.send(alloro);
                              ^

ReferenceError: alloro is not defined

Sorry if it's a stupid question but I'm very very new in this type of thing lol

A: This error origin is pretty, simple, like the message says:
execute(msg, args) {
        const menta = new Discord.MessageEmbed()
             .setTitle('ERBE')
             .addField('Nome', 'Alloro')
             .addField('Proprietá', 'Visioni psichiche e sogni, respinge la negatività e il male.')
             .setColor('#66CD00');
             msg.channel.send(alloro);
    }

Your newly created Embed is named menta, but you try to send one called alloro, just change the name of the const to alloro or send the menta emebed (either const alloro = ... or msg.channel.send(menta)).


text:
Q: Citation: How to set up lower case in partial citation and upper case in full reference for the author names? Note: My english isn't that good. My native english is german. I don't know the correct definition of german wissenschaftliche Ausarbeitung, which I called here as academic writing, german Kurzbeleg, which is the short reference in a citation in a continuous text, which I called here as partial citation and german Langbeleg, which is the full entry in the bibliography at the end of the written work, which I called here as full reference. I also couldn't find a correct translation of this definitions. So I someone has the experience with it, so please edit this question in the correct manner. Sorry for the inconvenience and thank you!
For my academic writing I have to set the names of the authors like this example:

*

*Partial citation: (Surname, Name 2000, S. 1)

*Full reference: SURNAME, NAME, 2000. Title...

Code for above example:
\documentclass[ngerman]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage{
            babel,
            csquotes
           }
\usepackage[
            backend = biber,
            sortlocale = auto,
            sorting = nty,
            style = authoryear-comp
           ]{biblatex}

\begin{filecontents}{\jobname.bib}
  @book{
        Sur,
        author = {Surname, Name},
        title  = {Title},
        year   = {2000},
       }
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

  Test \autocite[1]{Sur}.
  \printbibliography

\end{document}

How can I solve this task?
Thank you for your help and effort in advance!


text:
Q: How do we check Randomness? Let's imagine a guy who claims to possess a machine that can each time produce a completely random series of 0/1 digits (e.g. $1,0,0,1,1,0,1,1,1,...$). And each time after he generates one, you can keep asking him for the $n$-th digit and he will tell you accordingly.
Then how do you check if his series is really completely random?
If we only check whether the $n$-th digit is evenly distributed, then he can cheat using:

$0,0,0,0,...$
  $1,1,1,1,...$
  $0,0,0,0,...$
  $1,1,1,1,...$
  $...$

If we check whether any given sequence is distributed evenly, then he can cheat using:

$(0,)(1,)(0,0,)(0,1,)(1,0,)(1,1,)(0,0,0,)(0,0,1,)...$
  $(1,)(0,)(1,1,)(1,0,)(0,1,)(0,0,)(1,1,1,)(1,1,0,)...$
  $...$

I may give other possible checking processes but as far as I can list, each of them has flaws that can be cheated with a prepared regular series.
How do we check if a series is really random? Or is randomness a philosophical concept that can not be easily defined in Mathematics?

A: All the sequences you mentioned have a really low Kolmogorov complexity, because you can easily describe them in really short space. A random sequence (as per the usual definition) has a high Kolmogorov complexity, which means there is no instructions shorter then the string itself that can describe or reproduce the string. Ofcourse the length of the description depends on the formal system (language) you use to describe it, but if the length of the string is much longer then the axioms of your formal systems, then the Kolmogorov-complexity of a random string becomes independent of your choice of system.
Luckily, under the Church-Turing thesis, there is only 1 model of computation,(unless your machine uses yet undiscovered physical laws), so there is only 1 language your machine can speak that we have to check.
So to test if a string is random, we only have to brute-force check the length of the shortest Turing-program that outputs the first n bits correctly. If the length eventually becomes proportional to n, then we can be fairly certain we have a random sequence, but to be 100% we have to check the whole (infinite) string. (As per definition of random).

A: Leaving aside the theoretical aspect of your question, there are also pragmatic answers to it because there are real world uses for high-quality random generators (whether hardware or algorithmic). For statistical uses, "statistical randomness" is a used. For example you can use these "diehard tests" or TestU01.

A: This is discussed very nicely in Volume 2 of Knuth's The Art Of Computer Programming. The executive summary is that randomness is a mathematical concept that can be defined in mathematics but not easily.


text:
Q: Drone with Postgres - psql: could not connect to server: No such file or directory I've tried setting up a drone server using the postgres plugin but I'm completely unable to get it working.
I've done is to copy the default drone setup from the docs:
---
  kind: pipeline
  type: docker
  name: default

  steps:
    - name: test
      image: postgres:9-alpine
      commands:
        - sleep 5 #give the service some time to start
        - psql -U postgres -d test

  services:
    - name: database
      image: postgres:9-alpine
      environment:
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: password
        POSTGRES_DB: test

But I get the following error while trying to start it up
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

My guess is that postgres is not starting for some reason, but it's difficult to tell.
Here is the Postgres log:
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default timezone ... UTC
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
sh: locale: not found
performing post-bootstrap initialization ... No usable system locales were found.
Use the option "--debug" to see details.
ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    pg_ctl -D /var/lib/postgresql/data -l logfile start

waiting for server to start....LOG:  database system was shut down at 2020-05-27 08:49:09 UTC
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started
 done
server started
CREATE DATABASE

/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*

LOG:  received fast shutdown request
LOG:  aborting any active transactions
LOG:  autovacuum launcher shutting down
LOG:  shutting down
waiting for server to shut down....LOG:  database system is shut down
 done
server stopped

PostgreSQL init process complete; ready for start up.

LOG:  database system was shut down at 2020-05-27 08:49:11 UTC
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started

Either that or Postgres starts up fine but something kills it before other processes have the chance to communicate. I'm not entirely sure though.
Any help would be appreciated.

A: Drone brings up services in their own container that have their own hostname.
In your case you named your service database so when connecting with psql you need to pass the hostname so that psql establishes the connection with the container via TCP:
psql -U postgres -d test -h database


text:
Q: datetime convert to years This is my current code
from datetime import datetime as dt
df['Age'] = datetime.datetime.now()-pd.to_datetime(df[['Day','Month','Year']])

but my results are
0    3380 days 10:37:40.303097
1    3512 days 10:37:40.303097
2    3131 days 10:37:40.303097
3    3739 days 10:37:40.303097
4    4550 days 10:37:40.303097
5    3204 days 10:37:40.303097
6    3813 days 10:37:40.303097
7    5819 days 10:37:40.303097
8    4532 days 10:37:40.303097
9    2444 days 10:37:40.303097
10   2664 days 10:37:40.303097
11   5527 days 10:37:40.303097
12   3706 days 10:37:40.303097
Name: Age, dtype: timedelta64[ns]

How can I change the above to years?

A: I can't seem to format Timedelta as year - that said, you can use a decent approximation with days - 1 year = 365.25 days
df['Age'] = df['Age'].dt.days #turn timedelta into int number of days
df['Age'] = df['Age']/365.25

Afterwords you can use Round if there's too many decimals for you.
This only counts days. If you want more precision, you can even use seconds with 31556952 seconds in 1 year:
df['Seconds'] = df.Age.dt.days*24*3600+df.Age.dt.seconds #turn timedelta into int number of seconds
df['Years'] = df.Seconds/31556952

Basically your Timedelta is in many units: days, hours, minutes, seconds. You want to transfer that into one unit: float fraction of years. One way to do this is to convert into just one of the available units and then convert into years. Hence:
x = pd.Timedelta('3706 days 10:37:40.303097')
x.seconds
>>38260
x.days*24*3600+x.seconds
>>320236660 #Number of seconds in the Timedelta
(x.days*24*3600+x.seconds)/31556952 #Divided by the number of seconds in a year
>>10.14789577903468

A: It may be too late, but this should also work and I think might be easier:
df['Age'] = df['Age'].astype('<m8[Y]')


text:
Q: cannot instal discord module properly while installing the module, i get this error
C:\Users\User\Desktop\Trial>pip install discordpy
Collecting discordpy
  Using cached discordpy-0.1.1.tar.gz (1.3 kB)
Using legacy 'setup.py install' for discordpy, since package 'wheel' is not installed.
Installing collected packages: discordpy
    Running setup.py install for discordpy ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\user\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-ogovpl6m\\discordpy_7005c477f7d447de9f394c1c31fd29bc\\setup.py'"'"'; __file__='"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-ogovpl6m\\discordpy_7005c477f7d447de9f394c1c31fd29bc\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\User\AppData\Local\Temp\pip-record-t2eexxn7\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python38-32\Include\discordpy'
         cwd: C:\Users\User\AppData\Local\Temp\pip-install-ogovpl6m\discordpy_7005c477f7d447de9f394c1c31fd29bc\
    Complete output (14 lines):
    running install
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\User\AppData\Local\Temp\pip-install-ogovpl6m\discordpy_7005c477f7d447de9f394c1c31fd29bc\setup.py", line 32, in <module>
        setup(
      File "c:\users\user\appdata\local\programs\python\python38-32\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "c:\users\user\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "c:\users\user\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\User\AppData\Local\Temp\pip-install-ogovpl6m\discordpy_7005c477f7d447de9f394c1c31fd29bc\setup.py", line 20, in run
        raise Exception("You probably meant to install and run discord-py")
    Exception: You probably meant to install and run discord-py
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\user\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-ogovpl6m\\discordpy_7005c477f7d447de9f394c1c31fd29bc\\setup.py'"'"'; __file__='"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-ogovpl6m\\discordpy_7005c477f7d447de9f394c1c31fd29bc\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\User\AppData\Local\Temp\pip-record-t2eexxn7\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python38-32\Include\discordpy' Check the logs for full command output.

and to double check when i try running with this code-
from discord.ext import commands
code=commands.Bot(command_prefix='*')
@client.event
async def when_ready():
    print("Bot is ready")
@client.command()
async def hello(abcd):
    await abcd.send("Hi")
client.run('the bot token, cant share')

the error was shown to me was this
  File "C:\Users\User\Desktop\Trial\bot.py", line 4, in <module>
    @client.event
NameError: name 'client' is not defined

pls help out , so i need to spam so that my question get subbmitted and i dont get a error regarding that your post is mostly code , please add some more details?

A: *

*its discord.py so pip install -U discord.py

*You use whatever you define Client or Bot to, so it will be @code.event, @code.command() and so


text:
Q: Unable to load DLL 'LibFlac': The specified module could not be found. (Exception from HRESULT: 0x8007007E) HERE is the link to my project.
The error is on line 107: "context = FLAC__stream_encoder_new();" in file: FlacWriter.cs --> I didn't write that file. I got it from HERE
So I understand that libFLAC.dll is missing. So I tried all of the below approaches to solve the issue:
I downloaded libFLAC dll form rarewares.org/lossless.php#flac-dll-x64 I tried to add it as a reference, i get this ERROR:
"A reference to C:\CodeProjects\WaveConverter\WaveConverter\Libraries\libFLC_dynamic.dll' could not be added. Please make sure that the file is accessible, and that it is valid assembly or COM component."
I tried something else: I added the dll file to bin/Debug, reopened my project. ran the project again. same error on line: " context = FLAC__stream_encoder_new();" ERROR:"Unable to load DLL 'LibFlac': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"
I also tried 'importing' DLL in my code like this: I tried to add this line: "[DllImport("libFLAC.dll")]" under line 14 in my project file: Worker.cs
I get this ERROR: "Duplicate 'DLLimport' attribute'
I also downloaded dependency-walker from dependencywalker.com Not sure how to operate it, but when it finished downloading, I clicked on OPEN icon and opened the libFLAC_dynamic.dll file I was trying to add to the project. And there were no errors. I'm not sure how to use this dependencyWalker though...
What else can I try? How do I fix this error?

A: You are p/invoking an unmanaged library names LibFlac.dll. You need that library and its dependencies to be in the DLL search path when you first call a function from the library. Typically that means doing the following:

*

*Placing LibFlac.dll in the same directory as your executable file, and

*Installing all dependencies that LibFlac.dll has. Typically this will be an MSVC C++ runtime. Read the documentation carefully to work out what dependencies the DLL has.

This is an unmanaged DLL. Don't attempt to add it as a reference. It also seems that the DLL you have is named libFLC_dynamic.dll which differs from the name that your code is expecting. Have you got the right DLL?


text:
Q: ASP.NET Multiple Submits with Same Name with Masterpage I'm using a master page with multiple submit buttons to sort a table, as well as other submits on the page doing other things. I'd like to name all the submits for sorting the table the same name (sortTable), so I can do something like this on PostBack to pass the value of the column to sort by:
if (Request.Form["sortTable"] != null)
{
    sortTableBy(Request.Form["sortTable"]);
}

My problem is that when I run the site all the names are replaced with different values like ctl00$mainContent$ctl01 making it hard to capture them by a single name on postback. Any advice?

A: VDWWD's comment put me on the right track to solve this problem. I just added a function for each of those submits to call onclick and then put my sort table code in there. Thanks VDWWD.


text:
Q: Edad con fecha de nacimiento Tengo un vector de caracteres con fechas de nacimiento (en R) tipo "mes/día/año" , el vector consta de 161 fechas. Necesito obtener un vector numérico con las edades. ¿Hay forma de hacerlo de manera "rapida" sin tener que hacer todas las diferencias?

A: No encontré una función que haga exactamente eso, pero usando la librería lubridate es bastante fácil y resuelve automáticamente problemas del manejo de fechas como los bisiestos y cosas por el estilo.
Simulo unos datos:
library(lubridate)
fechas <- c("01/01/1900", "25/03/2019", "25/03/2021")

Con esta línea se resuelve el problema:
floor(time_length(ymd(Sys.Date()) - dmy(fechas), unit = "year"))

[1] 121   2   0

Si quieres tomar una referencia diferente al día de la fecha (hoy) para hacer el cálculo puedes reemplazar Sys.Date() con cualquier fecha arbitraria.
Uso las funciones ymd (Año/Mes/Día) y dmy (Día/Mes/Año) para convertir cadenas de caracteres a objetos de la clase fecha. Si tus fechas están en otros formatos tendrías que usar la función apropiada.
Va el mismo código, pero extendido y con comentarios.
floor(           #Para que redonde los años hacia abajo porque son años cumplidos, time_length regresa un double
  time_length(   #Regresa el período de tiempo y se pueden pasar un argumento para que sea en años
    ymd(Sys.Date()) - dmy(fechas), #El signo - funciona como difftime, regresa la diferencia en días. Sys.date() regresa el día de hoy
  unit = "year"))   #Acá está la unidad de tiempo para time_length


text:
Q: Errno::EACCES error when testing code in development on localhost Get this error when running this code:
<% content_for :game do %>
<% gamefolder = Dir.open(`#{Rails.root}/public/browserGames/#{@browserGame.slug}`) %>
<% gameFolder.each do |file| %>
  <% if file.match?(/.js/) %>
    <script src=<%= `#{Rails.root}/public/browserGames/#{@browserGame.slug}` + file %>></script>
  <% end %>
<% end %>

It stops me on line 2 and gives the Errno::EACCES error.  I am simply running this on localhost in development mode.  Wanting to make sure everything works before I try to deploy and find similar issues.
What I am trying to accomplish with this code is to load the js files for the specific game trying to be played in the window.
I am also open to trying other ways of achieving the goal, but I have different games on here and want to make sure I am only loading the specific files for the selected game.
Any help is greatly appreciated.

A: Use
Dir["#{Rails.root}/public/browserGames/test/*.js"]

instead of opening open for dir.
and use <script src="<%= file %>"></script>


text:
Q: Karate Tests: How to match contains each nested array response with just one schema Is possible to match each element of a nested array response (using contains) using just one schema?
I have a set of yml files with request params and response schemas, like this one:
response:
  appId: '#string'
  attributes: '#array'
  login: '#string'
  permissions: '#array'
  metadata:
    roles: '##array'
  userData:
    description: '#string'
    employeeId: '#string'
    employeeNumber: '##string'
    id: '#string'
    login: '#string'
    mail: '#string'
    name: '#string'

and then, in a reusable feature:
* def req = read(<testDataFile>)
* match response contains req.response

I can match nested objects with just one schema but I'm not sure if it's possible use the schema to match nested arrays
maybe like:
response:
  appId: '##string'
  attributes: '##array'
  attributes[*]:
    key: '#string'

or any other expression
Thanks a lot

A: You can't do this with a single "schema" and you have to declare the repeating element separately, as a Karate variable: https://github.com/intuit/karate#schema-validation
* def foo = { a: '#number' }

* def bar = { baz: [{ a: 1 }, { a: 2 }, { a: 3 }] }

* match each bar.baz == foo
* match bar == { baz: '#[] foo' }


text:
Q: Is "myself" okay in this sentence (grammar, style, etc.)? I read some other questions about "me" vs. "myself".  If I understood the answers right, "me" is correct or preferable in most cases.  So my question is, is it okay to use "myself" in the following?  My hunch is the administrator I'm writing to would like it better than "me".

After reviewing the documentation I submitted today, if you have any specific concerns about my son's medical needs, please do not hesitate to communicate them to his doctor or myself.

A: I don't think you would need to be embarrassed, but some people do (mistakenly, to be sure) think it is wrong. As so often occurs with these, they are just following uninformed prescriptions handed down by folks who don't know any better.
This has been going on for 400 years, so it is as clearly grammatical in the minds of native speakers as it is disparaged by prescriptivists telling people what to do.  CGEL says: "Overrides with 3rd person reflexives characteristically occur in contexts where the antecedent refers to the person whose perspective is being taken in the discourse."
See this for more.

A: While it's possible that the administrator would prefer "myself", the correct usage would be "me". If you would like to make it more clear, you could say

... please do not hesitate to communicate them to his doctor or to me.

The addition of the preposition makes it clear that I am a second indirect object in this case.


text:
Q: Recursive Notifications My application is IOS application.
I have a scenario typical to the calendar iPad application, when  the user goto to a date from a view, each views update itself and notify others. The problem is that notifications between views never ends.
I am using the NSNotificationCenter
[[NSNotificationCenter defaultCenter] postNotificationName:SelectedDateChangedNotification object:self userInfo:nil];

I would like to explore some ideas of how effectively implement this scenario.
Thanks

A: You need to have two ways of updating each of your views.  The first way is when the user updates it and the second way when it gets updated by a different view.  The first way sends notifications to the other views and the second way does not.  From an implementation standpoint, the first way would just be a wrapper around the second way which first notifies the other views.


text:
Q: Get user IP address using dns host not working on IIS I am running an application that has to get the current user IP address, the functionality seems to be working when running the app from VS, however it breaks completely when deployed on IIS, here is the code to get the user IP
 public static string GetUserIP()
 {
   string strHostName = "";
   strHostName = System.Net.Dns.GetHostName();

   IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

   IPAddress[] addr = ipEntry.AddressList;

   return ipEntry.AddressList.Last().ToString();
}

I have another method which uses the return value from the GetUserIP() method, here is the code
private void SaveSmsDetails(string cellNumber, string message, string userLogonName)
 {
  string[] userIP = IPAddressGetter.GetUserIP().Split('.');
 }
Now this method is throwing a an index out of range exception, this means the GetUserIP method does not returning any value hence the Split method is falling apart, is there anything I need to do or change or perhaps something must be done on the IIS server.
Note: IIS version is 8.5.9

A: MSDN says: If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.
Details here: Dns.GetHostEntry Method (String)
So, make sure that the known issues/scenarios are properly handled.
Further, try GetHostByName instead of GetHostEntry
source here


text:
Q: Algolia exception filters: Unexpected token string(to) expected ')' I am trying to perform filtering in my Android app using Algolia as they have shown in their Filtering and facets tutorial but I am getting this error in my query.setFilters() method: Algolia exception filters: Unexpected token string(to) expected ')'
Here is the code sample I used:
Query query = new Query();
query.setAttributesToHighlight("type");
query.setHighlightPreTag("
");
query.setHighlightPostTag("
");
query.setRestrictSearchableAttributes("type","price");
query.setFilters("code=1 AND (price:1000 to 300000000 OR price:10 to 100)");

My aim is to perform a range search on my data.
How can i achieve that?

A: The code snippet in the tutorial had a typo, filter keywords should be in all caps as you can see in the Filter Syntax list of keywords.
You should use this instead:
query.setFilters("code=1 AND (price:1000 TO 300000000 OR price:10 TO 100)");


text:
Q: Chrome DevTools sources webpack missing I cannot debug my Angular8 project since there is no webpack folder.
I start the application with like this: ng build --watch --source-map, and there are the .map files in the target folder, but chrome don't realize them.
(the js source maps are enabled in devtools settings)

A: Not sure I correctly understand your question, but usually you just

*

*run ng serve

*open http://localhost:4200

*use the debugger "open file" shortcut (with autocomplete) to find the source file your are looking for

*set breakpoints

*debug :-)


text:
Q: Replicating figure in another document with same numbering I have a large document with several images, and I'd like to duplicate some of these images in individual pdf documents on their own, while preserving the way they display, figure numbering, and reference numbering of citations, tables, etc. So for example, if the figure number is 1.3 in the main document, it would still be 1.3 in the other document, despite the fact that figures 1.1 and 1.2 don't exist in the other document. Likewise for any reference in the caption, i.e.:
\caption{Something referencing Table \ref{tab:example} and citing \cite{examplecite}.}

would display as "Figure 1.3: Something referencing Table 1.2 and citing [15]." in both documents, despite the absence of Table 1.1, or citations 1-14 in the latter document.
A very manual way to achieve this would be to duplicate my preamble in a new tex document, copy over only the relevant figure, then replace instances of \cite{Example}, etc, with its actual number so as to preserve the numbering, then use this to generate the pdf that I'm after. This would work, but it's a terrible solution.
I'd like to know how to best go about this. I'm just after ideas of things to try, not a fully coded working example, as I don't know how to make a MWE for this.

A: You want to try xr. This is a schematic "long" file, say ulysseslong.tex:
\documentclass{article}

\begin{document}

\section{Test}\label{sec:test}

\begin{figure}[htp]
\centering
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{A caption\label{fig:A}}
\end{figure}

\begin{figure}[htp]
\centering
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{B caption\label{fig:B}}
\end{figure}

\begin{figure}[htp]
\centering
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{C caption with a reference to Section~\ref{sec:test}\label{fig:C}}
\end{figure}

\begin{figure}[htp]
\centering
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{D caption\label{fig:D}}
\end{figure}

\begin{table}[htp]
\centering
\caption{A table caption\label{tab:A}}
\medskip
\begin{tabular}{cc}
a & b \\
c & d
\end{tabular}
\end{table}

\begin{table}[htp]
\centering
\caption{B table caption\label{tab:B}}
\medskip
\begin{tabular}{cc}
a & b \\
c & d
\end{tabular}
\end{table}

\end{document}

Here is the "short" version, say ulyssesshort.tex:
\documentclass{article}

\usepackage{xr}
\externaldocument{ulysseslong}

\makeatletter
\newcommand{\extref}[1]{%
  \@namedef{the\@captype}{\ref{#1}}%
}
\makeatother

\begin{document}

\begin{figure}[htp]
\centering\extref{fig:C}
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{C caption with a reference to Section~\ref{sec:test}}
\end{figure}

\begin{figure}[htp]
\centering\extref{fig:D}
\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}
\caption{D caption}
\end{figure}

\begin{table}[htp]
\centering\extref{tab:B}
\caption{B table caption}
\medskip
\begin{tabular}{cc}
a & b \\
c & d
\end{tabular}
\end{table}

\end{document}

Provided all cross references in ulysseslong.tex are solved, this is the output of processing ulyssesshort.tex:

A: If i understand correctly, one can do some thing like this:
Main document
\documentclass{article}
\usepackage{mwe} % just for the example

\let\mtincludegraphics\includegraphics
\renewcommand{\includegraphics}[2][]{%
\mtincludegraphics[#1]{#2}%
\immediate\write\mt{\string\mtfigureinserted{#2}{\thefigure}}}

\newwrite\mt
\AtBeginDocument{\immediate\openout\mt=\jobname.img}
\AtEndDocument{\immediate\closeout\mt}

\begin{document}
\lipsum[1-2]
\begin{figure}
\includegraphics{example-image-a}
\caption{example-image-caption}
\label{imga}
\end{figure}
\lipsum[1-2]
\begin{figure}
\includegraphics{example-image-b}
\caption{example-image-caption}
\label{imgb}
\end{figure}
\lipsum[1-2]
\begin{figure}
\includegraphics{example-image-c}
\caption{example-image-caption}
\label{imgc}
\end{figure}
\end{document}

This will write informations to external file mainfilename.img
New files
\documentclass{article}
\usepackage{mwe}

\newcommand*{\myimage}{}
\newcommand*{\myfile}{example-image-c}
\newcommand*{\mtfigureinserted}[2]{%
\renewcommand*\myimage{#1}%
\ifx\myimage\myfile
\setcounter{figure}{#2}%
\fi}
\input{newtest.img}

\begin{document}
\lipsum[1-2]
\begin{figure}
\includegraphics{\myfile}
\caption{example-image-caption}
\label{imga}
\end{figure}
\end{document}

One need only to set \newcommand*{\myfile}{example-image-c}.
\mtfigureinserted will set the counter figure to the correct value.


text:
Q: How do I generate an IAM policy for making snapshots? I have volumes mounted on EC2 instances of which I would like to make snapshots.
I created a new IAM user with the following policy:
{
  "Statement": [
    {
      "Sid": "...",
      "Effect": "Allow",
      "Action": [
        "ec2:CreateSnapshot",
        "ec2:CreateTags",
        "ec2:DeleteSnapshot",
        "ec2:DescribeAvailabilityZones",
        "ec2:DescribeSnapshots",
        "ec2:DescribeTags",
        "ec2:DescribeVolumeAttribute",
        "ec2:DescribeVolumeStatus",
        "ec2:DescribeVolumes"
      ],
      "Resource": [
        "arn:aws:ec2:eu-west-1:MY_USER_ID"
      ]
    }
  ]
}

I have added the access key and secret to my ~/.bashrc and sourced it. When I run ec2-describe-snapshots I get this response: Client.UnauthorizedOperation: You are not authorized to perform this operation.
When my "Resource" was just "*" I was able to list all types of Amazon's snapshots. I am looking to create snapshots owned by/visible to just me in the eu-west-1 region.

A: As wisely posted at How can I limit EC2 describe images permissions, resource level permissions are not implemented at all on ec2:Describe* actions.
In Reality you need to limit access based on other things and not the resource ARN.


text:
Q: Property of Dirichlet character (Apostol 8.17) We may use the following theorem,

Let  $\chi$ be a Dirichlet character modulo $k$ and assume $d|k , d<k$. Then the following two statement are equivalent:

*

*$d$ is an induced modulus for $\chi$

*There is a character $\psi$ modulo $d$ such that  $\chi(n) = \psi(n)\chi_{1}(n)$ for all $n$, where $\chi_1$ is the principal character modulo $k$.

And I wanna show that, if $k$ and $j$ are induced moduli for $\chi$ then so is their gcd $(k, j)$.
Using the theorem presented above, I can roughly see that the statement is true. But I do not know how to start the proof.

A: Here is the proof of Theorem 8.17 given in Tom Apostol's book (page 170, fifth edition):
Assume that $2.$ holds. Choose $n$ satisfying $(n,k)=1$ and $n\equiv 1 \bmod d$. Then $\chi_1(n)=\psi(n)=1$ so that $\chi(n)=1$ and hence $d$ is an induced modulus. Thus $2.$ implies $1.$ For the converse (which is much longer), see Apostol's text. One exhibits a character $\psi$ modulo $d$ for which $\chi(n)=\psi(n)\chi_1(n)$ holds for all $n$ using Dirichlet's theorem. More precisely, if $(n,d)>1$ we can just take $\psi(n)=0$. For $(n,d)=1$ we need to find an integer $m$ such that $m\equiv n \bmod d$ with $(m,k)=1$. This is where Dirichlet's theorem on infinitely many primes in arithmetic progressions is used.


text:
Q: Q[x,y]/(x) = Q[y]? I tried to use R[x]/I =(R/I)[x] to prove it and somewhat done. The thing is tho i'd like to see how it should be written formally and how to interpret terms such as (Q[y])[x]/ (x) provided it is correct.
Due to my poor understanding of ring theory in general, please explain as elementary and baic you could.

A: For any commutative ring $\,R\,$ we have $\,R[x]/(x) \cong R.\,$ Indeed the evaluation hom $\,R[x]\to R\,$ via $\,x\mapsto 0\,$ has kernel $\,(x),\,$ since $\,f(0)=0\iff x\mid f(x)\,$ by the Factor Theorem.
Yours is the special case $\, R = Q[y],\,$ since $,Q[x,y]\cong (Q[y])[x].$

A: The easiest way, probably, is to define $f:R[x,y]\rightarrow R[y]$ by $f|_{R[y]} = \text{id}_{R[y]}$ and $x\mapsto 0$. You can check that this is a homomorphism. Next we check that the kernel of this map is $(x)$, so that our result follows by the first isomorphism theorem. Note that $f(x) = 0$, so $(x)\subseteq\ker(f)$. Next, choose $\alpha\in R[x,y]$ and suppose $f(\alpha) = 0$. Define $\tilde{\alpha}$ as the polynomial $\alpha$ with all factors that contain $x$ removed. Then $\tilde{\alpha}\in R[y]$ and $f(\alpha) = f(\tilde\alpha) = \tilde\alpha$. Thus $f(\alpha)=0$ iff $\tilde\alpha=0$ iff $\alpha\in(x)$. We conclude that $\ker(f)\subseteq(x)$, which concludes the statement.

A: The universal property of free $R$-algebras tells you you can define a map $R[x_1,\cdots,x_n] \to A$ (where $A$ is also an $R$-algebra) by simply saying where the elements $x_1,\cdots,x_n$ get mapped to ; then you extend by "polynomiality" (in the same way that in the theory of vector spaces, you map the elements of a basis and then you "extend by linearity").
Thus if you want to define a map $R[x,y]/(x) \to R[t]$, this is equivalent to defining a map $R[x,y] \to R[t]$ with kernel containing $(x)$ ; so just send $x$ to $0$ and $y$ to $t$, which gives you a map $R[x,y]/(x) \to R[t]$. Using the universal property again, you get a map $R[t] \to R[x,y]/(x)$ by sending $t$ to the equivalence class of $y$ in the quotient ring. Now you have two maps and you can easily check that they are inverse of each other ($t \longleftrightarrow y+(x)$), hence you have your isomorphism.
Otherwise, the trick $R[x,y]/(x) \simeq (R[x])[y]/(x) \simeq (R[x]/(x))[y] \simeq R[y]$ works too, but at each step you have a (trivial) isomorphism to check. It's up to you to choose where you like to work.
Hope that helps,


text:
Q: Application Loader/Xcode Stuck on 'Verifying Assets with the App Store" While trying to upload my application to App Store Connect, I got stuck at "Verifying Assets with the App Store" for 4-5 hours. My network is fine, running at 50-60 upstream, and well over 100 downstream.

A: To fix this issue, I opened the Application Loader, opened the Preferences (⌘ + ,) and navigated to the 'Advanced' tab.
Disable the Signiant and Aspera Transfer Protocols but leave DAV on.


text:
Q: Getting character offset inside nested html tags I've got HTML code similar to this one:

    words words words
    words  words mystery words
    words words words

I'd like to get the character offset of "mystery" with respect to the pre tag using Javascript (native or MooTools). I can get it with respect to the span tag using the anchorNode property, but I can't find a way to get it with respect to the pre tag.

A: You could use a DOM Range to do this:
function getCharOffsetRelativeTo(container, node, offset) {
    var range = document.createRange();
    range.selectNodeContents(container);
    range.setEnd(node, offset);
    return range.toString().length;
}

Example:
var sel = window.getSelection();
var pre = document.getElementById("your_pre_id");
var offset = getCharOffsetRelativeTo(pre, sel.anchorNode, sel.anchorOffset);

Caveats:

*

*This will work in all major browsers except IE <= 8. If you need a solution for IE then I can provide it.

*This function will count characters inside


text:
Q: Google Maps SQL multiple markers not displaying I am trying to get multiple markers from my SQL
My XML file is drawing the required info as asked and shown in the following link
  http://e-track.biz/map/xml.php

XML from link:
<markers>
<marker MSISDN="27827910119" Time="23:30:35" Date="2016-01-01" lat="-26.2716" lng="28.22" Radius="971"/>
<marker MSISDN="27827910119" Time="07:31:41" Date="2015-11-05" lat="-26.3274" lng="28.2457" Radius="1460"/>
<marker MSISDN="27827910119" Time="07:31:40" Date="2015-11-05" lat="-26.3274" lng="28.2457" Radius="1460"/>
<marker MSISDN="27827910119" Time="10:13:01" Date="2015-10-09" lat="0" lng="0" Radius="0"/>
<marker MSISDN="27827910119" Time="16:38:19" Date="2015-10-04" lat="0" lng="0" Radius="0"/>
</markers>

The problem like most other I see on the site is that it is not showing the markers for me.
Here is my HTML file to try and download the markers onto the map as shown
 <!DOCTYPE html >

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>

I am using the sample in google maps tutorials It shows the map but not the markers assistance would be appreciated

A: There is a javascript error (Uncaught ReferenceError: type is not defined) generated by this line of your code:
var icon = customIcons[type] || {};

If you don't want custom icons, remove that line and change the definition of your markers to:
var marker = new google.maps.Marker({
    map: map,
    position: point,
    });

(because icon won't be defined)
live example
code snippet:

function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(47.6145, -122.3418),
    zoom: 13,
    mapTypeId: 'roadmap'
  });
  var infoWindow = new google.maps.InfoWindow;

  // downloadUrl("SO_20160101.xml", function(data) {
  var xml = parseXml(xmlData); // data.responseXML;
  var markers = xml.documentElement.getElementsByTagName("marker");
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < markers.length; i++) {
    var MSISDN = markers[i].getAttribute("MSISDN");
    var Time = markers[i].getAttribute("Time");
    var Radius = markers[i].getAttribute("Radius");
    var point = new google.maps.LatLng(
      parseFloat(markers[i].getAttribute("lat")),
      parseFloat(markers[i].getAttribute("lng")));
    bounds.extend(point);
    var html = "" + MSISDN + "
" + Time;
    var marker = new google.maps.Marker({
      map: map,
      position: point,
      // icon: icon.icon
    });
    bindInfoWindow(marker, map, infoWindow, html);
  }
  map.fitBounds(bounds);
  // });
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
    new ActiveXObject('Microsoft.XMLHTTP') :
    new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('MicrosoftXMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }
}

google.maps.event.addDomListener(window, "load", load);

var xmlData = '<markers><marker MSISDN="27827910119" Time="15:09:32" lat="-26.0" lng="28.0" Radius="3"/><marker MSISDN="27827910119" Time="19:07:32" lat="-26.2726" lng="28.2179" Radius="1206"/><marker MSISDN="27827910119" Time="19:08:56" lat="-26.2726" lng="28.2179" Radius="1206"/><marker MSISDN="27827910119" Time="19:21:29" lat="-26.2726" lng="28.2179" Radius="1206"/><marker MSISDN="27827910119" Time="21:58:13" lat="-26.2615" lng="28.2037" Radius="148"/><marker MSISDN="27827910119" Time="22:01:43" lat="-26.2615" lng="28.2037" Radius="148"/><marker MSISDN="27827910119" Time="22:02:07" lat="-26.2615" lng="28.2037" Radius="148"/><marker MSISDN="27827910119" Time="22:02:42" lat="-26.2615" lng="28.2037" Radius="148"/><marker MSISDN="27827910119" Time="22:13:15" lat="-26.2615" lng="28.2037" Radius="148"/><marker MSISDN="27827910119" Time="20:19:30" lat="-26.2615" lng="28.2037" Radius="148"/></markers>';
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}