text:
Q: Django Testing MySQLdb in UnitTest / WebTest I have a WebTest that I'm running using django-webtest against a database in memory.
# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    }
}

There's a piece of code that I just cannot run through the ORM, it runs 5x faster as straight SQL. Yes, I'm familiar with select_related, batch_select and prefetch_related. This is how my SQL code is executed in my view.
db = MySQLdb.connect(host=settings.DATABASES['default']['HOST'],
                user=settings.DATABASES['default']['USER'],
                passwd=settings.DATABASES['default']['PASSWORD'],
                db=settings.DATABASES['default']['NAME'])
            cursor = db.cursor(MySQLdb.cursors.DictCursor)
            cursor.execute("SELECT something FROM sometable WHERE somecondition = 'somevariable';")
            count_queryset = cursor.fetchall()
            cursor.close()
            db.close()

When my test script gets to this point in the view it chokes out with the following error:
File "/srv/reports/views.py", line 473, in my_view
    db=settings.DATABASES['default']['NAME'])
  File "build/bdist.macosx-10.8-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "build/bdist.macosx-10.8-x86_64/egg/MySQLdb/connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (1049, "Unknown database ':memory:'")

I'm not sure why the in memory sqlite3 database works nicely through the ORM but not when I'm using MySQLdb. The same thing happens if I run the code through a unittest.TestCase, too. Any ideas?

A: As alecxe points out in comments, you can't use MySQLdb connections and cursors with a sqlite3 database. Here was my quick and dirty workaround, which probably isn't suitable for any code you're going to have in production. I replaced my connection string with the sqlite3 equivalent:
import sqlite3
db = sqlite3.connect("settings.DATABASES['default']['HOST']")
cursor = db.cursor() # No direct equivalent to MySQLdb.cursors.DictCursor
cursor.execute("SELECT something FROM sometable WHERE somecondition = 'somevariable';")
...


text:
Q: Property of a positive Lebesgue measure set in $\mathbb{R}^n$ Let $E\subset\mathbb{R}^n$ be a positive Lebesgue measure set. Can we always find a $x\in E$ such that for any $r>0$, $B(x,r)\cap E$ is positive Lebesgue measure in $\mathbb{R}^n$?
($B(x,r)$ denotes the ball of radius $r$ with centre at $x$ in $\mathbb{R}^n$)

A: For ae. $x \in E$ we have $\lim_n {1 \over m B(x,{1 \over n}) }  \int_{B(x,{1 \over n})} 1_E(t)dt = 1_E(x)$.
Pick any $x$ for which we have equality, then ${m (E \cap B(x,{1 \over n})) \over m B(x,{1 \over n}) } \to 1$.
In particular, for some $N$, if $n \ge N$ then $m (E \cap B(x,{1 \over n})) \ge {1 \over 2}{m B(x,{1 \over n}) } >0$.
Since $r \mapsto mB(x,r)$ is increasing we see that $m (E \cap B(x,r)) >0$ for all $r>0$.
Alternative:
We can prove this directly. Since the Lebesgue measure is inner regular, we can assume that $E$ is compact.
Now suppose that for all $x \in E$ there is some $r>0$ such that $m(E \cap B(x,r)) =0 $.
The $B(x,r)$ form an open cover of $E$ and hence there is a finite subcover
$B(x_k,r_k)$. Then
$mE \le \sum_k m (E \cap B(x,r)) = 0$.
Hence there is some $x$ such that for all $r >0$ we have $m(E \cap B(x,r)) >0 $.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if the postcode exists in the current country on the checkout page I want to check if the postcode exists in the current country on the checkout page. How to implement this? or maybe someone knows a module that does it? Thanks for any help

A: Your requirements: check if the postcode exists in the selected country on the checkout page, when the customer clicks Next go to the payment step from the shipping step.
In other words, that is "check if the postcode is valid in the shipping step on the checkout page".
Solution:

*

*Frontend development: Using JS to check the postcode when the customer clicks Next go to the payment step from the shipping step, here send an ajax to the controller to check if the postcode exists in the selected country from the backend and then throw the error message if the postcode does not exist in the selected country.

*Backend development: create a controller to handle validating the postcode for the selected country.

More details in implementation:
Frontend:
When the customer clicks Next go to the payment step in the shipping step, it calls setShippingInformation function which calls validateShippingInformation.
So you should create a JS mixin to extend validateShippingInformation function which is declared in vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js.
In validateShippingInformation function in your JS mixin file, check if the validateShippingInformation function from the parent object (in vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js) returns true then you writing the validation for the postcode here. Note: you have to take care both the postcode from the new shipping address form and the selected existing shipping address (logged-in user).
In your validate function, get current shipping address post code, country_id and send it to the controller via Ajax. And then throw the error message if the postcode does not exist in the selected country.
Backend:
Create a controller to validate the postcode and return response. That controller:

*

*implement HttpPostActionInterface.

*inject Magento\Framework\App\RequestInterface into the constructor to get request params.

*inject Magento\Framework\Controller\Result\JsonFactory into the constructor to return response.

*inject Magento\Directory\Model\Country\Postcode\ValidatorInterface into the constructor to validate postcode for selected country.


text:
Q: Is this definition of group isomorphism equivalent to the standard one? Given two groups $(G_A, *_A)$ and $(G_B, *_B)$, can we define a group isomorphism $f : G_A \rightarrow G_B$ by

*

*$G_A$ and $G_B$ have the same number of elements

*with matrix $A$ such that $A_{ij}=i*_Aj$ and matrix $B$ such that $B_{ij}=i*_Bj$, then for all $i,j,x,y \in G_A$, if $A_{ij}=A_{xy}$ then $B_{f(i)f(j)}=B_{f(x)f(y)}$

and if so, how to prove that this definition is equivalent to the standard one?

A: I don't think this is equivalent.  For if, for example, $G_A = G_B = \mathbb{Z}/2\mathbb{Z}$ (thought of as the set $\{0,1\}$), but we define $f(0) = 1$ and $f(1) = 0$, then I think $f$ is an isomorphism according to your definition, but it isn't actually an isomorphism.
First, it's not an isomorphism (according to the usual notion of isomorphism) because it doesn't map the identity to the identity, so it's not even a homomorphism.
On the other hand, $$A = B = \begin{bmatrix} 0 & 1\\1&0 \end{bmatrix}.$$
Then, one can check that $A_{00} = A_{11}$ and $B_{f(0)f(0)} = B_{f(1)f(1)}$, and similarly that $A_{01} = A_{10}$ and $B_{f(0)f(1)} = B_{f(1)f(0)}$.
Edit:
In fact, it's worse than I thought.  In the example I gave, the 2 groups were actually isomorphic, but we have the following fact:
If $G_A$ and $G_B$ have the same number of elements, then they must be "isomorphic" according to your definition.  Let $f:G_A\rightarrow G_B$ be any constant map.  Then we have $B_{f(a)f(b)} = B_{f(x)f(y)}$ for any choices of $a,b,x,y$.
So, for example, $\mathbb{Z}/2\mathbb{Z}\times \mathbb{Z}2\mathbb{Z}$ and $\mathbb{Z}/4\mathbb{Z}$ are "isomorphic" according to your definition, but they aren't isomorphic at all.

A: The condition (which I'll call $P$) actually does say something interesting if we add the assumption that $f$ is a bijection.

Theorem. Let $G$ and $H$ be groups. A bijection $f:G\to H$ has property $P$ iff there are an isomorphism $h:G\to H$ and a $z\in Z(H)$ such that $f(g)=h(g)z$ for each $g\in G$.

Proof. Suppose first that $f$ has property $P$. Note first that if $a,b\in G$ and $ab=ba$, then $f(a)f(b)=f(b)f(a)$, so $f(1_G)\in Z(H)$. Let $z=f(1_G)$, and define $h:G\to H:g\mapsto f(g)z^{-1}$. Then for $a,b\in G$ we have $$h(a)h(b)=f(a)z^{-1}f(b)z^{-1}=f(a)f(b)z^{-2}=f(ab)f(1_G)z^{-2}=f(ab)z^{-1}=h(ab)\;,$$
since $ab=(ab)1_G$, so $h$ is an isomorphism.
Conversely, if $h:G\to H$ is an isomorphism, and $z\in Z(H)$, let $f:G\to H:g\mapsto h(g)z$. If $a,b,c,d\in G$ and $ab=cd$, then
$$f(a)f(b)=h(a)zh(b)z=h(ab)z^2=h(cd)z^2=h(c)zh(d)z=f(c)f(d)\;,$$ and $f$ has property $P$. $\dashv$


text:
Q: Solving IVP by Laplace transform I'm trying to solve an IVP with non-constant coefficients
$$ y'' + 3ty' - 6y = 1, \quad y(0) = 0, \; y'(0) = 0 $$
Taking the Laplace yields
$$ s^2Y + 3(Y + sY') - 6Y = \frac{1}{s}$$
$$ Y' + \left(\frac{s}{3} - \frac{1}{s}\right)Y = \frac{1}{3s^2}$$
The integrating factor is
$$ \mu(s) = \exp\left(\frac{s^2}{6} -\ln s\right) = \frac{1}{s}e^{\frac{s^2}{6}}$$
Thus
$$ \frac{d}{ds}\left( \frac{1}{s}e^{\frac{s^2}{6}}Y \right) = \frac{1}{3s^3}e^{\frac{s^2}{6}}$$
This where I'm stuck because I'm pretty sure the integral on the RHS is non-elementary.
I do know that the solution supposed to be $y = t^2/2$ and $Y = 1/s^3$

A: I think you meant $y'' + 3 t y' - 6 y = 1$.  Then you should get
$$ s^2 Y(s) - 9 Y(s) - 3 s Y'(s) = \dfrac{1}{s}$$


text:
Q: Bluemix Build Error with Node 7 I have been building a react js application which is hosted within IBM Bluemix. I have recently had issues with my build stage as part of the CI/CD Pipeline - We believe the issue has been based around the Node version we were using when running the build phase - we are now using Node 7 and are currently recieveing following error based on the archive directory build/ (error message below) :
npm info it worked if it ends with ok
npm verb cli [ '/home/pipeline/nvm/versions/node/v7.0.0/bin/node',
npm verb cli   '/home/pipeline/nvm/versions/node/v7.0.0/bin/npm',
npm verb cli   'build',
npm verb cli   '--verbose' ]
npm info using npm@3.10.8
npm info using node@v7.0.0
npm verb exit [ 0, true ]
npm info ok

Archive directory build/ does not exist. Please check the name.
Finished: FAILED
Any advice or help with this would be appreciated.

A: The error message is usually thrown when you are defining a build directory that doesn't exist because it might not be getting created during your build job. In your pipeline build stage, can you check the "Build archive directory" field in the configuration and make sure the directory listed there exists? Also, you can try leaving the field blank. Let me know how it goes.


text:
Q: InstanceStore WaitForEvents not firing when using WorkflowApplication with a WorkflowIdentity I posted this question on the microsoft forum but wanted to post it here for additional exposure. I have searched everywhere for an example of what I'm trying to do with no luck.
http://social.msdn.microsoft.com/Forums/en-US/wfprerelease/thread/8a424c0b-44f8-4670-8d64-9c7142117b55
Basically, I would like to use the WorkflowApplication along with the WorkflowIdentity and persistence store to accomplish durable delays.  I use WorkflowApplication because we have hundreds of workflows that need to be run dynamically so the WorkflowServiceHost is not really feasible in our scenario.
I used the Microsoft provided example, AbsoluteDelay, as a starting point and it works perfectly.  The problem comes when I try to pass in a WorkflowIdentity to the constructor of the WorkflowApplication.
Then, the WaitForEvents event on the InstanceStore does not fire because it is expecting the default Identity (id 1), not my new Identity (id 2). The line that does store.Execute creates a record in the IdentityOwnerTable with SurrogateIdentityId set to 1 instead of the id of my identity.
How can I tell the InstanceStore to use my new Identity and not the default one? It seems as if it is something that can be passed through in the CreateWorkflowOwnerCommand metadata.
// Create the InstanceStore
SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(_workflowDB);

// A well known property that is needed by WorkflowApplication and the InstanceStore
private static readonly XName _workflowHostTypePropertyName = XNamespace.Get("urn:schemas-microsoft-com:System.Activities/4.0/properties").GetName("WorkflowHostType");

// Create the XName for the workflow using the workflow's unique name
XName wfHostTypeName = XName.Get(workflowName);

// Configure a Default Owner for the instance store so instances can be re-loaded from WorkflowApplication
private static InstanceHandle CreateInstanceStoreOwner(InstanceStore store, XName wfHostTypeName)
{
    InstanceHandle ownerHandle = store.CreateInstanceHandle();
    CreateWorkflowOwnerWithIdentityCommand ownerCommand = new CreateWorkflowOwnerWithIdentityCommand()
    { //changed from CreateWorkflowOwnerCommand (did not fix problem)
        InstanceOwnerMetadata =
        {
            { _workflowHostTypePropertyName, new InstanceValue(wfHostTypeName) },
            // Something here to identify the WorkflowIdentity ??
        }
    };
    store.DefaultInstanceOwner = store.Execute(ownerHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner;
    return ownerHandle;
}

private static void WaitForRunnableInstance(InstanceStore store, InstanceHandle ownerHandle)
{
    // Only fires when using default Identity
    IEnumerable<InstancePersistenceEvent> events = store.WaitForEvents(ownerHandle, TimeSpan.MaxValue);
    bool foundRunnable = false;
    // Loop through the persistence events looking for the HasRunnableWorkflow event (in this sample, it corresponds with
    // the workflow instance whose timer has expired and is ready to be resumed by the host).
    foreach (InstancePersistenceEvent persistenceEvent in events)
    {
         if (persistenceEvent.Equals(HasRunnableWorkflowEvent.Value))
         {
             foundRunnable = true;
             break;
         }
    }
    if (!foundRunnable)
    {
        throw new ApplicationException("Unexpected: No runnable instances found in the instance store");
     }
}


text:
Q: htaccess rewrite rule fails on https redirection my htaccess look like this
RewriteEngine On
RewriteCond %{HTTP_HOST} !^localhost$
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^login/?(.*)$ login.php$1 [L]
RewriteRule ^register/?(.*)$ register.php$1 [L]

i want to redirect my pages login and redirect to https and so i added the code below
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/(login|register)/?$
RewriteRule .*$ http://%{HTTP_HOST}%{REQUEST_URI} [L]

so when i type http://www.xyz.com/login/ it redirects to https://www.xyz.com/login/ everything was fine when i decided to redirect the pages to http which are not login or register and i wrote
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/(login|register)/?$
RewriteRule .*$ http://%{HTTP_HOST}%{REQUEST_URI} [L]

after that i testted the url http://www.xyz.com/login/ again and it redirects me to https://www.xyz.com/login.php
any idea to redirect http://www.xyz.com/login/ to https://www.xyz.com/login/ and on that page when i click the link https://www.xyz.com/news/1/ redirect to http://www.xyz.com/news/1/

A: Try adding this right below the RewriteEngine On line:
RewriteCond %{HTTPS} off
RewriteRule ^(login|register)(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

RewriteCond %{HTTPS} on
RewriteRule !^(login|register) http://%{HTTP_HOST}%{REQUEST_URI} [L,R]

It also looks like you've pasted your rules wrong, the two blocks of rules are identical.


text:
Q: Javascript - Get custom attribute of each selectpicker selected value I receive an array of objects which are the selected options of a bootstrap selectpicker using var roles = $("#adminUserRoles").find("option:selected");. I would like to loop over each item in roles and get a custom attribute data-value however no matter what I try I can't seem to get each item as an object, I rather get it as a chunk of html.
Edit: I iterate the set using
roles.each(function(item, index){
                console.log(item.attr('data-value');
                console.log(roles[index].attr('data-value')
            });

and receive Uncaught TypeError: item.attr is not a function
HTML:
<select class="selectpicker" multiple="" data-live-search="true" id="adminUserRoles" name="roles" title="Current Role(s)" data-value="post" tabindex="-98">
   <optgroup label="Group 2">
      <option name="User" value="User" data-value="Group 2">User</option>
   </optgroup>
   <optgroup label="Group 1">
       <option name="User" value="User" data-value="Group 1">User</option>
   </optgroup>
</select>

A: You are very close.
Try the following,
    var roles = $("#adminUserRoles").find(':selected');

    $.each(roles , function (index, option) {

        var value = $(option).data("value");
    });

A: This will work

$("#but").on("click", function() {
  const vals = $("#adminUserRoles")
    .find("option:selected")
    .map(function() { return $(this).data("value")}).get();
  console.log(vals);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectpicker" multiple="" data-live-search="true" id="adminUserRoles" name="roles" title="Current Role(s)" data-value="post" tabindex="-98">
   <optgroup label="Group 2">
      <option name="User" value="User" data-value="Group 2">User</option>
   </optgroup>
   <optgroup label="Group 1">
       <option name="User" value="User" data-value="Group 1">User</option>
   </optgroup>
</select>
<button type="button" id="but">Click</button>

A: This will also work..
var roles = $("#adminUserRoles option:selected").map(function(){return $(this).data("value");}).get();
console.log(roles);


text:
Q: Articles with the names of pop stars and a word "concert" - which sentences are correct? Could you help me with a proper use of articles?

A. I was at a Madonna concert in London last week.
B. I was at a Madonna's concert in London last week.
C. I was at Madonna concert in London last week.
D. I was at a Madonna's concert in London last week.

What about names and surnames?

E. I was at an Ewa Farna concert in London last week.
F. I was at an Ewa Farna's concert in London last week.
G. I was at Ewa Farna concert in London last week.
H. I was at Ewa Farna's concert in London last week.

And finally what about bands, especially in plural or in foreign language?
Wilki in English means (Wolves)

I. I was at a Wilki concert in London last week.
J. I was at Wilki concert in London last week.
K. I was at Wilki's concert in London last week.
L. I was at a Scorpions concert in London last week.
M. I was at Scorpions concert in London last week.
N. I was at Scorpions' concert in London last week.
O. I was at Scorpions's concert in London last week.

Which versions are correct? What should I use?
Could you provide a good explanation?

A: It's either:

I was at a Madonna concert last week.

or:

I was at Madonna's concert last week.

(You should use either an article or the possessive, but not both.)
The correct sentences in your question are A, E, H, I, K, L, and N. (Some might find O an acceptable alternative to N; consult your favorite style guide for more information.)

As a footnote, the definite article can also be used:

I was at the Madonna concert last week.

(That version would be more likely if the listener already had prior knowledge of the concert.)


text:
Q: DCE image don't run after upgrade to TYPO3 v10 I have upgraded a TYPO3 project from v6 to v10.
Some content of DCE elements aren't working anymore, this is the code there:
TCA:
<config>
    <type>group</type>
    <internal_type>db</internal_type>
    <appearance>
       <elementBrowserType>file</elementBrowserType>
       <elementBrowserAllowed>jpg,jpeg,gif,png</elementBrowserAllowed>
    </appearance>
    <allowed>sys_file</allowed>
    <size>1</size>
    <minitems>0</minitems>
    <maxitems>1</maxitems>
    <show_thumbs>1</show_thumbs>
    <dce_load_schema>1</dce_load_schema>
    <dce_get_fal_objects>1</dce_get_fal_objects>
</config>

Fluid template:
 <f:for each="{field.slide}" as="slide">

                    <f:image src="uploads/pics/{slide.bild}" alt="{slide.titel}" />

How can I fix it to make work again, i have even changed the image to FAL but make error too.

A: Thanks @Julian! I have fixed this issue with change:
                    <f:image src="uploads/pics/{slide.bild}" alt="{slide.titel}" />

to
                    <f:image image="{slide.bild.0}" alt="{slide.titel}" />


text:
Q: Regarding Catching FaultException ex I am using Enterprise application block on my application' server side to handle exceptions.
I am able to successfully handle exception. I have created a custom service fault class to handle exceptions.
Here are my web config enteries...
<exceptionPolicies>
  <add name="WCF Exception Shielding">
    <exceptionTypes>
      <add type="TEST.Infrastructure.ExceptionHandling.Exceptions.TESTBusinessException, Pluto.Infrastructure.ExceptionHandling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
      postHandlingAction="ThrowNewException" name="TESTBusinessException">
        <exceptionHandlers>
          <add logCategory="BusinessLoggingCategory" eventId="501" severity="Error"
            title="Pluto Service Exception" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
            priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="Logging Handler" />
          <add
            type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.FaultContractExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="DefaultFaultContract Handler"
            faultContractType="TEST.Infrastructure.ExceptionHandling.Exceptions.TESTServiceException, Pluto.Infrastructure.ExceptionHandling"
            exceptionMessage="Pluto.Infrastructure.ExceptionHandling.Exceptions.TESTBusinessException {handlingInstanceID}">
            <mappings>
              <add name="Id" source="{Guid}"/>
              <add name="MessageText" source="{Message}"/>
            </mappings>
          </add>
        </exceptionHandlers>
      </add>

But on the client side when i try to catch this exception as
 catch (FaultException<TESTServiceException> fex)
        {
        }

this exception is not caught.
I am able to get the exception message on the client side which i have writen in app.config on server side.
Can any one please help me figure out the problem.
Thanks in advance
Vikram

A: Try extracting the exception details using the XmlReader:
catch (FaultException ex)
{
    string msg = "FaultException: " + ex.Message;
    MessageFault fault = ex.CreateMessageFault();
    if (fault.HasDetail)
    {
        System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
        if (reader.Name == "TESTServiceException")
        {
            TESTServiceException detail = fault.GetDetail<TESTServiceException>();
            msg += "\n\nStack Trace: " + detail.SomeTraceProperty;
        }
    }
    MessageBox.Show(msg);
}

More explanation on catching fault exceptions here and here.

A: Have you defined fault contract on the operation ?
[FaultContract(typeof(TESTServiceException))]

Have you defined the [ExceptionShielding] attribute on the service contract ?
Also the following service behavior should be set
 <behaviors>
      <serviceBehaviors>
        <behavior name="StandardBehaviour">
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
 </behaviors>


text:
Q: In Flutter, navigating to a page that have a heavy widget is too slow in an old device environmnet I'd like to implement Survey Platform
A survey has many questions and each of them has a part (ex. Part1, Part2, and so on...)
Each part is displayed in one page. (One page equals to one page)
After user finished the survey, they could check the result in one page. That page has a SingleChildScrollView and the SingleChildScrollView contains all of the question's answers. (This is a client's request, so it could not be revised)
Also, I have selected GetX library to administrate State and used RxDart to manage async.
At the onInit method in a answers page's controller, I call the result api and save it to RxList variable.
In answers page's view, if the RxList variable's value is null, it builds CircularProgressIndicator. And in a case of not null, it builds SingleChildScrollView.
I'd like to make the answers page right away pop up when the Get.toNamed method is called and the CircularProgressIndicator has been displayed until the RxList variable is initialized.
But, when I called the Get.toNamed method, the screen had been stoped in the page that called Get.toNamed method. And a few seconds later, the answers page finally pop up.
What should I do to solve this problem?? My code is like belows.
// Survey Answers View
class SurveyResultDetailView extends BaseView<SurveyResultDetailController> {
  @override
  PreferredSizeWidget? appBar(BuildContext context) {
  @override
  Widget body(BuildContext context) {
    return Obx(
      () {
        if (controller.surveyDiagnosisUiModel == null) {
          return CircularProgressIndicator();
        }

        return SingleChildScrollView(
          child: Column(
            children: [
              So long childrens~~~
            ],
          ),
        );
      }
    );
  }
}

// Survey Answers Controller
class SurveyResultDetailController extends BaseController {
  final PreferenceManager _preferenceManager =
      Get.find(tag: (PreferenceManager).toString());

  late final String surveyConfigId;

  final Rxn<SurveyDiagnosisResultUiModel> _rxModel =
      Rxn<SurveyDiagnosisResultUiModel>(null);

  SurveyDiagnosisResultUiModel? get surveyDiagnosisUiModel => _rxModel.value;

  void setSurveyDiagnosisUiModel(SurveyDiagnosisResultUiModel? value) {
    _rxModel.value = value;
  }

  final RxList<SurveyQuestionListUiModel> _surveyQuestionListUiModel =
      RxList<SurveyQuestionListUiModel>();

  List<SurveyQuestionListUiModel> get surveyQuestionListUiModel =>
      _surveyQuestionListUiModel.toList();

  void getDiagnosisResultUiModel() {
    Future<String> diagnosisResultFuture =
        _preferenceManager.getString('recent_detail_result');

    callDataService(
      diagnosisResultFuture,
      onSuccess: _handleDiagnosisResultResponseSuccess,
    );
  }

  void _handleDiagnosisResultResponseSuccess(String response) {
    ~~~~~ response entity mapping to ui model code

    _surveyQuestionListUiModel.refresh();
  }

  List<SurveyQuestionListUiModel> parseQuestionListByPartNumber(int number) {
    return surveyQuestionListUiModel
        .where((element) => element.partNumber == number)
        .toList();
  }

  /// ------------> 생애설계 행동 진단 결과 관련 값

  @override
  void onInit() {
    surveyConfigId = Get.arguments as String;
    getDiagnosisResultUiModel();
    super.onInit();
  }
}


text:
Q: Videojs-youtube: How to config with VideoJS in ReactJS I want to create a Video Player in ReactJS with VideoJS that can run with a Youtube link
I followed the instruction in VideoJS Guide Page with the functional component (https://videojs.com/guides/react/#react-functional-component-and-)
But I don't know how to integrate videojs-youtube(https://github.com/videojs/videojs-youtube) as a plugin that can use in techOrder.
{
  autoplay: true,
  controls: true,
  responsive: true,
  fluid: true,
  sources: [
    {
      type: 'video/youtube',
      src: 'https://www.youtube.com/watch?v=kjlu9RRHcbE',
    },
  ],
  techOrder: ['html5', 'youtube'],
}

I tried some solutions by adding a script into body but didn't work
Screenshot of error


text:
Q: Clustered column chart in C# using Chart in Windows Forms Application I would like to create a clustered column chart like the one shown in the image.

From my research, the best option is to use a DataTable to create this format in C#. However, I have a List of my BoardYield Class (List) which contains members such as monthly passCount, failCount, monthlyYieldPercentage, overallYield, and other such members.
I would like to create a clustered column chart that has a quarterly or monthly breakdown for different board part numbers. I would like to format my Chart Series such that I can use my List list and get the data to look like the image without switching to a DataTable.
Do I have an option for this? How would I format my Series using a List to create a chart as shown?
Thank you!


text:
Q: in doing/by doing/while doing
By/in doing X, Y happens.

I am trying to understand the subtle difference between "by doing X" and "in doing X" .

This thread's responder says that: " Both "by doing X" and "in doing X" form non-finite adjunct clauses of cause or reason. In the most general sense, they both mean 'as a consequence of doing X.' Consequently, there are many situations where both items, be and in, sound acceptable."
And suggest using "by doing X" if the the other action, Y, is the "direct result" of the X.
Then suggest using "in doing X" or "by doing X" if X is the "indirect cause" of the other action, Y.

On the other hand, this thread's responder says that: "Using the word "in" means that the action takes place at the same time as something. However "by" is used to denote the manner or reason something was done. "
So "in doing so" actually means "while doing so", but "by doing so" means "because I did so".
+
Supposing this explanation above is correct, I wonder if I can use use "while" in the place of "in" in this kind of situations.

*

*By trying to solve one problem, I created another.

Does this sentence mean "creating another problem" is the direct result of the "trying to solve one problem" ? Do "trying to solve one problem" and "creating another problem" happen at the same time? or "trying to solve one problem" happens first and then "creating another problem" happens as a result of the first action?

*In trying to solve one problem, I created another.

Do "trying to solve one problem" and "creating another problem" happen at the same time? or "trying to solve one problem" happens first and then "creating another problem" happens as a result of the first action?

*While trying to solve one problem, I created another.

What is the difference between this sentence and sentence 2?

*Raskolnikov confesses his crime to Sonia and admits that by
  killing the two women – Alena Ivanovna and her servant and sister,
  Elizabeth - he actually destroyed himself.

Do "killing the two women" and "destroying himself" happen at the same time? or "killing the two women" happens first and then "destroying himself" happens as a result of the first action?

*Raskolnikov confesses his crime to Sonia and admits that in
  killing the two women – Alena Ivanovna and her servant and sister,
  Elizabeth - he actually destroyed himself. (Original one)

Do "killing the two women" and "destroying himself" happen at the same time? or "killing the two women" happens first and then "destroying himself" happens as a result of the first action?

*Raskolnikov confesses his crime to Sonia and admits that while
  killing the two women – Alena Ivanovna and her servant and sister,
  Elizabeth - he actually destroyed himself.

What is the difference between this sentence and sentence 5?

A: Yes, if you created another problem by trying to solve one problem, then the problem you created was caused by you trying to solve the one problem.
Your analysis is good, but you've arrived at these conclusions by substituting a group of words you understand well with a group of words you don't quite understand.
The other problem you created while trying to solve the one problem could have nothing to do with you trying to solve the problem. All it suggests is you created another problem when you were trying to solve the problem. However, if you created another problem in trying to solve one problem, that suggests the other problem had to do with you trying to solve the problem.
While it's unclear how you created another problem, it is clear it was related to your work on the one problem (problem you were originally trying to solve).
Same idea applies to your other example. The sentence with "while" suggests Raskolnikov destroyed himself when he was killing the two women. The sentence with "in" suggests that something about killing the women destroyed him.


text:
Q: Is winlogon.exe ordinarily on the Windows Task Manager/Process list? (At roughly 1656K of mem?)  Just wondering if it's a virus.
Also, separate question: My memory usage for Win-7 64 is hovering at 1 GB.  Nothing on but one instance of my IE browser. Is this a little high?

A: The winlogon.exe process is a core windows process, and it should generally be running. Its memory usage seems fairly low (mine is usually about 3,200k).
As for the memory usage, even though you may only be running IE, the system itself is likely running a couple dozen various services. Some of them tend to be fairly high on the memory usage side, particularly the aggregate svchost.exe processes which can host multiple core windows services. Some of those may use around 200 megs or so of memory each, and there will likely be many other instances that use anywhere from 5-25 megs each. There are also a variety of other core windows services such as csrss, conhost, lsass, etc. that use a few megs each. Windows may also run a variety of other utility services, such as audiodg.exe, a variety of media player and/or media center services, etc.
You should also be aware of other non-application type processes that you may have running. These would include anti-virus and anti-malware programs that usually appear in the system notification area, and possibly other services that you may have installed (for example, DkService.exe is the background Diskeeper Service that defragments your drives if you have Diskeeper installed.)
It should also be noted that many services and applications in newer versions of windows tend to be rather "greedy" in their use of memory. They reserve more for their own use than they actually need, and only releasing unused quantities when the operating system requests it. Some processes may show they are using say 100 megs of memory, when in actuality they are using 30 out of a reserved 100. If other applications need memory, the OS will usually direct applications with higher reserve than usage to free up some of their reserve. If you have limited physical memory (i.e. 2Gb), starting up other processes besides IE should result in changes in memory usage for larger processes. If you have plenty of memory (i.e. 4Gb or more), greedy memory usage is fairly normal, and not something to worry about until it actually causes performance problems.
A base memory footprint of 1Gig is pretty normal for Windows Vista/7. This is largely a result of Microsoft moving services out of the windows kernel, and into distinct user-mode services. While your memory footprint does increase, the benefits of these kinds of changes tend to be more robustness, improved security, more modularity, etc. Greater use of memory by applications also leads to improved performance, as accessing data on disk is still orders of magnitude slower.

A: Yes it is, winlogon.exe is a default Windows Process. 1656K of memory is a perfectly normal usage for winlogon.exe.
About the other question, it depends on other process that are running simultaneously.


text:
Q: How to return stored procedure results into a List of Class when not using entity framework? I have been working with entity framework for quite some time and have gotten quite used to using this to dump data into Lists of Classes.
I am now working on a very old project that doesn't have EF and I don't have the time to convert it over to EF (nor would I as it needs a full rewrite).
I am in there though making some minor adjustments and need to pull back data from a stored procedure.  I want to store the data in a List of Class, class being one that I created on my own.
I know I can use a DataReader and just read each record passed back and create an item of Class and add that to the list.
                List<MyClass> myClassGuy = new List<MyClass>();
                dr = cmd.ExecuteReader(CommandBehavior.Default);

                while (dr.Read())
                {
                    MyClass myClassItemToAdd = new MyClass();
                    myClassItemToAdd.VarA = (dr, "VARA");
                    myClassItemToAdd.VarB = (dr, "VARB");
                    myClassItemToAdd.VarC = (dr, "VARC");
                    //etc
                    myClassGuy.Add(myClassItemToAdd);
                }

I know I can do the above but after using EF for such a long time.  I have to believe there is a better way of doing this?  Is there?

A: I wrote a whole bunch of code to handle this stuff, then found AutoMapper which (generally) does a pretty good job when working with results from SQL queries:
// setup mapping (this is a once-per-execution thing)
if (AutoMapper.Mapper.FindTypeMapFor<IDataReader, MyData>() == null)
    AutoMapper.Mapper.CreateMap<IDataReader, MyData>();

// Read from the DataReader into a list
IList<MyClass> data = AutoMapper.Mapper.Map<IDataReader, IList<MyData>>(dr);

A: One of the great things about EF is that it automates the process of materializing objects stored in the database.
Using ADO.Net, that work falls on you.  You need to read out column values, transform them if appropriate, and put them in the right part of your object.
There's no significantly easier way, without introducing additional frameworks (e.g. AutoMapper), to do that than what you have now.

A: You should write your own reusable methods to make things easier when you work with your next similar task. As about your exact question, no, there is no simpler solution, but nothing stops you from simplifying your future tasks as much as possible.

A: You could refactor what you have, one DAL and SomeClass.
The nice thing about not using EF is you have a lot more control on your app's performance. Doesn't matter how much horse power you have still your jockey must be light.
That is of course if your app is critical or some trivial web page.

A: If you are absolutely unable to use an ORM framework, then you can make then code more generic by modifying your stored procedures to return an XML stream (which should be fairly easy to do) and on the application side, deserialize the stream into objects.
For example, I can define the following data access method which takes a generic type, a name of stored procedure and any number of SqlParameters (optional) and deserializes and returns a list of T. The helper method Deserialize<T> takes in a an XML stream and deserializes it to a List<T>:
public static IEnumerable<T> GetEntity<T>(string storedProcedureName, params SqlParameter[] parameters)
{
    try
    {
        using (SqlConnection connection =
            new SqlConnection("connectionString"))
        {
            connection.Open();
            SqlCommand command = new SqlCommand(storedProcedureName, connection);
            command.CommandType = System.Data.CommandType.StoredProcedure;

            if (parameters != null && parameters.Any())
            {
                command.Parameters.AddRange(parameters);
            }

            string result = (string)command.ExecuteScalar();

            return Deserialize<T>(result);
        }
    }
    catch (Exception ex)
    {
        // Handle the exception
        return (IEnumerable<T>)default(T);
    }
}

private static IEnumerable<T> Deserialize<T>(string xmlStream, params Type[] additionalTypes)
{
    XmlSerializer serializer = additionalTypes == null ? new XmlSerializer(typeof(List<T>))
        : new XmlSerializer(typeof(List<T>), additionalTypes);

    using (var reader = new XmlTextReader(new StringReader(xmlStream)))
    {
        if (!serializer.CanDeserialize(reader))
        {
            return (IEnumerable<T>)default(T);
        }

        return (IEnumerable<T>)serializer.Deserialize(reader);
    }
}

And to use it, I can have something as simple as
IEnumerable<MyObject> myObjects = DataAccess.GetEntity<MyObject>("MyStoredProc");
The stored procedure looks like this:
SELECT t.Id as 'Id', t.Name as 'Name'
FROM MyTable t

FOR XML PATH('MyObject'), ROOT('ArrayOfMyObject')

The only tricky part is to make sure column aliases match the properties on the object. You'll also need to add the [XmlRoot("ArrayOfMyObject")] attribute to the MyObject class.
This seems like a lot of code but if you are truly unable to use a framework or library, this would be a decent path to go IMO.

A: Well it kind of depends. How many properties are you mapping - if it's only a handful then your current approach is probably best, although it's initially onerous it still makes maintenance easy if the SP result set changes.
Then again if we're talking about many fields coming back from the stored procedure, you could use the very lightweight Linq to SQL - it's officially "dead" but still perfect for this kind of thing and it can map to stored procedure results. Or something even lighter like Rob Conery's Massive which at something like 700 loc is a good option.
And of course  Automapper is always an option.
However. If for some reason you can't introduce L2S or any 3rd party packages into the legacy codebase, you could go with a simple reflection based mapper class like the example below.
Given this SQL:
create table MyRecords
(
    ID int identity,
    Name nvarchar(255),
    DateCreated datetime,
    IsSilly bit
)

Insert into MyRecords select 'John',getdate(),0
Insert into MyRecords select 'Andrew',getdate(),1
Insert into MyRecords select 'Steve',getdate(),0
Insert into MyRecords select 'Max',getdate(),1

Then this console app shows how simple it really is to generalise this kind of thing; error checking, etc, omitted for brevity, and it doesn't support multiple result sets, but you get the idea of how little code is required.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;

namespace MiniORM
{
    //Attribute to map SQL result set field to class public instance property
    public class FieldInfo : Attribute
    {
        public string FieldName { get; set; }
        public Type DataType { get; set; }
    }

    public class MyRecord
    {
        [FieldInfo(DataType=typeof(int),FieldName="ID")]
        public int ID { get; set; }
        [FieldInfo(DataType = typeof(string), FieldName = "Name")]
        public string Name { get; set; }
        [FieldInfo(DataType = typeof(DateTime), FieldName = "DateCreated")]
        public DateTime DateCreated { get; set; }
        [FieldInfo(DataType = typeof(bool), FieldName = "IsSilly")]
        public bool IsSilly { get; set; }

        public override string ToString()
        {
            return string.Format("{0}-{1}-{2}-{3}", ID, Name, DateCreated, IsSilly);
        }
    }

    public class FieldInfoDBMapper<T> where T: class,new()
    {
        private readonly Dictionary<string,KeyValuePair<PropertyInfo,Type>> _mapping;

        public FieldInfoDBMapper()
        {
            var t = typeof (T);
            _mapping = new Dictionary<string,KeyValuePair<PropertyInfo,Type>>();
            foreach (var pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var infos = pi.GetCustomAttributes(typeof(FieldInfo));
                if (infos.Any())
                {
                    var fieldInfo = (FieldInfo) infos.First();
                    _mapping.Add(fieldInfo.FieldName,new KeyValuePair<PropertyInfo, Type>(pi,fieldInfo.DataType));
                }
            }

        }
        public List<T> MapFromReader(IDataReader reader)
        {
            List<T> data = new List<T>();
            while (reader.Read())
            {
                T item = new T();
                foreach (var entry in _mapping)
                {
                    var value = Convert.ChangeType(reader[entry.Key],entry.Value.Value);
                    entry.Value.Key.SetValue(item,value);
                }
                data.Add(item);
            }
            return data;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            List<MyRecord> records  =new List<MyRecord>();
            using (
                SqlConnection conn =
                    new SqlConnection("Your connection string here"))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand("Select * from MyRecords", conn))
                {
                    var reader = comm.ExecuteReader();
                    var mapper = new FieldInfoDBMapper<MyRecord>();
                    records.AddRange(mapper.MapFromReader(reader));
                }
            }
            foreach (var record in records)
            {
                Console.WriteLine(record.ToString());
            }
            Console.ReadLine();
        }
    }
}

Output:
1-John-09/05/2014 00:39:37-False
2-Andrew-09/05/2014 00:39:37-True
3-Steve-09/05/2014 00:39:37-False
4-Max-09/05/2014 00:39:37-True

Hope that helps.

A: I have a mapping library for stuff like this. https://www.nuget.org/packages/SprocMapper/
Documentation: https://github.com/gtaylor44/SprocMapper
public class MyClass
{
    string VarA;
    string VarB;
    string VarC;
}

public List<MyClass> GetResults()
{
    using (SqlConnection conn = new SqlConnection("YourConnection"))
    {
        return conn.Select().ExecuteReader<MyClass>(conn, "YourStoredProcedure");
    }
}


text:
Q: Xcode Auto Layout, label next to Switch Having struggles trying to get the following view to work across devices, this is just one of many of my auto-layout issues. I have some text next to a UISwitch, on devices that are large enough I am happy for the text to be on a single line but on smaller devices the text can be split across multiple lines, I just can't get it to work correctly, it either appears like the screenshot or somewhere else messed up no matter what constraints I try to apply.
The middle image is iPhone 7.

A: I know this question is old, but it is something I encountered myself recently.
In the storyboard, you should set the label's horizontal Content Compression Resistance Priority to 749.

A: Looks like the trailing side of the switch is not constrained to align with the trailing side of the text field and other UI elements. Also make sure there is no constraint for the width of the text, as this is what will stretch.


text:
Q: How can I use boost::thread::timed_join with nanoseconds enabled in boost::date_time? Here is some C++ code illustrating my problem with a minimal expample:
// uncomment the next line, to make it hang up:
//#define BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG //needed for nanosecond support of boost
#include <boost/thread.hpp>
void foo()
{
    while(true);
}
int main(int noParameters, char **parameterArray)
{
    boost::thread MyThread(&foo);
    if ( MyThread.timed_join( boost::posix_time::seconds(1) ) )
    {
        std::cout<<"\nDone!\n";
    }
    else
    {
        std::cerr<<"\nTimed out!\n";
    }
}

As long as I don't turn on the nanosecond support everthing works as expected, but as soon as I uncomment the #define needed for the nanosecond support in boost::posix_time the program doesn't get past the if-statement any more, just as if I had called join() instead of timed_join().
Now I've already figured out, that this happens because BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG changes the actual data representation of the timestamps from a single 64bit integer to 64+32 bit. A lot boost stuff is completely implemented inside the headers but the thread methods are not and because of that they cannot adapt to the new data format without compiling them again with the apropriate options. Since the code is meant to run on an external server, compiling my own version of boost is not an option and neither is turning off the nanosecond support.
Therefore my question is as follows: Is there a way to pass on a value (on the order of seconds) to timed_join() without using the incompatible 96bit posix_time methods and without modifying the standard boost packages?
I'm running on Ubuntu 12.04 with boost 1.46.1.

A: Unfortunately I don't think your problem can be cleanly solved as written. Since the library you're linking against was compiled without nanosecond support, by definition you violate the one-definition rule if you happen to enable nanosecond support for any piece that's already compiled into the library binary. In this case, you're enabling it across the function calls to timed_join.
The obvious solution is to decide which is less painful to give up: Building your own boost, or removing nanosecond times.
The less obvious "hack" that may or may not totally work is to write your own timed_join wrapper that takes a thread object and an int representing seconds or ms or whatever. Then this function is implemented in a source file with nothing else and that does not enable nanosecond times for the specific purpose of calling into the compiled boost binary. Again I want to stress that if at any point you fail to completely segregate such usages you'll violate the one definition rule and run into undefined behavior.


text:
Q: Plot3D: ColorFunction depending on (x,y) or z While trying to answer this question I found out "weird" behavior of ColorFunction
Plot3D[x y, {x, -10, 10}, {y, -10, 10}, PlotRange -> Full,
 ColorFunction -> Function[{x, y, z}, Hue@(x y)]]

gives incorrect colors

the virtually identical code (from naive point of view)
Plot3D[x y, {x, -10, 10}, {y, -10, 10}, PlotRange -> Full,
 ColorFunction -> Function[{x, y, z}, Hue@z]]

gives correct plot

Also if you disable ColorFunctionScaling as many posts (e.g. this) suggest
Plot3D[x y, {x, -10, 10}, {y, -10, 10}, PlotRange -> Full,
 ColorFunction -> Function[{x, y, z}, Hue@(x y)],
 ColorFunctionScaling -> False]

the colors are really messed up

So the question - why are the first two plots different? A bug?
I'm using Mathematica 11.1 on Linux.

A: As the documentation on ColorFunctionScaling says,

ColorFunctionScaling is an option for graphics functions that specifies whether arguments supplied to a color function should be scaled to lie between 0 and 1.

In the first plot, $x$ and $y$ are both scaled to the range $[0,1]$. This means that the ColorFunction does not receive $x$ and $y$, but rather $(x+10)/20$ and $(y+10)/20$, and the color is then the hue of $(x+10)(y+10)/400$.
In the second plot, $z$ is scaled to the range $[0,1]$. This means that the ColorFunction does not receive $z$, but rather $(z+100)/200$ as the third argument.
In the third plot, the number of PlotPoints is too small and thus you see Moiré effects.


text:
Q: BluetoothLEDevice.GetGattServicesAsync() throws "Value does not fall within the expected range." exception I wrote a simple app that monitors BLE advertisements. When the app receives an advertisement it calls BluetoothLEDevice.FromBluetoothAddressAsync() and if that call returns a non null value GetGattServicesAsync() is called (see code below). Occasionally GetGattServicesAsync() will throw a  "Value does not fall within the expected range."
private async void WatcherAdvertisementReceivedAsync(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher sender,
                                                 BluetoothLEAdvertisementReceivedEventArgs args)
{
    using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

    if (device == null)
        return;

    try
    {
        var gatt = await device.GetGattServicesAsync();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}


text:
Q: Check whether vector in R is sequential? How can I check whether an integer vector is "sequential", i.e. that the difference between subsequent elements is exactly one. I feel like I am missing something like "is.sequential"
Here's my own function:
is.sequential <- function(x){
    all(diff(x) == rep(1,length(x)-1))
}

A: There's no need for rep since 1 will be recicled:
Edited to allow 5:2 as true
is.sequential <- function(x){
  all(abs(diff(x)) == 1)
}

To allow for diferent sequences
is.sequential <- function(x){
 all(diff(x) == diff(x)[1])
}

A: So, @Iselzer has a fine answer. There are still some corner cases though: rounding errors and starting value. Here's a version that allows rounding errors but checks that the first value is (almost) an integer.
is.sequential <- function(x, eps=1e-8) {
  if (length(x) && isTRUE(abs(x[1] - floor(x[1])) < eps)) {
     all(abs(diff(x)-1) < eps)
  } else {
    FALSE
  }
}

is.sequential(2:5) # TRUE

is.sequential(5:2) # FALSE

# Handle rounding errors?
x <- ((1:10)^0.5)^2
is.sequential(x) # TRUE

# Does the sequence need to start on an integer?
x <- c(1.5, 2.5, 3.5, 4.5)
is.sequential(x) # FALSE

# Is an empty vector a sequence?
is.sequential(numeric(0)) # FALSE

# What about NAs?
is.sequential(c(NA, 1)) # FALSE

A: This question is quite old by now, but in certain circumstances it is actually quite useful to know whether a vector is sequential.
Both of the OP answers are quite good, but as mentioned by Tommy the accepted answer has some flaws. It seems natural that a 'sequence' is any 'sequence of numbers, which are equally spaced'. This would include negative sequences, sequences with a starting value outside different from 0 or 1, and so forth.
A very diverse and safe implementation is given below, which accounts for

*

*negative values (-3 to 1) and negative directions (3 to 1)

*sequences with none integer steps (3.5, 3.6, 3.7...)

*wrong input types such as infinite values, NA and NAN values, data.frames etc.

is.sequence <- function(x, ...)
    UseMethod("is.sequence", x)
is.sequence.default <- function(x, ...){
    FALSE
}
is.sequence.numeric <- function(x, tol = sqrt(.Machine$double.eps), ...){
    if(anyNA(x) || any(is.infinite(x)) || length(x) <= 1 || diff(x[1:2]) == 0)
        return(FALSE)
    diff(range(diff(x))) <= tol
}
is.sequence.integer <- function(x, ...){
    is.sequence.numeric(x, ...)
}
n <- 1236
#Test:
is.sequence(seq(-3, 5, length.out = n))
# TRUE
is.sequence(seq(5, -3, length.out = n))
# TRUE
is.sequence(seq(3.5, 2.5 + n, length.out = n))
# TRUE
is.sequence(LETTERS[1:7])

Basically the implementation checks if the max and min of the differences are exactly equal.
While using the S3 class methods makes the implementation slightly more complicated it simplifies checks for wrong input types, and allows for implementations for other classes. For example this makes it simple to extend this method to say Date objects, which would require one to consider if a sequence of only weekdays (or work days) is also a sequence.
Speed comparison
This implementation is very safe, but using S4 classes adds some overhead. For small length vectors the benefit is the diversity of the implementation, while it is around 15 % slower at worst. For larger vectors it is however slightly faster as shown in the microbenchmark below.
Note that the median time is better for comparison, as the garbage cleaner may add uncertain time to the benchmark.
ss <- seq(1, 1e6)
microbenchmark::microbenchmark(is.sequential(ss),
                               is.sequence(ss), #Integer calls numeric, adding a bit of overhead
                               is.sequence.numeric(ss))
# Unit: milliseconds
# expr                         min       lq     mean   median       uq      max neval
# is.sequential(ss)       19.47332 20.02534 21.58227 20.45541 21.23700 66.07200   100
# is.sequence(ss)         16.09662 16.65412 20.52511 17.05360 18.23958 61.23029   100
# is.sequence.numeric(ss) 16.00751 16.72907 19.08717 17.01962 17.66150 55.90792   100


text:
Q: How to import OSM relations to PostgreSQL databases? I have created PostgreSQL databases using Osm2pgsql. I have all the lines and points data.

*

*How can I import the relations stored in OSM file? for example turn restriction?

*Is there an easy way to visualize it in QGIS? similar to JOSM symbols?

A: The relation data is in table planet_osm_rels.
Osm2pgsql is able to process some kind of relations, like multipolygon, route and boundary. Those are useful for rendering.
Turn restrictions are not used for rendering, so you have to extract the data from the table yourself, and style it like JOSM does.


text:
Q: Can a large amount of arguments deteriorate performance of a ksh or bash script? I'm running a KornShell script which originally has 61 input arguments:
./runOS.ksh 2.8409 24 40 0.350 0.62917 8 1 2 1.00000 4.00000 0.50000 0.00 1 1 4900.00 1.500 -0.00800 1.500 -0.00800 1 100.00000 20.00000 4 1.0 0.0 0.0 0.0 1 90 2 0.10000 0.10000 0.10000 1.500 -0.008 3.00000 0.34744 1.500 -0.008 1.500 -0.008 0.15000 0.21715 1.500 -0.008 0.00000 1 1.334 0 0.243 0.073 0.642 0.0229 38.0 0.03071 2 0 15 -1 20 1

I only vary 6 of them. Would it make a difference in performance if I fixed the remaining 55 arguments inside the script and just call the variable ones, say:
./runOS.ksh 2.8409 24 40 0.350 0.62917 8

If anyone has a quick/general answer to this, it will be highly appreciated, since it might take me a long time to fix the 55 extra arguments inside the script and I'm afraid it won't change anything.

A: There's no performance impact, as you're asking, but I see other threads:

*

*What is the commandline limitation for your system? You mention 61 input parameters, some of them having a length of 8 characters. If the number of input parameters increases, you might have problems with the maximum command length.

*Are you performing 440 million scripts? That's too much, far too much. You need to consider why you're doing this: you mention needing to wait ±153 days for their execution to finish, which is far too much (and unpredictable).


text:
Q: Is it possible to steal foreign app iCloud prefs? I store some preferences in iCloud with a help of [NSUbiquitousKeyValueStore defaultStore]. Can foreign apps get data from my app cloud using my app cloudURL [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] or using something else? If yes, how can I protect my data?

A: As far as I know, every app works in its own sandbox and therefore it is not possible to get data from other (3rd party) apps - it doesn't matter whether they store their stuff in iCloud or on the device.
If you want to provide some data from one of your apps for other apps then you need to provide them on your own server so other apps can download what they need.
But of course the people owning the actual device can access all information stored on the device if they use programs on their computers that allow people to access iPhone's file system.


text:
Q: Temporal filtering (monthly) does not work I want to count how many tasks each letter has, filtered by month (previous and current). It correctly groups the letters but does not filter the month, and all the duplicate counts appear in both columns. Once I have this figured out, I'd like to do a rate between month and month in one more column. I feel that the solution is close, but I have not been able to find it yet. How far am I?
This is my script:
SELECT
    column1 AS 'letter',
    COUNT(`tasks`.`created_at` >= str_to_date(concat(date_format(date_add(now(6), INTERVAL -1 month), '%Y-%m'), '-01'), '%Y-%m-%d')
        AND `tasks`.`created_at` < str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')) AS `previous`,
    COUNT(`tasks`.`created_at` >= str_to_date(concat(date_format(`Lead Task Logs`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')
        AND `tasks`.`created_at` < str_to_date(concat(date_format(date_add(now(6), INTERVAL 1 month), '%Y-%m'), '-01'), '%Y-%m-%d')) AS `current`
FROM my_table
GROUP BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')
ORDER BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')
;

This is the output that I get:

letter
previous
current

A
4
4

A
3
3

B
8
8

C
4
4

D
12
12

D
3
3

E
2
2

E
2
2

This is the output that I want:

letter
previous
current

A
4
3

B
8

C
4

D
12
3

E
2
2

A: I'm not quite catch what do you want to achieve, but based on your example, I think you can do it like this
SELECT
  A.letter
  , A.Previous
  , CASE
     WHEN B.Current = A.Previous THEN '-'
     ELSE B.Current
    END AS Current
FROM
(SELECT
    column1 AS 'letter',
    COUNT(`tasks`.`created_at` >= str_to_date(concat(date_format(date_add(now(6), INTERVAL -1 month), '%Y-%m'), '-01'), '%Y-%m-%d')
        AND `tasks`.`created_at` < str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')) AS `previous`,
FROM my_table
GROUP BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d'
ORDER BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d') A
INNER JOIN
(SELECT
    column1 AS 'letter',
    COUNT(`tasks`.`created_at` >= str_to_date(concat(date_format(`Lead Task Logs`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d')
        AND `tasks`.`created_at` < str_to_date(concat(date_format(date_add(now(6), INTERVAL 1 month), '%Y-%m'), '-01'), '%Y-%m-%d')) AS `current`
FROM my_table
GROUP BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d'
ORDER BY
    str_to_date(concat(date_format(`tasks`.`created_at`, '%Y-%m'), '-01'), '%Y-%m-%d') B ON B.letter = A.letter
;


text:
Q: border-radius gradient with transparent background I have this simple CSS spinner, here:

html {
  background: black;

  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

@keyframes k__common-spin-cw {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}

.wd-spinner {
  height: 30px;
  width: 30px;
  border-style: solid;
  border-color: rgba(255, 255, 255, 0.15);
  border-width: 2px;
  border-radius: 100%;
  border-top-color: #00ba8c;
  -webkit-animation: k__common-spin-cw 700ms linear infinite;
  animation: k__common-spin-cw 700ms linear infinite;
}

Is it possible to have a gradient border with border-radius, and instead of having the tail of the highlighted border-top just abruptly end, make it a nice gradient fade, while also keeping the background transparent?

A: I have removed  the animation and increased the size to make the effect more easily visible.
With a pseudo, I have added a shadow of the same color than the border to create the fade.
Hover on the div and the overflow hidden will be applied, setting the final effect

html {
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.wd-spinner {
  height: 200px;
  width: 200px;
  border-radius: 100%;
  position: relative;
}
.wd-spinner:hover {
  overflow: hidden;
}
.wd-spinner:after {
  content: "";
  position: absolute;
  height: 196px;
  width: 196px;
  border-style: solid;
  border-color: rgba(255, 255, 255, 0.15);
  border-width: 2px;
  border-radius: 100%;
  border-top-color: #00ba8c;
}
.wd-spinner:before {
  content: "";
  position: absolute;
  height: 196px;
  width: 196px;
  top: 2px;
  left: 2px;
  border-radius: 100%;
  box-shadow: -40px -40px 70px -22px #00ba8c;
}


text:
Q: Бот продолжает реагировать на ответ, даже после того, как он уже был дан. Discord.py При ответе бот должен писать, правилен ли он, но после того как ответ уже был дан, и бот написал, был ли он правильным или нет, бот продолжает реагировать на любые сообщения, и говорить, что это не правильный ответ(или правильный).
В общем: нужно чтобы после ответа бот переставал продолжать реагировать на сообщения, до написания команды.

Код:

@bot.command()
async def country(ctx):
    global round
    round = 0
    flags = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
    flag = random.choice(flags)
    await ctx.send('Какой страны этот флаг?')
    await ctx.send(flag)
    if flag == '':
        answ = 'австралия'
    elif flag == '':
        answ = 'аргентина'
    elif flag == '':
        answ = 'афганистан'
    elif flag == '':
        answ = 'болгария'
    elif flag == '':
        answ = 'зимбабве'
    elif flag == '':
        answ = 'израиль'
    elif flag == '':
        answ = 'индия'
    elif flag == '':
        answ = 'иран'
    elif flag == '':
        answ = 'ирландия'
    elif flag == '':
        answ = 'италия'
    elif flag == '':
        answ = 'китай'
    elif flag == '':
        answ = 'испания'
    elif flag == '':
        answ = 'египет'
    elif flag == '':
        answ = 'греция'
    elif flag == '':
        answ = 'дания'
    elif flag == '':
        answ = 'оаэ' or 'арабские эмираты' or 'объединённые арабские эмираты' or 'объединенные арабские эмираты'
    elif flag == '':
        answ = 'украина'
    elif flag == '':
        answ = 'сша' or 'америка'
    elif flag == '':
        answ = 'россия' or 'рф'
    author = ctx.message.author
    round = 1
    if round == 1:
        @bot.event
        async def on_message(message):
            if message.author == author:
                if f'{answ}' in message.content:
                    await ctx.send('Вы угадали!')
                else:
                    await ctx.send(f'Вы проиграли... \nЭто была {answ}')
    round = 0

A: Чтобы функция завершилась вам придётся использовать "return":
if round == 1:
        @bot.event
        async def on_message(message):
            if message.author == author:
                if f'{answ}' in message.content:
                    return await ctx.send('Вы угадали!')
                else:
                    return await ctx.send(f'Вы проиграли... \nЭто была {answ}')


text:
Q: How I can obtain the absolute positions (top and left) of a d3js item? Hello I wanted to get the position of a node or text of d3js to submit a popup from its position, thanks. I have this:
                                nodeEnter.append("a")
                                        .attr("xlink:href", function (d) {
                                            return d.path;
                                        })
                                        .style("text-decoration", "none")
                                        .style("display", function (d) {
                                           return (d.name == node_info.name && d.not_beneficially_held == "true") ? "block" : "none";
                                        })
                                        .append("text")
                                        .attr("x", function (d) {
                                            return (d == root) ? 17 : 15;
                                        })
                                        .attr("y", function (d) {
                                            return (d == root) ? 21 : 25;
                                        })
                                        .attr("text-anchor", function (d) {
                                            return d.children || d._children ? "end" : "start";
                                        })
                                        .text(function (d) {
                                            return "$";
                                        })
                                        .style("fill", function (d) {
                                            return "#4682b4";
                                        })
                                        .on('click', function (d) {
                                            action_click = true;
                                            $('#popup_paid').fadeIn('slow');
                                            $('.popup-overlay').fadeIn('slow');
                                            return false;
                                        })
                                        .on('mouseout', function (d) {
                                            d3.selectAll("a").remove();
                                        });

And this code or the offset jQuery not work for me:
                function getAbsoluteElementPosition(element) {
                  if (typeof element == "string")
                    element = document.getElementById(element)

                  if (!element) return { top:0,left:0 };

                  var y = 0;
                  var x = 0;
                  while (element.offsetParent) {
                    x += element.offsetLeft;
                    y += element.offsetTop;
                    element = element.offsetParent;
                  }
                  return {top:y,left:x};

var pos = getAbsoluteElementPosition(element);
When a normal HTML if I works perfectly.
Thanks in advance and greetings


text: Q: Characteristic functions of character sheaves on tori I am currently reading a set of lecture notes by V. Ostrik and G. Williamson, Character sheaves, tensor categories and non-Abelian Fourier transform. In Theorem 1.1, they make the assertion that the characteristic function $\chi_{\mathcal{L}, \phi}$ is a character of the finite torus $T(\mathbb{F}_q)$. Does anyone know of a reference for a proof of this result, preferably one where the details are all worked out?


text:
Q: Custom Exception handing with Property class in C# I know this is already asked question.I need to develop User Defined Exception Handing along with the property class, But i am not retrieving the newly added property(DSMException.cs properties) Exceptions .  I went through these two solutions-
Custom exception with properties
What is the correct way to make a custom .NET Exception serializable?
I have a Property class -DSMException which contains three properties Type,Message, InnerExceptionMessage, which needs to be dsiplayed.
DSMException.cs
 public class DSMException
    {
        public string Type { get; set; }
        public string Message { get; set; }
        public string InnerExceptionMessage { get; set; }
    }

The Respective custom Exception class is given.
FatalException.cs
 public class FatalException :Exception
    {
        DSMException exception = new DSMException();
        public FatalException():base()
        {

        }

        public FatalException(string? Message): base(Message)
        {
            exception.Type = "FATAL";
            exception.Message = "MESSAGE:" + Message;
        }

        public FatalException(string? Message,Exception ex) : base(Message,ex)
        {
            exception.Type = "FATAL";
            exception.Message = "MESSAGE: " + ex.Message;
            exception.InnerExceptionMessage = "MORE DET: " + ex.ToInnerMostException().Message;
        }
    }

I am throwing exceptions like below code
Channel.cs
 public override void Run(ServiceSettings settings, DataSource dataSource, string path)
 {
 try
{
  var channel = entities.Channels
         .Where(c => c.Name == parameters.Channel)
         .FirstOrDefault();
    if (channel != null)
      {
        // ANY LOGIC
      }
   else
    {
      throw new FatalException("Invalid Channel Name !!!");
    }
}
 catch (FatalException ex)// for channel is null
 {
     throw ex;
 }
catch (Exception ex)
 {
    throw ex;
 }
}

The error raises here during the catching of the Exceptions-FatalExceptions
FolderInvocation.cs (Error)
 private void DoFolderInvocation(DataSource dataSource, Plugin plugin)
{
  // Do type invocation
try
 {
 result = helper.Invoke(importableFile.Path);// This invokes the Run method, I skipped those codes

 if (result == null)
     logger.WriteError($"{dataSource.Key}: Unknown error while processing file '{importableFile.Path}'.");
else if (result.Success == false)
      logger.WriteError($"{dataSource.Key}: Error while processing file '{importableFile.Path}'.
      {result.Message}");
 else
     logger.WriteDebug($"{dataSource.Key}: File '{importableFile.Path}' was processed successfully.
     {result.Message}");
 }
 catch (FatalException exFatal)// **Problem Arises here-> need to get Ex.Type in the FatalException**
 {
   logger.WriteError($"{dataSource.Key}: An error occurred while processing data source:
   {exFatal.Message}");
    throw exFatal;
 }
 catch (Exception ex)
{
 logger.WriteError($"{dataSource.Key}: Invocation error while processing file '{importableFile.Path}'.
 {ex.Message}");
}
}

What I am missing, as far these minimum reproduced code is correct but I need to get Ex.Type in the FatalException. Kindly advice me.

A: If I understand you correctly, you just need to forward the fields as public properties:
public class FatalException: Exception
{
    private readonly DSMException _exception = new DSMException();

    /* ... snip ... */

    public string MyType => _exception.Type;
    public string MyMessage => _exception.Message;
    public string MyInnerExceptionMessage => _exception.InnerExceptionMessage;
}

It does seem to defeat the purpose of the DSMException class a bit however. You could make the DSMException a public property, but I'd strongly suggest to make it immutable beforehand.
I obviously don't know the intended purpose of the DSMException class, however since all values are assembled in the constructors anyway, you could also directly assign to public properties:
public FatalException(string? Message): base(Message)
{
    Type = "FATAL";
    Message = "MESSAGE:" + Message;
}

public string MyType { get ; }
public string MyMessage { get ; }
public string MyInnerExceptionMessage { get ; }

To continue on the immutability suggestion: You could define your DSMException class like so:
public sealed class DSMException
{
    public DSMException(string type, string message, string innerMessage)
    {
        Type = type;
        Message = message;
        InnerExceptionMessage = innerMessage;
    }

    public string Type { get; }
    public string Message { get; }
    public string InnerExceptionMessage { get; }
}

... and then just make it a public property:
public class FatalException: Exception
{
    /* ... snip ... */

    public DSMException DSM => _exception;
}

It does appear that you still have to duplicate most of the constructor code across FatalException, ErrorException, WarningException etc.
Also note that as long as your custom exceptions only fly around in the same AppDomain, everything is fine; the moment they may cross domain boundaries (e.g. by wire), DSMException needs to be serializable and the serialization methods of your custom exceptions would need to be implemented as well.


text:
Q: Getting the executable name of a QProcess in Qt/C++ Is there any possibility to figure out the executable name/path of a QProcess object? By now I only know that there is QProcess::pid() for identifying a process. Scouring the Qt doc hasn't lead to a useful solution so far.
Thanks in advance!
Example
int main() {
    QProcess* p = new QProcess(this);

    p->start("C:\\test.exe");

    func(p);

    return 0;
}

void func (QProcess* p)
{
     qDebug() << "The application name of the app with pid" << p->pid() << "is" << p->name(); // name() doesn't exist, that's where I need help
}

A: Try to use program() method of the QProcess object, like this:
QProcess process(this);
process.start("calc.exe");
qDebug() << process.program();
process.waitForFinished();


text:
Q: Stylesheets not working in asp.net site under iis7.5 Hi
My app works fine when run from VSWEBdeveloper10.
But from IIS7.5, it doesnt apply stylesheets at all.
I have checked paths.
When I try to access stylesheet directly from browser, it redirects to the app's login page, and after logging in, it shows a weird sqlserver error.
Dont know how it relates CSS to sqlserver.
Note that, app works perfectly fine with VSWebDeveloper2010 while debugging.

A: Are you running the application as a virtual directory under the default website on port 80?  If so, then your stylesheets and images are possibly not being found because the pathing is now incorrect according to the root of the default website.  What works is if you actually create a new website on a separate port.  Then your stylesheets will be found without a problem.


text:
Q: Wordpress / WooCommerce - Product Image has no Link to Add I'm new to Wordpress. I installed the Livre Theme and WooCommerce.
In the Edit Product screen, there is an option to add a Back Cover Image. But, unlike the other fields which have a link at the bottom to say 'Add Product Image' or 'Add Product Gallery Images' the Back Cover Image section has no link.
Can anyone advise me on how to fix this. I have tried contacting the Theme Creator but got no response.
Here's a screenshot showing the problem:

Here's what I've tried:
I've uploaded the dummy content for this theme and what's really bizarre is, when you view this product (see screenshot) the back cover is there. I have no idea where it's getting it from or why it's not there on the product page when the front cover and look inside are.
I've looked everywhere through all the settings and can't figure out why the link is missing.
Thanks!

A: Thanks to @VijayHardaha for his comment which enabled me to get to the bottom of this.
I disabled all the plugins then re-enabled them one-by-one (it should have occurred to me to try this but I'm new to website development).
I found the conflict with Elementor. As soon as you disable that plugin, the Back Cover Link appears.
Not an actual solution (I have no idea how to resolve the conflict) but it's a useful workaround.
Disable Elementor, Add your Back Cover Image and if you want to continue using Elementor, re-enable it. The Back Cover Image remains, it's only the link to change it that disappears.


text:
Q: python module keep crashing I am trying to create a doorbell with a raspberry pi zero. When I press the button it will send a picture to telegram. The module works but, after a few pressed the button the module crash.
and see an error in terminal:
* Error in `python3': double free or corruption (out): 0x01f306e8 *
or I get this error:

python3: malloc.c:2406: sysmalloc: Assertion `(old_top == initial_top
  (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE &&
  prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) ==
  0)' failed.

I hope somebody know how to fix the problem
thanks alot!
python
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
from picamera import PiCamera
import pygame
from settings import getstring
import RPi.GPIO as GPIO

camera = PiCamera()

bot = telepot.Bot('TOKEN')
ring = 'tones/doorbell.mp3'
pin = 22
pressed = 0

pygame.mixer.init()
pygame.mixer.music.load(ring)

def sendpic(chat_id):
    camera.resolution = (1024, 768)
    camera.capture('snapshots/test.jpg')
    photo = open('snapshots/test.jpg', 'rb')
    bot.sendPhoto(chat_id, photo)

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print('Got command: %s' % command)

    if command == '/roll':
        bot.sendMessage(chat_id, random.randint(1,6))
    elif command == '/time':
        bot.sendMessage(chat_id, str(datetime.datetime.now()))
        pygame.mixer.music.play()

        sendpic(chat_id)

MessageLoop(bot, handle).run_as_thread()
print('I am listening ...')

# Define GPIO -pins as standard
GPIO.setmode(GPIO.BCM)

# Define pin X as input and enable internal resistors
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# function for button press
while True:
    input_state = GPIO.input(pin)
    if input_state == False:
        pressed = 1
    else:
        if pressed == 1:
            print('Someone at the door.')
            pygame.mixer.music.play()

            pressed = 0

while 1:
    time.sleep(10)


text:
Q: D3 - access axis tick by index
I have an histogram drawn in D3. X-scale is ordinal.
When I hover specific datum on histogram with mouse cursor, I want the font-weight of corresponding tick text label on X-axis to become bold.
For that purpose I use
.on("mouseover", highlightTickCallback)

callback.
The highlightTickCallback function receives corresponding datum as first parameter, so I could calculate tick index by searching specific key in domain of X-scale. But now, when I have index of tick, I need to access this tick somehow, and I don't understand how could I do that.

A: Something like this would work if you have the tick index:
d3.selectAll(".tick")
.select("text")
.style("font-weight", function(d,i) {return i == yourIndexValue ? 900 : 100})

That will restyle all your ticks so that anything that isn't the mouseovered value will have a light font and the one that is will have a bold font. Keep in mind this will collect all your ticks together, so if you have multiple axes, you'll want to specify the  element that you've hopefully put your axis ticks inside first:
d3.select("#axisX")
.selectAll(".tick")
.select("text")
.style("font-weight", function(d,i) {return i == yourIndexValue ? 900 : 100})

You could also filter the selection of ticks, which might make more sense depending on how much you want to do on mouseover:
d3.select("#axisX")
.selectAll(".tick")
.select("text")
.filter(function(d,i) {return i == yourIndexValue})
.style("font-weight", 900)


text:
Q: How do I train the OSX Auto-Correct to fix my particular brand of typos? I'm proud of my typos.  They are like the proof that I can type way too fast, probably faster than I can think.
I love the auto-correct feature, once I got used to not going "AH! Typo! furious backspacing Retype correctly!"
I have one beef though. It seems that the typos I make are nonstandard enough that about 50% of the time, Auto-Correct chooses the wrong word. This irritates me even more than making a typo in the first place. It seems to happen often with double letter endings where I miss one, but that's certainly not the only case.
Example: When typing the word 'will' I often type 'wil', I have no idea why. Auto-Correct zaps this to 'ail'. So then, instead of backspace, type another L, space, keep going, I have to delete the entire wrong word.
The reason I am asking here is that I don't want to add misspelled words to the dictionary, I want to train the behavior of the Auto-Correct engine itself so that it's more accurate to my typos as opposed to the 'standard' ones.
Is this possible? I can't imagine that there's no capability for learning in that algorithm. I dream of a time when I can just mash away at the keyboard, and the computer just knows what I mean and records my rhoughts (There's another one: it gets instantly set to 'roughest' instead of 'thoughts') accordingly.  If auto-correct can be trained, that takes us a lot closer.

A: There is an easy fix for this.
Open System Preferences. In the window that appears, select keyboard. Click the tab labeled "text". In this window, you can set specific misspelled words to correct to the word you want. Hope this helped!


text:
Q: Does this series that has terms $1/n$, then terms $1/n (\log n)^2$, then terms $1/n \log n (\log \log n)^3$, etc. converge or diverge? Define $\log_{(k)}$ to be the logarithm function iterated $k$ times, where $\log_{(0)}$ is the identity function. Consider the series $\sum_n 1/a_n$ where
$$a_n = (\log_{(f(n))} n)^{f(n)+1} \prod_{k=0}^{f(n)-1} \log_{(k)} n$$
where $f(n)$ is the largest non-negative integer such that $\log_{(f(n))} n \geq 1$. So the terms in the series first look like $1/n$ until $n > e$, and then $1/n (\log n)^2$ until $n > e^e$, and then $1/n (\log n) (\log \log n)^3$ until $n > e^{e^e}$, and then $1/n (\log n) (\log \log n) (\log \log \log n)^4$, etc. Does this series converge or diverge? I believe that if we instead defined
$$a_n   =  (\log_{(f(n))} n)^{M} \prod_{k=0}^{f(n)-1} \log_{(k)} n$$
for a fixed power $M > 1$ then the series would diverge. This generalizes a Putnam problem result that the series diverges when $M=1$, and it's surprising that the series diverges for $M > 1$ because it diverges more slowly and also the formula looks much more like convergent series formulas when $M > 1$ instead of $M = 1$. But anyway, I'm actually interested in the case where $M$ grows linearly with the number of iterated logarithms.


text:
Q: QProcess exception QT I am developing an application that creates and runs another Qprocess. My code is:
QProcess myProcess = new QProcess();
connect(myProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(sendProcessCompleted(int,QProcess::ExitStatus)));
connect(myProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(sendProcessError(QProcess::ProcessError)));

myProcess->start(program, arguments);

void SensorSimulator::sendProcessCompleted(int exitError, QProcess::ExitStatus exitStatus)
{
    if(exitStatus == QProcess::CrashExit)
    {
        QString errorMessage("SensorSimulator is unexpectedly crashed.");
        emit ProcessError(errorMessage);
    }
    else
    {
        QString p_stdout = myProcess->readAllStandardOutput();
        QString p_stderr = myProcess->readAllStandardError();
    }

}

void SensorSimulator::sendProcessError(QProcess::ProcessError error)
{

    QString p_stdout = myProcess->readAllStandardOutput();
    QString p_stderr = myProcess->readAllStandardError();
    QString errorMessage;
    errorMessage = "SensorSimulator is unexpectedly crashed. ProcessError: " + error;
    //emit ProcessError(errorMessage);
}

I am getting this exception in the p_stdout:

Running, to stop press 'S' or close the window.
  Exception Found: Type: System.InvalidOperationException Message:
  Cannot see if a key has been pressed when either application does not
  have a console or when console input has been redirected from a file.
  Try Console.In.Peek.

Can anyone please help?
EDIT: the process I am running is a .Net application

A: The problem was a little specific but the solution may help peoples that have the same error message to understand what it is.
The procees I ran used Console.KeyAvailable property that according to MSDN throws exception when the input to the the process is a redirected input:

InvalidOperationException : Standard input is redirected to a file
  instead of the keyboard.

When I changed it to Console.In.Peek, everything works fine.


text:
Q: model.find method is not returning required fields from database The console.log(correct.password) is returning undefined whereas the if condition results in false.
app.post('/login' , async (req , res)=>
{

   const correct = data.findOne({name : req.body.name}).select({name : 0});
   if(!correct)
   {
    return res.status(400).send("Invalid Username or
    Password")
   };

    console.log(correct.password);

   const passcomp = compare(req , correct);
  if(!passcomp) { console.log("innnncorrect");return

  res.status(400).send("Invalid Username or Password");}

  res.send("Successful");

});

I should get the password of the requested user, but the query I am receiving does not contain neither the name nor the password.
How do I solve the problem?

A: You probably just need to add the await keyword before your query, as you are in an async function:
const correct = await data
  .findOne({ name : req.body.name })
  .select({ name : 0 });


text:
Q: PL/SQL Procedure with DBMS Output within Implicit Cursor Loop I am working on a homework assignment, which requires letter grade updates based on marks.  Both must be done with procedures.  The first using an implicit cursor and the second an explicit cursor.  My explicit cursor procedure works perfectly.  My implicit cursor has two issues however.  The first, it does not seem to update for a mark of 50.  The second, when displaying output it displays the student id but not the updated grade.  Any ideas for fixing these?  Following is what I have so far:
CREATE OR REPLACE PROCEDURE comp_grade_s IS
  CURSOR cur_class IS
    SELECT studid, marks, grade
    FROM class
  FOR UPDATE NOWAIT;
  TYPE type_class IS RECORD
    (studid class.studid%TYPE,
    marks class.marks%TYPE,
    grade class.marks%TYPE);
  rec_class type_class;
  lv_grade_txt class.grade%TYPE;
BEGIN
  OPEN cur_class;
  LOOP
    FETCH cur_class INTO rec_class;
      EXIT WHEN cur_class%NOTFOUND;
      UPDATE class
        SET grade = 'F'
        WHERE marks < 50;
      UPDATE class
        SET grade = 'D'
        WHERE marks >= 50 AND marks < 60;
      UPDATE class
        SET grade = 'C'
        WHERE marks >= 60 AND marks < 70;
      UPDATE class
        SET grade = 'B'
        WHERE marks >= 70 AND marks < 80;
      UPDATE class
        SET grade = 'A'
        WHERE marks >= 80;
      UPDATE class
        SET grade = lv_grade_txt
        WHERE CURRENT OF cur_class;
      DBMS_OUTPUT.PUT_LINE('Student ID: ' || rec_class.studid || ' gets grade ' ||
        lv_grade_txt);
  END LOOP;
  CLOSE cur_class;
END;

Thanks in advance for any assistance,
Emily

A: try this one i don't know why are u not trying to print the grade in the dbms_output from the
record in which you have defined
create or replace PROCEDURE comp_grade_s IS
CURSOR cur_class IS
SELECT studid, marks, grade

FROM class

FOR UPDATE NOWAIT;
TYPE type_class IS RECORD
(studid class.studid%TYPE,

marks class.marks%TYPE,

grade class.grade%TYPE);

rec_class type_class;
BEGIN
OPEN cur_class;
LOOP
FETCH cur_class INTO rec_class;

  EXIT WHEN cur_class%NOTFOUND;

  UPDATE class

    SET grade = 'F'

    WHERE marks < 50;

  UPDATE class

    SET grade = 'D'

    WHERE marks >= 50 AND marks < 60;

  UPDATE class

    SET grade = 'C'

    WHERE marks >= 60 AND marks < 70;

  UPDATE class

    SET grade = 'B'

    WHERE marks >= 70 AND marks < 80;

  UPDATE class

    SET grade = 'A'

    WHERE marks >= 80;

  UPDATE class

    SET grade = lv_grade_txt

    WHERE CURRENT OF cur_class;

  DBMS_OUTPUT.PUT_LINE('Student ID: ' || rec_class.studid || ' gets grade ' ||

    rec_class.grade);

END LOOP;
CLOSE cur_class;
END;


text:
Q: How to make contourf plot based on points boundary? I have a csv file including lan, lon, z values. I've been trying to make contourf based on bellow code :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import geojsoncontour
import utm
import matplotlib.cm as cm
from scipy.spatial import ConvexHull
import alphashape
from descartes import PolygonPatch
from mask import alpha_shape
import math
import matplotlib.ticker as ticker

data_url = 'http://spatialcloud.ir/files/data_1.csv'

df = pd.read_csv(data_url)
df.head()

x,y  = utm.to_latlon(df.lat, df.lon, 39, 'N')
z = df.z

plt.scatter(y,x)

def plot_contour(x,y,z,resolution = 50,contour_method='linear'):
    resolution = str(resolution)+'j'
    X,Y = np.mgrid[min(x):max(x):complex(resolution),   min(y):max(y):complex(resolution)]
    points = [[a,b] for a,b in zip(x,y)]
    Z = griddata(points, z, (X, Y), method=contour_method)
    return X,Y,Z

X,Y,Z = plot_contour(y,x,z,resolution = 50,contour_method='linear')

fig, ax = plt.subplots(figsize=(13,8))
cpf = ax.contourf(X,Y,Z,cmap="rainbow")
fig.colorbar(cpf)
plt.show()

The result is like the below image :
contourf image
But I need to make contourf based on my points boundary like this :
what I want from contourf
I mean I need to make contourf just inside the black polygon which is my points boundray and all colors outside of black polygon get removed.
What should I do???