find a bounded set of real numbers with countably many limit points.

Question: Find a bounded set of real numbers with countably many limit points.
This is a question from Rudin's real analysis. I was wondering if "countably many" includes finite? Or does it have to be countably infinite?
If it includes finite, then I could just find a set with one limit point, ie.
$$\{\; 1 / n\; |\; n = 1, 2, 3, 4, \dots\;\}$$ limit point being zero.
However, if it is the case that I have to find a bounded set of real numbers with countably infinite limit points, I am stumped. Is that even possible?
Comment: Just want to point out that, since Rudin's books was written a few decades ago, a couple of his terminologies bear different meanings today. His "countable" is our "infinite and countable" (our "countable" is his "at most countable"). He also uses "neighbourhood" instead of "open ball". Nowadays "neighbourhood" has a more general definition.
Answer: You correctly constructed a set with one limit point, $0$. Similarly, you can construct a set with the limit point $1$. The union of the two is then a set with two limit points.
Now, if a union of $n$ such sets has $n$ limit points, how would you create a set with countably infinite number of points?
Once you solve that question, you need to also bound your set. For that, let me just give you a hint that $[0,2] = [0,1]\cup [1,\frac32]\cup[\frac32,\frac34]\cup\dots$
Comment: Edit: so they do mean countably infinite right
Comment: would {1/n} U {1/2 + 1/n} U 1{1/3 + 1/n} U ....U {1/m + 1/n} for n = 1,2,3,4,...work? it would be bounded between (0, 1.5) and have as many limit points as there are positive integers
Comment: But you have to be carefull with the original argument, as a countable union of set with one limit points may be a set with an uncountable number of limits points.
Comment: @Tryss True, that's why I said the limit point should be $1$, just to keep in disjoint from the original.
Comment: @mac5 The example you stated is risky. How do you know, for example, that you didn't construct additional limit points?
Comment: if u did the limit points as 0, 1, 2, 3, .... then they would be disjoint but the set would not be bounded. I did the fractions since they tend to zero and would give us a bound.
Comment: @mac5 Yes, I know they would not be bounded, that's why I have you another hint. Look at the last sentence of my answer. It is not obvious that in your (obviously bounded) example, there are only countably many limit points.
Answer: The set
$$\left\{ \frac{1}{2^n} + \frac{1}{k+1} \mid (n,k) \in \Bbb N^2 \right\}$$
has $\{0\} \cup \{\frac{1}{n+1} \mid n\in \Bbb N\}$ as its limits points
Comment: what is N^2 signify? is it the set of all pairs (x,y) with x y being natural numbers?
Comment: @mac5 : yes, it's an usual notation
Comment: that makes sense. so 1/2 ^n makes limit points if we hold n and vary k, giving us 1/2 1/4 1/6... but if we hold k and vary n, then we get 1/2, 1/3, 1/4, 1,5. since one is included within the other, we only need to write the 1/k+1. is that right?
Comment: yes. And each point is isolated, so it's the only limits points (if you add 0)


relation jv_commit already exists

Question: I am using JaVers version 5.8.8, Spring boot 2.1.5, PostgreSQL 42.2.8. Its running fine when application runs first time however error comes application starts second time and so on. It is mentioned in official documentation of JaVers that this issue was fixed in version 5.6.2 but i am using latest version 5.8.8 still this error persists. Below is the error stacktrace: -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2020-01-21 18:30:04.506[0;39m [31mERROR[0;39m [35m59224[0;39m [2m---[0;39m [2m[  restartedMain][0;39m [36mo.s.boot.SpringApplication              [0;39m [2m:[0;39m Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditController' defined in file [D:\billing-system-principal-service\target\classes\com\posti\billing\controller\AuditController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JaversFromStarter' defined in class path resource [org/javers/spring/boot/sql/JaversSqlAutoConfiguration.class]: Invocation of init method failed; nested exception is org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL:
CREATE TABLE jv_commit (
commit_pk BIGINT NOT NULL,
author VARCHAR(200),
commit_date TIMESTAMP,
commit_date_instant VARCHAR(30),
commit_id NUMERIC(22,2),
CONSTRAINT jv_commit_pk PRIMARY KEY(commit_pk)
)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$165.0000000015AA1FF0.getObject(Unknown Source) ~[na:na]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at com.posti.billing.BillingServiceApplication.main(BillingServiceApplication.java:20) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.5.RELEASE.jar:2.1.5.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JaversFromStarter' defined in class path resource [org/javers/spring/boot/sql/JaversSqlAutoConfiguration.class]: Invocation of init method failed; nested exception is org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL:
CREATE TABLE jv_commit (
commit_pk BIGINT NOT NULL,
author VARCHAR(200),
commit_date TIMESTAMP,
commit_date_instant VARCHAR(30),
commit_id NUMERIC(22,2),
CONSTRAINT jv_commit_pk PRIMARY KEY(commit_pk)
)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$165.0000000015AA1FF0.getObject(Unknown Source) ~[na:na]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 25 common frames omitted
Caused by: org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL:
CREATE TABLE jv_commit (
commit_pk BIGINT NOT NULL,
author VARCHAR(200),
commit_date TIMESTAMP,
commit_date_instant VARCHAR(30),
commit_id NUMERIC(22,2),
CONSTRAINT jv_commit_pk PRIMARY KEY(commit_pk)
)
    at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:91) ~[polyjdbc-0.7.6.jar:na]
    at org.polyjdbc.core.schema.SchemaManagerImpl.create(SchemaManagerImpl.java:52) ~[polyjdbc-0.7.6.jar:na]
    at org.javers.repository.sql.schema.JaversSchemaManager.ensureTable(JaversSchemaManager.java:229) ~[javers-persistence-sql-5.8.8.jar:na]
    at org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:47) ~[javers-persistence-sql-5.8.8.jar:na]
    at org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:186) ~[javers-persistence-sql-5.8.8.jar:na]
    at org.javers.spring.jpa.JaversTransactionalDecorator$1.doInTransactionWithoutResult(JaversTransactionalDecorator.java:186) ~[javers-spring-jpa-5.8.8.jar:na]
    at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.javers.spring.jpa.JaversTransactionalDecorator.ensureSchema(JaversTransactionalDecorator.java:183) ~[javers-spring-jpa-5.8.8.jar:na]
    at org.javers.spring.jpa.JaversTransactionalDecorator.afterPropertiesSet(JaversTransactionalDecorator.java:177) ~[javers-spring-jpa-5.8.8.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 37 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: relation "jv_commit" already exists
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:311) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:297) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:274) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:269) ~[postgresql-42.2.8.jar:42.2.8]
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.2.0.jar:na]
    at org.polyjdbc.core.schema.SchemaManagerImpl.ddl(SchemaManagerImpl.java:88) ~[polyjdbc-0.7.6.jar:na]
    ... 48 common frames omitted

Comment: Please help !! Its required urgently.
Comment: @Bartek Walacik : Do you have solution for this ?
Comment: If you think you found a bug you are supposed to report it to our Issues https://github.com/javers/javers/issues, please follow the Guidelines for Bug Reporting https://github.com/javers/javers/blob/master/CONTRIBUTING.md#guidelines-for-bug-reporting
Comment: Thanks for the response. I dont know if its still a bug in JaVers, so asked at this place. Ideally if tables & sequences are created then it should avoid to create. Am i correct or does it work differently ? Anyways i have reported issue at the given link, please look at it.
Answer: looks like bug in JaversSchemaManager:248:
if (schemaName != null) {
            return resultSet.next();
/*248*/            } else {
            String tableSchemaName;
            do {
                if (!resultSet.next()) {
                    return false;
                }

                tableSchemaName = resultSet.getString("TABLE_SCHEM");
            } while(tableSchemaName != null
                    && !tableSchemaName.equalsIgnoreCase("public")
                    && !tableSchemaName.equals("")
                    && (!(this.dialect instanceof MsSqlDialect) || !tableSchemaName.equalsIgnoreCase("dbo"))
                    && (!(this.dialect instanceof OracleDialect) || !tableSchemaName.equalsIgnoreCase("system"))
            );

while loop always exit with false if schema is not defined.
Use .withSchema("SCHEME") it helps for me.

relation jv_commit already exists


Main Menu link to all newsletters and another for Articles

Question: I am very new and not a developer. I would like to create two main menu links for newsletter content type (simplenews) and the core articles type. I want the behavior to be the same as blog.
I assumed that simplenews would add the link when installed but it did not. I have been searching the net for hours, I cannot find a solution.
Thank you in advance for your help.
Answer: How much I understand go to structure > menu > main menu and click "add link" for Drupal 7 and structure > menu > main navigation for Drupal 8

 and for this, you need to create two views one is for newsletter content type and second is for article content type. You can make the view by going to structure > views > add new view for both Drupal 7 and 8. The view type must be page not block.

All the pictures are for Drupal 8. If you need more assistance please let me know.


Close anywhere sldenav overlay

Question: I want to close the menu where you clicked anywhere on the screen
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sidenav
Comment: Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve).
Answer: Add a click event listener to the window and call your closeNav function.
<code>window.addEventListener('click', function(event) {
    if (event.target.tagName === 'HTML') {
        closeNav();
    }
});
</code>
Comment: Well it works but you are lucky (or maybe you knew beforehand) that your window listener executes before the click lestener on the open button or the sidenav would close right after being opened

Close anywhere sldenav overlay


SQL Server 2012 constant CPU load

Question: I'm trying to diagnose an abnormal CPU usage of the sqlservr.exe process from a SQL Server 2012 Express installation.
The installation is running in a VM with Windows Server 2012 R2, 8-core Xeon E5 and 8GB of RAM.
The CPU load (from both ProcessExplorer and Task Manager) stays constantly at around 12%-15%. Restarting the service has no effect, the CPU usage will go right back at the same level a few minutes after restarting.
My biggest problem is that the SQL server was bundled with a third-party software and I don't have sa access to the DB. I was given read only access to the software's database (I can only access views, not tables) but I can't run any reports from SSMS or execute this.
The high CPU consumption definitely comes from the third-party application (if I stop it the load goes back to idle levels) but their support has been so far useless in resolving this issue and I need to deal with it on my own.
Is there anything else I can try to pinpoint the source of the high cpu usage?
Comment: What is the error message returned when you run the statement given as an answer to the question [How do I find out what is hammering my SQL Server?](http://stackoverflow.com/a/945290/1820861)?
Comment: IMO, 12%-15% CPU utilization is hardly "high". How do you know that's "abnormal" for this application? Why are you worried about it? The CPU is a resource to be used, SQL Server is using it, why is that a problem?
Comment: I would be very, very surprised if 12-15% CPU utilization was the cause of the problem.
Comment: `Msg 297, Level 16, State 1, Line 1`
`The user does not have permission to perform this action.`
Comment: Sadly Express is delivered without SQL Server Profiler and other useful tools: [Features Supported by the Editions of SQL Server 2012](https://msdn.microsoft.com/en-us/library/cc645993(v=SQL.110).aspx#Scalability), but even if you had the tools you wouldn't see much with your current permissions. SQL Performance Counters might be an option, but you won't glean any details from them. Only estimates and hints.
Comment: Unfortunately I've had issues where the third-party application cannot connect to the SQL Server anymore and it's impacting some other equipment.
Now what I've noticed is that after a specific operation performed in the application, the sqlservr.exe process goes from 1%-2% CPU load to 12%-15% and stays there, even after service or system restarts.
So far the developer refuses to inspect our installation and blames the problem on system/hardware configuration issues.
Comment: Can you find out the exact version of the SQL 2012 Express Edition? Service Pack Level, Cumulative Update Level, .... There have been issues with CPU spikes and some high CPU levels in some versions of SQL Server. [FIX: Low CPU spikes at a set interval even without user activity in SQL Server 2008 R2 or in SQL Server 2012](https://support.microsoft.com/en-us/kb/2590839)
Answer: You would require at least either the view server state or view database state before you could think of analysing any performance issues inside SQL Server:
What can user do with VIEW SERVER STATE permissions?
Seeing as you are limited to the built-in Windows Performance Monitor you could monitor the following counters to establish any basic issues:

Memory – Available MBytes
Physical Disk – Avg. Disk sec/Read
Physical Disk – Avg. Disk sec/Write
Physical Disk – Disk Reads/sec
Physical Disk – Disk Writes/sec
Processor – % Processor Time
SQLServer: General Statistics – User Connections
SQLServer: Memory Manager – Memory Grants Pending
SQLServer: SQL Statistics – Batch Requests/sec
SQLServer: SQL Statistics – Compilations/sec
SQLServer: SQL Statistics – Recompilations/sec
System – Processor Queue Length

These counters are listed according to the following article SQL Server Perfmon (Performance Monitor) Best Practices.
Seeing as you are having a CPU load the following quote from Brent's article seems adequate:

Look for Obvious CPU Bottlenecks

First, look at the Processor Queue Length for CPU pressure. If this number is averaging 1 or higher (except during the SQL Server's full backup window if you're using backup compression), this means things are waiting on CPUs to become available.

I'm suspicious when this number is over 1, because it often means that people have installed other software on the SQL Server such as applications or web sites. That's a problem. If you get pushback from management saying that they don't want to buy new servers, point out that two CPUs of SQL Server Enterprise licensing cost around $50-60k – which would pay for a separate server for the web app. If you can eliminate applications from the SQL Server, then you don't have to use as much CPU power, and less CPUs mean less licensing costs.

There are more in-depth Perfmon metrics that you can add to your capture if you see the Processor Queue Length showing up, but for junior DBAs, the first thing I would recommend is simply remote desktop into the SQL Server. Right-click on the taskbar, click Task Manager, and click on the Processes tab. Check the box that shows processes for all users, and then click on the CPU column to sort the CPU percentage from high to low. Sit and watch it for a minute or two. Which processes are using CPU power? If it's SQLServer, then we need to do more research, but there's a good chance it's another application, and we need to get that app off this server.  Generally speaking, enabling hyperthreading on a SQL Server is not going to fix that kind of a problem.

If the sqlserver.exe process is the only one with 12-15% load then you will require additional permissions to be able to analyse the root cause.

SQL Server 2012 constant CPU load


Laravel view is not getting session data

Question: I'm trying to pass some data to a view and it appears as though the view is not getting it. Here is the getProfile route in my controller:
public function getProfile($username)
{
    if(User::userExists($username))
    {
        if($username == Auth::user()->username)
            return View::make('user.profile');
        else
            return View::make('user.profile')->with('user-requested', $username);

}

The view is supposed to change based on whether the parameter $username is the user logged in, in which it will display more information and allow editing and if not then limited information will be displayed. I am checking the session 'user-requested' key in my view as follows:
Username: {{ Session::get('user-requested'); }}

and also like the following:
@if(!Session::has('user-requested'))
//display full profile info
@else
//display limited profile info

Currently the view just displays the full profile info block regardless of whether I enter a username parameter that is not the currently logged in user. The session variable 'user-requested' seems to be null but I am unsure why, is there any reason for this?
Answer: You don't need to use Session to get user-requested variable in view, just use it simple something like this.
@if(isset($user-requested))

@else

@endif

To put data in session you have to use Session::put('key','value'). The only way the variables are set in Sessions using with() is when they are used with redirects.
Comment: How can I access the variable $user-requested in the view? It's is stating it's undefined
Comment: `{{$user-requested}}` which is just like ``


JSDoc with TS - show return interface comments in intellisense?

Question: Let's say I have a function whose return value is a defined typescript interface.  The interface is well annotated:
interface ReturnValue {
  /**
   * Wind value, in knots
   */
  wind: number;
  /**
   * Humidity in %
   */
  humidity: number;
}

/**
 * Function to return some values
 * @returns Returner
 */
const myFunction = (): ReturnValue => {
  return {
    wind: 4,
    humidity: 5
  };
};

I'd like to be able to see the annotations of the return value interface when I use intellisense, or when hovering over the function.  Instead, this is what I get:

I get a little more detail when I don't name the interface but declare it directly as the return value of the function:
/**
 * Function to return some values
 */
const myFunction = (): {
  /**
   * Wind value, in knots
   */
  wind: number;
  /**
   * Humidity in %
   */
  humidity: number;
} => {
  return {
    wind: 4,
    humidity: 5
  };
};

This gives:

But even this doesn't the show comments I used when defining the return value object shape.  Also its messy.
Is it possible to write JSDoc comments such that I can see them as part of the intellisense when defining return values in typescript?
Answer: Sadly, you don't really have any control here.
Typescript types can get deep, and completely unfolding all of them always to their atomic pieces isn't really practical for more complex types. But, as you note, for simple types it can be a bit too quick to wrap them up in a named alias. A tooltip that has many pages of interface details to scroll through is almost as useless as very little information.
So typescript errs on the side of conciseness, opting to show you the types you have named rather than large granular interfaces.
If you want to know what in a type like this, you can just make one, type a . and then explore its interface:

And the JS doc comments do make their way through when you actually use them:

Though I agree it can be hard to understand what's in a type sometimes, I don't believe there are any ways to manipulate how TypeScript/VSCode unravel and report on your type aliases.
Comment: I think your comment that "And the JS doc comments do make their way through when you actually use them" was the light bulb for me.  I can still have a quick reminder of what units my variables are in once I call them, which is mostly what I needed. Thank you!


How do I change the hyperlink display text to reflect the result from another column in SQL?

Question: Can anyone tell me how I can get my URL text to show up as the the "IMAGE NAME" in my query? I am using Toad Data Point SQL Builder and this is what I have so far
<code>SELECT
    ast.location,
    ast.assetnum,
    ast.description,
    own.alnvalue AS "OWNED BY",
    di.description AS "IMAGE NAME",
    concat ('http://link_here', substr(di.URLNAME, 25)) as Link
</code>
I then get the Image name and Link in two different columns, but would like to have the Link text show as the "Image Name". Also once I export the query results to an excel instance can I have the Link display as a Hyperlink without having to do one by one?
Comment: The code seems to be incomplete. I see the query but don't see how you're reading the results into variables in the program (or script or whatever you're building).  Please indicate what technologies are involved, and reveal enough information that someone who has no knowledge of your specifics can understand (and help you solve) the problem.
Answer: You're only 50% lucky, which is quite a lot in this case.
Don't bother about displaying "Image name" as the result - it just won't happen. Result of a SQL statement is pure text, unless you use some tool which lets you format data (such as Oracle Apex).
However, your 50% luck comes with exporting data to Excel, with working URLs. Here's how:

run a query which uses Excel's hyperlink function
see the result; right-click it, choose "Export dataset"
export to "Excel instance"; make sure to set options just like I did.
pay attention to "Treat string fields as strings" that option should NOT be checked
the result is as you wanted it - clickable URLs


Find the equation of the secant line through the points where x has the given values

Question: $f(x)=x^2+3x; x=3, x=4$
$A. y=10x-12$
$B. y=10x+12$
$C. y=12x-10$
$D. y=10x$
I can't find this anywhere in my notes so I am not sure where to start this one. Would I try to find the derivative of the original equation or maybe utilize the rate of change formula?
Update: After applying the rate of change formula I have concluded that$ y=10x-12.$ I was wondering if anyone could tell me if this is the correct answer?
Answer: You don't need calculus for this. Notice how the question is asking for the equation of the secant line through two points, not the tangent line at a point.
We begin by finding the slope of the secant line. Using the function definition, we determine that $(3, 18)$ and $(4, 28)$ are two points that define the secant. The slope is simply $m = \frac{28 - 18}{4 - 3} = 10.$
Now we use one of our points (I'll use $(3, 18)$ here) to see that the y-intercept of the line is $(0, -12).$ So the answer is $\text{(A)} y = 10x - 12.$
Comment: Thank you for clearing that up for me!


Inverter um número de 3 dígitos em C

Question: Necessito fazer um programa que o usuário digite um número de três dígitos e o programa inverte esse numero por exemplo 123 -> 321, gostaria de saber a lógica para fazer isso, pois não consigo pensar em algo.
Answer: Se quiser entender como funciona o algoritmo de uma função que faça a reversão:
#include <stdio.h>
#include <string.h>

void reverse(char str[]) {
    int len = strlen(str) ;
    char tmp;
    for (int i = len / 2; i >= 0; i--) {
        tmp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = tmp;
    }
}

int main(void) {
    char str[] = "123";
    reverse(str);
    printf("%s", str);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Fazendo por matemática:
#include <stdio.h>
#include <math.h>

int reverse(int num) {
    int inv = 0;
    int dig = 0;
    for (int i = 2; i >= 0; i--) {
        dig = num / (int)pow(10.0, (double)i); //infelizmente C não tem uma função de potência para inteiro
        num -= dig * (int)pow(10.0, (double)i);
        inv += dig * (int)pow(10.0, (double)(2 - i));
    }
    return inv;
}

int main(void) {
    printf("%d", reverse(123));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Se voce precisar de um funcao que faca a inversao de numeros de tamanho arbitrario:
int inverte(int x) {
    int inv = 0;
    while (x > 0) {
        inv = 10 * inv + x % 10;
        x /= 10;
    }
    return inv;
}

O que ela faz e ir pegando o resto da divisao do numero por 10, ou seja, o digito mais a direita do numero e somar com o numero que temos ate o momento vezes 10.
Por exemplo, se formos inverter 23:
inv = 0
resto de 23 por 10 == 3
inv = 10 * inv + 3 == 3
dividimos 23 por 10 == 2
repetimos:
inv = 10 * inv + 2 % 10 == 10 * 3 + 2 == 32

Comment: Eu estava fazendo por cálculo, devia ter pensando em usar o módulo  para evitar a função de potência.
Comment: Tragam um oscar pra esse mito! Estava matutando sobre como fazer isso com tamanhos dinâmicos. Seu exemplo foi bem mais simples do que estava pensando em fazer, muito obrigado Lucas, ajudou bastante!
Answer: Para as condições exatas do problema, basta isso:
str[0] ^= str[2];
str[2] ^= str[0];
str[0] ^= str[2];

Veja funcionando no IDEONE
Versão inline :)
str[0] ^= str[2] ^= str[0] ^= str[2];

Veja funcionando no IDEONE
Aplicando a strings de tamanho maior:
int i, len = strlen( str );
for ( i = len / 2; i >= 0; i--)
    str[i] ^= str[len - i - 1] ^= str[i] ^= str[len - i - 1];

Veja funcionando no IDEONE
Postei como "curiosidade algoritmica", já que as duas soluções postadas resolvem bem o problema, da maneira tradicional.
Para saber como funciona esta solução, veja esta questão. (dica do  @bfavaretto)
Comment: Essa é legal p/ quem é mais *hardcore*. Provavelmente teria alguns benefícios usando assim.
Answer: Para esse problema com 3 dígitos isso já basta.
   #include <iostream>
   using namespace std;

   int main()
   {
    int n = 123;
    cout << "Valor inicial:" << n << endl;
    cout << "Valor Inverso:";
    cout << n % 100 % 10 / 1;
    cout << n % 100 / 10;
    cout << n / 100;
   }

Comment: Por que nessa linha `cout << n % 100 % 10 / 1;` você divide por 1 ? Veja https://ideone.com/SqpLvD
Comment: Nessa mesma linha, `n % 100 % 10` é equivalente a `n % 10`, não se faz necessário primeiro pegar o resto da divisão por 100 para, então pegar o resto da divisão por 10. Aproveitando, esta presente questão é sobre [tag:c] e sua resposta está em [tag:C++], creio que deixar explícito no texto da resposta que você está dando o exemplo em outra linguagem pode ajudar quem chegar aqui no futuro a não se confundir
Answer: Esse função funciona para números positivos e negativos
int foo(int num) {
    int x = 0;
    boolean flag = false;

    if(num < 0) {
        flag = true;
        num = num * -1;
    }

    while (num > 9) {
        x = x + num % 10;
        x = x * 10;
        num = num / 10;

        if (num < 10) {
            x = x + num;
        }

    }
return flag ? x*-1 : x;
}

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Inverter um número de 3 dígitos em C


What does this notation mean? It is two numbers in brackets

Question: I originally though they were (rather bad) fingering suggestions, but then I saw the second bar where the fingering suggestion is 2 4, yet this (51) still shows. What exactly does it mean then when the numbers are in brackets like this? My music theory book does not explain fingering notation at all for some reason, and Wikipedia is not helping here either.
Comment: You can't use a sustain peddle here ( don't think), else you mung the right hand.  That said I could be totally wrong.
Comment: I would just stop at "(rather bad) fingering suggestions". Somebody ought to tell whoever thought those fingerings were sensible why pianos have sustain pedals!
Comment: @alephzero I am glad I am not the only one who thought that. I have already ignored their previous suggestions and I think I shall continue.
Comment: @coteyr I think sustain is necessary here, though I reapply the pedal at the third bass note.
Comment: This really does not look like fingering to me.  It might make some sense for the first bar but not for the second.  Are there more examples of this notation in the piece?  The next bar doesn't have (50) under the first note by any chance does it?
Comment: @JimM Page 3 @ http://hz.imslp.info/files/imglnks/usimg/b/b2/IMSLP72131-PMLP02774-Schumann--Davidsbundler-Op6--2nd-ver--Ed-B_H.pdf
Comment: @bwv869 Thanks for the link.  This notation is used in a number of places throughout the pieces.  There are some places where it seems to make sense to me.  I think what is confusing me is that it is inconsistent.  If there are three notes to play I would expect to see fingering for all three;  in some cases they are showing fingering for just the lowest note or the lower two notes (at least I think that's what they are doing).
Answer: In piano this parenthesis with 2 fingering means that you should change finger while keeping the note played.
For example at the second bar you show, you should first use your 5th finger to attack the note, and switch to your 1st finger while keeping the note played, so you can reach the next note (that is quite far) with your 5th finger.
Comment: I always thought that was notated like https://musescore.org/sites/musescore.org/files/fingersubstitution.jpg


How to generate ipa file without xcode from windows? if possible

Question: I am trying to create ipa without mac and xcode. I have iphone to test app. I never used expo for development purpose. Is this possible with expo or any online resource which can generate this ipa for testing purpose only? Its a React native app
Comment: in which language your code is written ??
in `angular` or `swift` or `objc`  or `c#`??
Comment: "javascript" I think i forget to mention app is developed using React Native
Answer: Yes it'll be possible with Expo.
You need to create a new project with create-react-native-app or exp init, then move your existing code over and execute exp build:ios, which will build the ipa on Expo's servers for you to download.
You will not be able to include any third party native libraries (i.e. libraries that aren't 100% Javascript, that you had to link with react-native link).
However, Expo provides an extensive list of native API for you to use.
Comment: I did, all the blue text are clickable links.
Comment: it will be great if you provide a direct link to expo documentation.


Quais são as ferramentas disponíveis para cobertura de código em .NET em Visual Studio?

Question: Tenho desenvolvido sistemas utilizando TDD em .NET. Recentemente, a empresa que trabalho, comprou a versão do Visual Studio 2013 Pro e, nesta versão não temos a ferramenta de cobertura de código (code coverage), somente a partir da versão Premium (visual studio compare versions) a cobertura de código está disponível.
Dessa forma, quais as opções que tenho?
Quais as ferramentas opensource (free) para cobertura de código, são equivalentes a ferramenta do visual studio versão Premium em diante?
O que gosto muito é a experiência de estar tudo integrado ao visual studio, porém, se existir alguma ferramenta, mesmo que não esteja totalmente integrada, mas que ofereça uma boa experiência e desempenho, não me importo com a integração.
Comment: [Nesta questão tem um resumão sobre várias ferramentas](http://stackoverflow.com/questions/276829/code-coverage-for-c-net) (em inglês)
Answer: Esse link do Stack Overflow (https://stackoverflow.com/questions/276829/code-coverage-for-c-net) levou a conclusão que não existem muitos aplicativos free.
O único free seria o OpenCover https://github.com/sawilde/opencover


Expansion for $f(x)\in k[x]$

Question:
Let $k$ be a field and let $b(x)\in k[x]$ have $\deg(b)\ge1$. Then each nonzero $f(x)\in k[x]$ has an expansion $f(x)=d_m(x)b(x)^m+\cdots d_j(x)b(x)^j+\cdots+d_0(x)$ for every $d_j(x)=0$ or $\deg(d_j)\lt \deg(b)$.

My textbook proves it by induction, but I have a question about $m$. How to find such $m$ properly.
By division algorithm, $f(x)=g(x)b(x)+d_0(x)$, where $d_0(x)=0$ or $\deg(d_0)\lt \deg(b)$. Since $k[x]$ is an integral domain, $\deg(f)=\deg(g)+\deg(b)$, which means $\deg(g)\lt\deg(f)$. By induction hypothesis, $g(x)=d_m(x)b(x)^{m-1}+\dots+d_1(x)$. Hence, $f(x)=g(x)b(x)+d_0(x)=d_m(x)b(x)^m+\cdots+d_0(x)$.
But why we can say that $g(x)=d_m(x)b(x)^{m-1}+\dots+d_1(x)$ ? I think this $m$ depends on $g$ so it may be some $n$ but it won't get the desire result.
Answer: Of course, $m$ depends on $f$ (and $b$), and so do the $d_k(x)$.
Since $\deg(d_kb^{k})$ can range from $k\deg b$ to $(k+1)\deg b-1$ (with the one exception when $d_k(x)= 0$) and the highest summand must have degree $\deg f$, we will need $$m=\left\lfloor\frac{\deg f}{\deg b}\right\rfloor.$$
Comment: appreciate for your answer. Do you have any suggestions about my writing in inductive step?

Expansion for $f(x)\in k[x]$


Postfix can not send to some mailservers: 'not logged in'

Question: I have setup a Postfix stack (with Dovecot and Spamassassin, ClamAV + Amavis) which is working pretty good, actually.
It relays my emails (I am using Thunderbrid as client) to other mailservers. I tried different ones like gmx or gmail.
I have an old mailserver (default iredmail, no customizations) which will be migrated as soon as the new server is working.
Whatsoever, the only mailserver which makes problem is this one. When I send an email to this iredmail machine, my new postfix server gives me a "Undelivered Mail Returned to Sender" notice with the following content:
<email@example.com>: host mail.otherhost.com[OTHER_HOST_IP] said: 553 5.7.1
    <email@example.com>: Sender address rejected: not logged in (in reply to RCPT TO
    command)

In addition to this, I have the maillog of the new postfix server (masked as host.com):
Feb  1 15:34:19 mail postfix/submission/smtpd[7090]: connect from p11e11b3f.dip0.t-ipconnect.de[MY_HOME_IP]
Feb  1 15:34:19 mail postfix/submission/smtpd[7090]: Anonymous TLS connection established from p11e11b3f.dip0.t-ipconnect.de[MY_HOME_IP]: TLSv1 with cipher ECDHE-RSA-AES256-SHA (256/256 bits)
Feb  1 15:34:19 mail postfix/submission/smtpd[7090]: 7E92928C0DAE: client=p11e11B3F.dip0.t-ipconnect.de[MY_HOME_IP], sasl_method=PLAIN, email@example.com
Feb  1 15:34:19 mail postfix/cleanup[7096]: 7E92928C0DAE: message-id=<email@example.com>
Feb  1 15:34:19 mail postfix/qmgr[4363]: 7E92928C0DAE: from=<firstname.lastname@example.com>, size=673, nrcpt=1 (queue active)
Feb  1 15:34:19 mail postfix/submission/smtpd[7090]: disconnect from p11e11B3F.dip0.t-ipconnect.de[MY_HOME_IP]
Feb  1 15:34:20 mail postfix/smtpd[7101]: connect from localhost.localdomain[127.0.0.1]
Feb  1 15:34:20 mail postfix/smtpd[7101]: 9C3BC28C0DCA: client=localhost.localdomain[127.0.0.1]
Feb  1 15:34:20 mail postfix/cleanup[7096]: 9C3BC28C0DCA: message-id=<email@example.com>
Feb  1 15:34:20 mail postfix/smtpd[7101]: disconnect from localhost.localdomain[127.0.0.1]
Feb  1 15:34:20 mail postfix/qmgr[4363]: 9C3BC28C0DCA: from=<email@example.com>, size=1108, nrcpt=1 (queue active)
Feb  1 15:34:20 mail amavis[5722]: (05722-04) Passed CLEAN {RelayedOpenRelay}, [MY_HOME_IP]:59846 [MY_HOME_IP] <firstname.lastname@example.com> -> <email@example.com>, Queue-ID: 7E92928C0DAE, Message-ID: <firstname.lastname@example.com>, mail_id: gSTyaLhv6ZgI, Hits: -1, size: 673, queued_as: 9C3BC28C0DCA, 1061 ms
Feb  1 15:34:20 mail postfix/lmtp[7098]: 7E92928C0DAE: to=<email@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=1.2, delays=0.16/0/0/1.1, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as 9C3BC28C0DCA)
Feb  1 15:34:20 mail postfix/qmgr[4363]: 7E92928C0DAE: removed
Feb  1 15:34:20 mail postfix/smtp[7102]: Untrusted TLS connection established to mail.otherhost.com[OTHER_HOST_IP]:25: TLSv1 with cipher ADH-AES256-SHA (256/256 bits)
Feb  1 15:34:20 mail postfix/smtp[7102]: 9C3BC28C0DCA: to=<firstname.lastname@example.com>, relay=mail.otherhost.com[OTHER_HOST_IP]:25, delay=0.15, delays=0.05/0/0.05/0.05, dsn=5.7.1, status=bounced (host mail.otherhost.com[OTHER_HOST_IP] said: 553 5.7.1 <email@example.com>: Sender address rejected: not logged in (in reply to RCPT TO command))
Feb  1 15:34:20 mail postfix/cleanup[7096]: C20F928C0DCB: message-id=<firstname.lastname@example.com>
Feb  1 15:34:20 mail postfix/bounce[7103]: 9C3BC28C0DCA: sender non-delivery notification: C20F928C0DCB
Feb  1 15:34:20 mail postfix/qmgr[4363]: C20F928C0DCB: from=<>, size=3112, nrcpt=1 (queue active)
Feb  1 15:34:20 mail postfix/qmgr[4363]: 9C3BC28C0DCA: removed
Feb  1 15:34:20 mail postfix/virtual[7104]: C20F928C0DCB: to=<firstname.lastname@example.com>, relay=virtual, delay=0.08, delays=0.04/0/0/0.03, dsn=2.0.0, status=sent (delivered to maildir)
Feb  1 15:34:20 mail postfix/qmgr[4363]: C20F928C0DCB: removed

In addition to this elaborate log, I have the related snippet from the iredmail machine"
Feb  1 17:44:48 mail postfix/smtpd[15073]: connect from unknown[HOST_IP]
Feb  1 17:44:48 mail postfix/smtpd[15073]: NOQUEUE: reject: RCPT from unknown[HOST_IP]: 553 5.7.1 <email@example.com>: Sender address rejected: not logged in; from=<firstname.lastname@example.com> to=<email@example.com> proto=ESMTP helo=<mail.host.com>
Feb  1 17:44:48 mail postfix/smtpd[15073]: disconnect from unknown[HOST_IP]

The question I am asking myself now: Is there a misconfiguration in the default iredmail server I am not aware of or is there a misconfiguration in my new postfix server which should be fixed.
And in general, what exactly means this error, I am a bit new to this entire mailserver segment of system administration, but very eager to learn new stuff.
Thanks in advance.
(The new postfix machine is masked as HOST_IP, mail.host.com and email@example.com, the old iredmail machine is masked as: OTHER_HOST_IP, mail.otherhost.com and email@example.com)
Comment: Your question is not clear, probably because you obfuscated all the hostnames. Exactly which of these hosts are _yours_ and which are third parties?
Comment: I am sorry, updated the question. Is IP/Domain masking in logs considered a bad practice? If so, I will update the posting again to contain the real data.
Comment: Sometimes it helps to have the real information, though sometimes it is not advisable due to privacy concerns. See [What information should I include or obfuscate in my posts?](http://meta.serverfault.com/q/963/126632) for a full discussion.
Comment: Looks like sender's domain is configured on iredmail also, as local?
Answer: By default iredmail won't allow unauthenticated connections coming from domains it controls. Either remove sender's domain from iredmail (if it should not be there) or add sending server's IP to mynetworks in iRedMail configuration (if you trust it).
Answer: Your iredmail machine which you named mail.otherhost.com is misconfigured. It appears to be wanting users connecting on port 25 to authenticate before sending mail, which is not appropriate for incoming connections on this port. Port 25 is intended for receiving mail from other domains on the Internet. Authentication should be required only for incoming connections on port 587, the submission port, which users of your domain use to send outgoing mail.
I'm not familiar enough with iredmail to tell you the exact setting to change, though this shouldn't be too hard to find.
However, if you're decommissioning the box anyway, and its replacement is working, you could just ignore it and swap in the new server.
Answer: Message Sender address rejected: not logged in means, that used sender address ("From:" address) has a owner - probably is hosted on given server, so emails from this address cannot cames from outside.
On given server probably exist mailbox or alias with given from address - try remove it.


Export variable in PHP exec

Question: I'm trying to do the following: inside script.php:
\exec('export FOO=BAR');

Now if I run script.php in CLI, then run echo $FOO, $FOO doesn't appear to be set.
Any ideas how can I properly "export" a CLI variable from PHP's  \exec()?
Comment: Is https://www.php.net/manual/en/function.putenv.php or https://www.php.net/manual/en/function.getenv.php what you're looking for?
Comment: The execution within PHP is active only for the scope of the script execution, not outside. It is not fully clear if you want to import or expot an ENV var, because your scenario is about exporting.
Comment: @WOUNDEDStevenJones I think he rather looking for `putenv()`.
Comment: @WOUNDEDStevenJones I'm tried, doesn't seem to work also
Comment: @DanielW. Yeah I want to set `FOO` as environment var in CLI
Comment: @IMB what is your real use case? In modern software design, you usually don't change the environment from within the application. If you want a generator for specific vars, you should let PHP write a `.env` file and reimport that in the final destination.
Comment: @DanielW. It's for dev environment only. I'm tired of doing `export FOO=BAR` (where `BAR` is a random long string) every time I start a docker container.
Comment: @DanielW. Basically, I'm just creating a shortcut script because I type `export FOO=BAR` in CLI way too often everyday while in dev environment.
Answer: You shouldn't do that. Don't change environment from within application. Start your container with the string instead:
In ./start-docker-development-container.sh:
#!/bin/bash
export RANDOM_STRING=`pwgen -Bs1 12`
docker-compose up -d --remove-orphans

In docker-compose.yml:
version: '3.1'
services:
    your_service:
        environment:
            RANDOM_STRING: ${RANDOM_STRING}

Comment: I can see this working but is there really no way for my initial approach to work, basically no way to "export" a var from PHP to a CLI env?
Comment: @IMB you could start your (development) PHP script using `<?php $_ENV['RANDOM_STRING'] = rand();`, but it does not make sense to first export from PHP and then reimport to PHP. If you need to, set it in docker-compose or your start dev script.
Comment: I'm not really setting an `$_ENV` in PHP, I literally just need to run `export FOO=longSecretString` inside a PHP shortcut script.
Comment: @IMB ENV vars set in PHP are only set until the end of the script. You can export it by letting PHP write a file and then use `source ` in bash. There is no way for PHP to manipulate ENV vars outside of the runtime scope. It's even easier to make this in bash like in the script shown above.
Comment: If that's the case then I think all I need is a bash script with `#!/bin/bash` `export FOO=BAR` `docker start mycontainer`. I don't think I really need to modify the `docker-compose.yml` file right?
Comment: @IMB `docker start` does not allow environment variables. `docker run` allows `-e ` but best option is to use `docker-compose.yml` and just add the variables.
Comment: @IMB The very best solution would be to have an environment specific .env file with the variables already in, but talking about your env loading in the application is a little too long of a talk for comments.

Export variable in PHP exec


coluna com acentuação invalida

Question: Estou montando um relatório utilizando o banco de dados de um sistema e PHP com o DBLIB, porém, quem estruturou o banco criou as tabelas e campos com acentuação. Quando eu vou fazer uma consulta em algum campo que não tenha acentuação a query funciona, mas quando acento tem dá erro de coluna invalida.
Exemplo:
 select CAST(cp.[vencimento] AS date) as vencimento from contaspagar as cp;  //essa funciona de boa
 select CAST(cp.[dataemissão] AS date) as dataemissao from contaspagar as cp; //essa da erro de coluna invalida

Estou usando Linux, PHP 5.6, e a biblioteca freetds para conectar no SQL, SQL 2008 express.
Erro no PHP:

SQLSTATE[HY000]: General error: 207 General SQL Server error: Check messages from the SQL Server [207] (severity 16) [(null)]NULL

Significado do erro:

Invalid column name '%.*ls'.
Comment: Posta a mensagem de erro exata por favor.
Comment: Ygor tem como informar exatamente que ocorre? Se informar talvez consigamos lhe orientar para que funcione.
Comment: @guilherme-nascimento estou montando uma tela em PHP para gerar um relatório, ja consigo fazer a conexão com o banco de dados e executar algumas query, porem algumas tabelas do banco possui acentuação e quando executo a query pelo PHP fala que a coluna esta com nome invalido, mas se executo a query direto no management ela executa normalmente
Comment: Tá mas posta o erro exatamente, se a mensagem de erro exata não temos como deduzir nada.
Comment: coloquei na pergunta
Answer: Quando os nome dos identificadores (tabelas colunas ect) têm caracteres acentuados ou outros tipos use os escapes, no caso do SQL SERVER são colchetes ([])
Mude:
SELECT descrição FROM ...

Para:
SELECT [descrição] FROM ...

Comment: tentei assim:select CAST([cp.dataemissão] AS date) as dataemissao  e assim: select CAST(cp.[dataemissão] AS date) as dataemissao deu nome da coluna invalida
Comment: @YgorAnjos Deve se assim: `select CAST(cp.[dataemissão] AS date) as dataemissao` os colchotes são individuais ou seja vai para cada coluna
Comment: tentei, mesmo erro :( .... direto no ServeManagement funciona, quando coloco no PHP da erro
Comment: @YgorAnjos qual erro? no SQL Management também dá esse erro?
Comment: SQLSTATE[HY000]: General error: 207 General SQL Server error: Check messages from the SQL Server [207] (severity 16) [(null)]NULL  Invalid column name '%.*ls'.
Comment: quando eu coloco outro campo sem acentuação nos colchetes ele executa
Comment: @YgorAnjos pode ser problema no resto da consulta, adiciona ela na pergunta.
Comment: o resto é ...from tabela as cp
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/52541/discussion-between-ygor-anjos-and-rray).
Comment: @YgorAnjos quando vc imprime o seu select pelo php (se não testou isso, faça) ele imprime certo? ou ele mostra caracteres estranhos nos acentos?
Comment: foi uma das primeiras coisas que testei, eu estou usando PDO, será que muda algo?
Comment: @YgorAnjos coloca o select completo aqui.
Comment: coloquei na pergunta
Comment: @YgorAnjos tente só `select CAST([dataemissão] AS date) as dataemissao from contaspagar as cp` ou ainda `select CAST(contaspagar.[dataemissão] AS date) as dataemissao from contaspagar`
Comment: esta acontecendo o mesmo erro
Answer: Solução:
$query=iconv( 'UTF-8', 'Windows-1252', $query );

A conexão com o SGBD não é UTF-8. FreeTDS é Ansi/Windows 1252.

coluna com acentuação invalida


fastify-http-proxy: Failure with "Promise may not be fulfilled with 'undefined'

Question: I am using the fastify with fastify-http-proxy with the following configuration:
<code>const proxy = require('fastify-http-proxy');
fastify.register(proxy, {
    upstream: "https://myendpoint/occm/api/azure",
    prefix: '/azure',
    onResponse: (request, reply, res) => {
        console.log('Inside onResponse')
        reply.send('New body of different length');
    },
    onError: (reply, error) => {
        console.log('Inside onError')
        reply.send(`My Error: ${error}`);
    },
    replyOptions: {
        rewriteRequestHeaders: (originalRequest, headers) => {
            console.log('Inside rewriteRequestHeaders')
            return {
                ...headers,
            };
        },
    },
});
</code>
I have configured a fastify route as this:
<code> fastify.route({
        method: 'GET',
        url: `/azure/vsa/working-environments`,
        schema: {
            description: 'Trying out',
            tags: ['notifications'],
            security: [{
                authorization: []
            }],
            params:{
                title: "Working Env GET",
                description:'Trying out...',
                type: 'object',
                example: 'No input',
                properties: {
                    'accountId': {
                        description: "Account ID",
                        type: 'string'
                    },
                },
            }
        },
        handler: async (request, reply) => {
        }
</code>
I am calling it as:

GET http://localhost:xxxx/azure/vsa/working-environments

Basically I would like to proxy the request to this endpoint:

https://myendpoint/occm/api/azure/vsa/working-environments

Now whenever I am running it, getting this error:
<code>{"level":30,"time":1644249539394,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","req":{"method":"GET","url":"/azure/vsa/working-environments","hostname":"localhost:8092","remoteAddress":"127.0.0.1","remotePort":63308},"msg":"incoming request"}
{"level":50,"time":1644249540657,"pid":12100,"hostname":"pradipm02-PC","requestId":"Q3T9RjI11N","err":{"type":"FastifyError","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n    at C:\\Users\\pradipm\\clients\\CloudManager\\cm_2\\occm\\service-infra\\notifications\\node_modules\\fastify\\lib\\wrapThenable.js:30:30\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)","name":"FastifyError","code":"FST_ERR_PROMISE_NOT_FULFILLED","statusCode":500},"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204"}

</code>
Any of the console.log in the rewriteRequestHeaders, onReponse, onError are not showing up.
Any help is appreciated.
Answer: This is discussed in the following thread in fastify-http-proxy forum.
It is suggested to use fastify-reply-from instead.
That solves my issue.


How can I redirect user/*/edit to another page based on user content?

Question: I have a site with the following relationship: for every user, there is one corresponding (node) profile. For the user/*/edit, I would like the user to actually edit their profile node, not the user account. I've thought about preprocessing the page template to make something available in order to then re-write the secondary menu in the template - but which variable can I use? It's not available in the $user array.
Comment: I was asking to make sure it wasn't already done for you.  If you can pretty much guarantee that there is only one such profile node per user, I can map out the broad strokes here for you
Comment: you are playing with fire here in a lot of ways, but what version of drupal are you using?
Comment: you have query the database to get the back reference, otherwise you can also keep the user node id on user entity also which will be udpated when a node is referred to a uid, that way you can have it on $user also.
Comment: @Jimajamma, I'm using D7.
Comment: @arpitr - How would I keep the the user nid on the user entity? I'm not sure I follow.
Comment: and are you using any module for the nodes as a profile or doing this all yourself?
Comment: answer for jimajamma question is important. Assuming the user node is from a content type that you have created and not coming from any module, the time node get saved, there must be  user reference field, so you can hook the node_update process and check the user reference field value then save the current nid to the user entity corresponding to that uid.
Comment: I'm not using another module, the profile nodes are not entities. @arpitr - are you suggesting that I add another field to the node for user reference? I've had a lot of trouble with both the node reference and entity reference projects, especially with my content types already developed, the references break for some reason. I've used this kind of relationship in the past, I'm not sure why this time it's different. I'm looking into using relation project now.
Comment: @Jimajamma I guess we can assume one node per user - "here is one corresponding (node) profile"
Comment: There is exactly one corresponding profile node per user.
Comment: you do not have to create reference field if you have relation in place, I wonder if relations are both ways or not, I have never used relation before just as an idea I can suggest you can do a custom query to get the user-node relation mapping and create a helper function which takes the user as argument and returns the node related and simply the time you need to get the node call this function with global $user(uid).
Comment: Please be more specific about your needs. Anyhow, I think you can consider using page manager module. You can use so many different things like redirecting, making custom pages, using page manager contexts to load metadata related to the pages, defining access rules and so on.
Answer: So in broad strokes, basically what you want to do is grab the user's uid and then open for editing the corresponding profile type node owned by that user.
So, if you have that user's uid in $uid, it would be something along these lines:
$nid = db_select('node', 'n')
        ->condition('n.type', 'YOUR_PROFILE_NODE_TYPE')
        ->condition('n.uid', $uid)
        ->fields('n', array('nid'))
        ->execute()->fetchField();

which, if I've not typo'ed anything will set $nid to the node id of the node of type YOUR_PROFILE_NODE_TYPE that is owned by $uid.
If there is only one, that's the node we are looking for.
So, now you just need to create a link to node/$nid/edit and you're all set.  (Somewhat obviously, you want to present this link only to admins and the user who owns the profile.)
So, where do you put all of this?
Of course, you could preprocess this into a variable that's used in a page template, but you could also create a new menu item as well, eg user/#/edit-profile that grabs the user id out of the second argument and then does all of the above to grab the actual nid and then presents the node edit form, but now we are getting past the broad strokes :)  (But hook_menu() is the place to look, with user.module a great starting point for example code for user/#/edit to modify)
Comment: This looks great, but I'm not getting anything usable if I put it in _themename_ _preprocess. Here's what I'm doing   `$uid = $variables['user']->uid;
 $nid = db_select('node', 'n')
 ->condition('n.type', 'fellow_profile')
 ->condition('n.uid', $uid)
 ->fields('n', array('nid'))
 ->execute()->fetchField();
$variables['profile_nid'][] = $nid;`
Comment: I doubt there is a `user` variable being sent in via `preprocess()`, but it is available in the second argument.  Once again, broad strokes here, it would be `1` if you were looking at `user/1/edit-profile` or just plain old `user/1` and can be found via `arg(1)` (no relation to user 1 and 1 here, arg(#) just returns the #th argument in the path).
Comment: You're right, there isn't, but I can user_load() and have it - but, that won't give me the reference to the profile node. My solution is to use an entity reference field on each (user and profile), which gives me just what I need. Thanks for all your brainstorming!
Answer: Consider making a new solution based on Profile2, otherwise spice you current solution up with the Rules module. :)
Answer: In this case, I added an entity reference field to both the the user and profile node. In the page template, I can user_load() the uid of the logged-in user and have the entity reference available for theming.


Multilingual menus: logic and architecture

Question: A question dedicated for developers: What is the right Multi-lingual option for entities and menus in Drupal 8? In contrast to Drupal 7 that never asked me for a menu language, some entities and menus in Drupal 8 asks me for a default... But... I don't want a singular language for that menu... I want it to include 2 and even 3 languages... Thus what is the logical option? My question is basically comprised of two questions:

Is it Not specified? Or Not applicable?, and what is the difference between the two?
I also wonder why the ready-to-work menus that comes with the Drupal 8 installation, are not multilingual and are locked to the language in which the site was installed... Won't it be more flexible to set it to some kind of a multilingual option and that's it?...
Answer: It seems to be impossibe to have one multilingual custom menu in Drupal 8.0.
What you have to do is to create one menu per language. You specify the one language of the menu as you show in your image.
Then in blocks you place all your menus in the same place. Here you can choose which menu is chosen for which language.
This is far from elegant, since you have to edit each language separately without a translate button. But apart from being a cluttered process to create, it works nicely.


How does the World Ranking work?

Question: Why are athletes ranked the way they are in the BWF world ranking?
For instance, Marc Zwiebler, listed as World #10 as of May 2016, has not won any tournament this year, and has never won a top-level (Superseries) event. How come he's ranked so highly?
Answer: Whenever an athlete competes in a BWF tournament, they get some amount of points. The world ranking is then calculated by the sum of the 10 highest tournament points in the last year. In the ranking details page of a player, these 10 are marked with yellow stars.
The number of points awarded to a player for participating in a tournament depends on two factors: The result and the level of the tournament.
For example, a player who loses in the round of 128 in a Future series (the lowest level) tournament will be awarded 60 points. On the other hand, the winner of the Olympics gets a massive 12000 points. Semifinalists (place 3 and 4) will get about 75%, and quarterfinalists (places 5-8) about 50% of the winner's points.
This ranking rewards consistency; it is perfectly possible that an athlete who regularly reaches the later rounds of tournaments is ranked above one who only manages to win two high-level tournaments per year but does not play any other ones, or an athlete who only competes in the lower-level Future/International Series. For instance, Marc Zwiebler has often reached the quarterfinals at Superseries tournaments (5040 points), and the semi-finals or finals at Grand Prix Gold tournaments (~4000-6000 points).
There are a lot more subtleties, in particular the points awarded at national team events and special rules for doubles and mixed. You can find all of this information, and more, in Appendix 6 of the BWF General Competition Regulations, in particular the table of points in §6.3.

How does the World Ranking work?


Como limpar o que já foi escrito no terminal em lua?

Question: Após a execução do comando:
Print("teste")
Info = io.read()

Gostaria que a tela do terminal, com o print resultante fosse limpada
Answer: é quase o mesmo problema que respondo nessa questão, perguntando sobre o terminal de Python Como limpar o console no Python?  -
Motivo: apagar o terminal não é um problema da linguagem - nem de Lua, nem de C++, nem de Python, nem de nenhuma que não seja um "framework" integrado com o terminal - como Cobol, o "Qbasic" predecessor do VisualBasic e as primeiras versões do Delphi na década de 1990 - todas elas "enxergam" a saída apenas como um arquivo de escrita de bytes (ou caracteres, nos casos em que a linguagem traduz automaticamente texto acentuado e emojis para a codificação que o terminal está usando).
Então, se você precisa de qualquer interface um pouco mais sofisticada no terminal, e no caso, bem pouco sofisticada mesmo: só apagar a tela - tem que usar comandos que o programa do terminal vai entender. Esses comandos tem o nome de "Sequências ANSI" - e além de poderem apagar a tela, também podem posicionar a impressão em qualquer posição, mudar a cor do texto, etc... Começam com um caractere "<ESC>" (código "\x1b"), seguido de alguns parâmetros e um especificador do comando. Em vez desses parâmetros aparecerem impressos no terminal, eles executam uma ação.
Esses comandos funcionam na maioria dos terminais, mas justamente não funcionam no cmd do Windows - (mas vão funcionar se você baixar o app de "terminal" da Windows store).
Então, para apagar a tela e posicionar o cursor na linha 1, coluna 1, basta imprimir a sequência:
print("\x1b[2J\x1b[1;1H")

Para só apagar a tela:
print("\x1b[2J")

Uma outra solução, se você está no CMD do Windows e não tem sequências ANSI, é só imprimir uma porção de linhas em branco, pelo menos uma a mais que o tamanho do terminal. Em Lua precisa fazer um for
for i=0,70,1 do
  print("\n")
end

Vai imprimir 70 linhas em branco.
o que não fazer:
Por que evitar chamar "os.execute"?  Como está descrito na outra resposta, a chamada os.execute vai  ciniciar um outro processo no sistema operacional, carregar um shell - e tudo isso para imprimir algumas linhas em branco.
É umas 1000 a 10000 vezes mais lento, e usa o mesmo tanto de memória a mais. Não vai fazer diferença por que se você está apagando a tela, está numa sessão interativa com o usuário - e os computadores hoje são tão rápidos que mesmo assim vai ser imperceptível. Mas eu costumo dizer que usar os.execute("clear") para apagar a tela é equivalente a telefonar pra um chaveiro pra ele vir, e abrir sua porta de casa com as ferramentas dele, a cada vez que você vai entrar ou sair de casa (sendo que você está com a chave na mão e é só usa-la).
Mas, apesar de tudo, é só deselegante e a experiência do usuário vai ser a mesma - eu que pessoalmente me incomodo com isso (e vai funcionar diferente no linux e no Windows - mas até aí, a sequência ANSI também vai)
Outros comandos para o terminal:
Aqui tem uma página legal com o resumo de vários comandos para o terminal:
http://ascii-table.com/ansi-escape-sequences.php
É só lembrar de trocar "ESC" por "\x1b" - que imprime o caractere "ESC" pelo seu código (27 em decimal).
Outra dica é depois que descobrir sequências que funcionam, não deixar as sequências "cruas" no meio do seu código - quem é que vai ver um  print("\x1b[2J") lá no meio e vai saber que você está apagando a tela? Crie ou variáveis com as strings contendo os cmandos, ou funções que imprimam esses comandos do tipo:
function cls()
    print("\x1b[2J\x1b[1;1H")
end

Aí  - no ponto em que precisa apagar a tela, você só chama a função cls() - fica muito mais fácil de se preocupar só com a lógica do seu programa e os códigos de apresentação ficam numa parte separada.
Answer: Você pode usar o comando os.execute().
No Windows:
os.execute("cls")

No Unix:
os.execute("clear")

Resposta traduzida do stackoverflow em inglês, fonte:
https://stackoverflow.com/questions/23187310/how-do-i-clear-the-console-in-a-lua-program


How to show whole content in Textview with scrolling left right not top bottm as show in screenshot?

Question:
I have book content that will be shown in the textview with scrolling left right for next content. Is there any library or logic to show content like that?
Answer: You should add some property into your textview XML tag such as
<code>android:inputType="text"
android:scrollHorizontally="true"
</code>
Use it, try and let me know if it works for you or not.
Happy to help you if you need to know more about it.
Thanks.
Happy coding :)
Comment: Thanks for your reply. But I need to show the long text in Textview with swipeable page format like book and also change the text size by clicking button.


Correct way to fetch data with server side rendering (Next.js, when to use componentDidMount and when to use componentWillMount)

Question: I am using Next.js, in the _app.js page (where we set a general webapp state) I have 2 types of data that I need to have in the header (so for every component).
1) The first type is the header info, this info should be rendered before the app loads. I will use get getInitialProps to call the endpoints and put them into the props and then to componentWillMount to add them to the state.
2) The second type is the data for the Search component, it as a lot of data and I don't particularly mind loading it while the app is already rendered as It is not displayed in the first user visual.
So I am gussing that here it is much better prefered to use componentDidMount and asynchorslly call the endpoint that fetches the serach object data and than adding setting the state with it.
The purpose of this questionis double:
1) Review - Am I thinking about this correctly or did I miss something?
2) Question - now, when the data is loaded after first render, I am passing the data like so: _app.js -> Layout -> Menu -> SearchBar
so my question is, in my searchBar I need to do something like
componentDidMount() {
    this.setState({ options: this.props.searchBarSource })
}

But, because _app.js is filling this data with an async call, wouldn't this mean that I will always get an empty object?
WWhat is the correct way to solve this? If I setTimeOut to around 3 seconds and then set the data is it a normal solution or very hacky and there are better ways?
Comment: you can use life-cycles to detect changes in `this.props.searchBarSource` and store accordingly. But do you really need to synchronize props to state? Can't you use `this.props.searchBarSource` where you normally would use `this.state.options`?
Answer: What your are trying to do makes sense. Coming to NextJS, you need to be very deliberate about which data should load server side and which shouldn't.
Here are some pointers:

There is no need to setState in the search component, you can
use this.props.searchBarSource as Kunukn mentioned.
[Note - If you are combining getInitialProps and client side (shallow routing), when the user navigates to a new client side route, the initialProps will be undefined. A workaround might be to store initialProps in state or Local Storage.]
The point of getInitialProps is to load async data before the
component mounts. You will always receive the resolved Promise on
componentDidMount, so your this.props.searchBarSource will never
be empty (or more correctly, pending).
Comment: Yeah you were right about passing the searchBar as a props, not state, after doing so and putting it in the componentDidMount function it works great.
So what is better? using getInititialProps for props that appear to the user all the time and use componentDidMount when you want to fetch data that the user doesn'r see first? Or just fetch everything in getInitialProps without the componentDidMount part?
Comment: The former. For example, I have a product page which needs to be rendered server side for optimal user experience and SEO. But I only need the main data to be available in order to render the page (price, image, basic shipping). That would go in `getInitialProps`. But secondary widgets, especially if they are below the fold, can have their data fetched on component mount.
Comment: At the end of the day you are making a tradeoff: Do you want the page to do more server side fetches and no loading spinners? Have everything fetched in `getInitialProps`. If you are fine with loading spinners for some things, fetch client side.


Question on Chopin opus 25, number 12, on a note that is kept between two measures

Question: In Chopin Etude opus 25, number 12, at measure 57, the last notes of left and right hand are supposed to be kept until the end of the first notes of measure 58.
In my feeling, this is impossible to respect this transition of measures 57 to 58 exactly as he wrote, with a speed of 80 for a white note.
Do pianists really respect this ?
Did Chopin really want that we don't release these two notes between measures 57 and 58 ? Or is it a mistake ?
Here is a snapshot :
https://www.free-scores.com/partitions_telecharger.php?partition=1506#
Comment: For those with no access to the sheet music, please post a copy.
Comment: What fingering do you use for those notes? Do you switch fingers while still holding those notes down?
Comment: @Tim : you are right. Sorry. I have added it now.
Comment: @Dekkadeci : I use index ("2") for both hands on the last note of the measure 57. I don't switch fingers.
Answer: Tying the note over the barline to increase its length by one 16th note is, effectively, "forcing" you to play legato. Since the context already implies legato playing, we might instead ask, Why not tie every note in the same manner?
I believe the answer is that it's because there is a pedal clear indicated. Chopin wants the pedal to clear the reverberating C7 chord from the measure before, but these two notes form interesting suspensions that resolve into the Db chord in the second measure shown. Since this passage is tonicizing F minor (iv in C minor), you could also analyze the chord on beat 1 as a iiø43/iv.
Without the tie, you would clear the pedal just after playing the first notes in the second measure, erasing the G and B♭.
Answer: I can't speak to how different pianists might execute this or how many try to respect the notation, but a survey of early editions of Chopin in IMSLP shows this notation (or something equivalent to it) appears consistently, including in the first print edition.  A search on autographs indicates we may only have an authorized copy in prep for first ed. publication, not one in Chopin's hand, which I don't have access to.  But the consistency of this notation in early editions seems to indicate that Chopin did want pianists to try to at least approximate this.
And given that a similar tied note figure in the left hand occurs again a few bars later, it's hard to claim that this is some sort of "mistake" or simple misprint of Chopin's original notation.


Is there a difference between Espirando and Mancando?

Question: I've seen both these terms listed in online music glossaries as meaning "dying away", but neither entry ever refers to the other. Are there any real-world differences in how these are interpreted?
Comment: In which pieces of music have you seen these terms? The typical musical term I see for "dying away" is smorzando.
Comment: Both Italian, both meaning 'dying away, 'expiring'. Can't find any more info.
Answer: FWIW, the go-to Dolmetsch page says
espirando

(Italian) fading away, expiring, dying away, spirando, en expirant

mancando

(Italian) failing, diminishing in strength, dying away, lacking

smorzando

(Italian) extinguished, put out, gradually dying away to a whisper,
  calming down, subduing (Italian ) in music, similar terms include al
  niente (Italian), morendo (Italian), dämpfend (German), abschwächend
  (German), bis zum Nichts (German), en amortissant (French), hasta la
  nada (Spanish)

The basic answer is that composers use the word(s) they want to, and there's a ton of overlap in the multitude of semicommonly used descriptors.
Comment: Doesn't *morendo* also mean something similar?
Comment: @ToddWilcox - another Italian word for dying. Maybe that's a common thing to do there?!
Comment: I typically understand "al niente" to mean dying away to literally nothing, not the p/pp/ppp of smorzando.
Comment: All this answer has done really is to quote Dolmetsch. Little has been added. Google Dolmetsch.
Comment: I didn't accept this answer primarily for its Dolmetsch quotes, I accepted it for "The basic answer is that composers use the word(s) they want to, and there's a ton of overlap in the multitude of semicommonly used descriptors"


How to calculate the mean and standard deviation of a time series spread?

Question: I am just starting anew in econometrics, and am presently trying out statistical arbitrage, specifically cointegration. I have stochastic time series data for variables A, B. Engle-Granger testing is used for the project. What I have done:

Performed a stationarity test.
Performed differencing
Performed OLS regression
Found the trading pair formula by calculating the spread. Which is spread = dependent (A) - regressor (B).

Now, where I got confused is how to get the mean and standard deviation of the spread. I'm a bit confused on how to calculate these, and I'll really appreciate it if I can get a help in this regard.
Please see the attached.csv file and simply enter your response when the file is opened in Excel.

or go directly to it - https://fileport.io/gp9SsSBcaSwq
Comment: If you use Engle-Granger and find that A and B are cointegrated, why do you apply differencing?
Comment: Engel Granger dictates that the variables must be stationary at first difference.
Comment: It might be what a unit root test shows, but not what Engle-Granger dictates. Engle-Granger is about cointegration (a relationship between multiple integrated series), not about integration (a property of a single series). To find out about cointegration using the Engle-Granger procedure, you should not be differencing. Instead, you should run a regression of A on B as they are. If there is cointegration, the residual will be stationary. It will be the estimate of S.
Comment: @Richard Hardy, You're right. The differencing is done to check if the raw variables are stationary at first difference. Engel Granger test was done non the raw data. I have attached a CSV file to the main post. Could you add the formula  to calculate mean and standard deviation in Excel, and reshare with me? Thank you.
Answer: The stationary combination $S$ of a pair of cointegrating time series $(A,B)$ can be treated as any stationary time series. If the cointegrating vector is $(1,-1)$, then $S:=A-B$ is stationary.

Its (unconditional) mean can be estimated as the sample mean, just as you would do with i.i.d. data.
The (unconditional) standard deviation can again be estimated as the sample standard deviation; see e.g. this thread.
The standard error of the mean can be estimated using autocorrelation-robust standard errors such as Newey-West.

Here is some R code:
<code>T=1e3
set.seed(1); x=arima.sim(model=list(ar1=0.9,ma1=-0.3),n=T)
mean=mean(x); print(mean)
sd  =sd  (x); print(sd  )
se  =sqrt(sandwich::NeweyWest(lm(x~1))); print(se)
</code>
Comment: @ken4ward, Excel formulas are `=AVERAGE(...)` and `=STDEV.S(...)` where `...` is the range of the cells the time series occupies.
Comment: I'm not using R for now, could you add the formula to calculate mean and standard deviation in Excel, and reshare with me? Thank you.


Exposed filters of a view printed in different places

Question: How can I get a view to expose filters that are drunk rendering separately.
Have three filters exposed but I do not know how to get it to fit the layout correctly.
Is it possible to achieve this type of layout with drupal 7?
I have an image that explains:
Thanks.
Answer: My first instinct would be to create a custom template for that specific View. However, based on the screenshot, it looks like you only want to move 2 of the 3 exposed filters to the side.
Had you wanted to move all of the exposed filters to the side, it likely could have been done with a custom views-view.tpl.php file.
Perhaps give the  Better Exposed Filters a try!
I haven't personally tested this module, but a Google search lead me to this. Hope this helps.
Answer: in "exposed form settings" on third column in views ui, select: display as a block: yes, then configure the block in blocks admin page (or panels if you are usuing it) to display it in your page. BEF module is a good one, try with and without it.


How to write a complex query using `expr` in mongodb?

Question: I'm trying to write a bit complicated query to the MongoDB and I honestly don't know how to write it correctly. In SQL pseudocode it's something like:
SELECT *
FROM Something
WHERE
   (IF Item.NestedItem THEN NULL ELSE Item.NestedItem.Id) == 'f4421f9e-5962-4c68-8049-a45600f36f4b'
OR (IF Item.NestedItem THEN NULL ELSE Item.NestedItem.OtherId) == 'd6b799dc-f464-4919-8435-a7b600cc408a'

I succeeded in writing IF as
{ "$cond" : [{ "$eq" : ["$Item.NestedItem", null] }, null, "$Item.NestedItem.Id"] }
{ "$cond" : [{ "$eq" : ["$Item.NestedItem", null] }, null, "$Item.NestedItem.OtherId"] }

But now I'm not sure how to compare them to constants and then join. I'm trying to write a translator from SQL-like language to MongoDb and this is example of query I cannot translate. I want something like
{ "$and" :
    { "$eq" : { "$cond" : [{ "$eq" : ["$Item.NestedItem", null] }, null, "$Item.NestedItem.Id"] }, "f4421f9e-5962-4c68-8049-a45600f36f4b" },
    { "$eq" : { "$cond" : [{ "$eq" : ["$Item.NestedItem", null] }, null, "$Item.NestedItem.OtherId"] }, "d6b799dc-f464-4919-8435-a7b600cc408a" } }

But it's an invalid query as I get it
Answer: The $cond is a aggregation expression, you need to use $expr before $and operation, in your SQL query you have user OR so just updating in query $and to $or

corrected $eq syntax after $or

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $or: [
          {
            $eq: [
              {
                $cond: [
                  { $eq: ["$Item.NestedItem", null] },
                  null,
                  "$Item.NestedItem.Id"
                ]
              },
              "f4421f9e-5962-4c68-8049-a45600f36f4b"
            ]
          },
          {
            $eq: [
              {
                $cond: [
                  { $eq: ["$Item.NestedItem", null] },
                  null,
                  "$Item.NestedItem.OtherId"
                ]
              },
              "d6b799dc-f464-4919-8435-a7b600cc408a"
            ]
          }
        ]
      }
    }
  }
])

Playground
Comment: Right, you gave me some insights. Thanks
Comment: Is `Item` array or object?
Comment: An object. It looks like the query is pretty simple and the only question is how do I translate it via primitives I have. But it's unrelated to Mongo itself, so I think I just accept your answer and gone playing with it.
Comment: Okay good, have just updated and confirmed in playground, you can check if its help you.


Encontrar um botão usando XPath Selenium

Question: Estou tentando encontrar um botão usando o webdriver + selenium em python, o código do botão é:
<button class="w-full h-14 pt-2 pb-1 px-3 bg-accent text-dark-1 rounded-full md:rounded select-none cursor-pointer md:hover:shadow-big focus:outline-none md:focus:bg-accent-2 md:focus:shadow-small ">

Ativar

4 horas Minerando

</button>

Eu tentei:
driver.find_element_by_xpath('//button[.//div[text()="Ativar"]]').click()

Mas ocorre a mensagem de erro:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[.//div[text()="Ativar"]]"}

Todavia na página caso eu pesquise pelo inspecionar>Crtl+F e cole
//button[.//div[text()="Ativar"]]

ele encontra o botão... se alguém puder me ajudar por favor...
Comment: Particularmente não gosto do XPATH. Uma mudança de layout na tela e vc perde sua automatização. Porque simplesmente não utilizar `driver.find_element_by_link_text('Ativar')`?
Comment: Quer entender como encontar o xpath de um botão ou sabe como o xpath é extraido na ferramenta do desenvolvedor nos navegadores mas tem dúvida sobre o uso na lib do python?
Comment: Tenta inspecionar, dentro do inspecionar elemento, no item selecionado, clique com botão direito -> copy -> copy Xpath..
Tenta dessa forma.
Answer: Evite usar o find_element_by_xpath, pois qualquer modificação no layout da página irá quebrar seu script.
Dê preferência aos:

find_element_by_id
find_element_by_name
find_element_by_class (nem sempre válido, pois elementos diferentes podem compartilhar a mesma classe)

Porém, como não tive acesso ao fonte inteiro da página, no caso específico, eu usaria o find_element_by_link_text conforme abaixo
elem = driver.find_element_by_link_text('Ativar')
elem.click()

Answer: Se esse for o único button na pagina, você pode tentar algo assim:
driver.find_element_by_xpath(//*button[@class='font medium']descedant-or-self::div[@class='text-17 md:text-18 md:font-bold leading-18').click();

Se não funcionar desse jeito, eu sugiro duas modificações:

Tente tirar o asterisco que coloquei antes do button.
Substitua  o "descedant-or-self::" por uma barra simples "/"

Acredito também  que lhe sera de ajuda esse link para aprender alguns truques na hora de procurar por Xpath.
Answer: Olá, acredito que você precisa esperar a página carregar e somente ao finalizar o carregamento buscar o elemento pelo XPATH. Segue o exemplo, não testei, mas deve funcionar para o que você precisa.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

# Sua lógica anterior

# Essa parte do código vai esperar até o botão aparecer na tela
WebDriverWait(driver, 3).until(
  expected_conditions.visibility_of_element_located(
    (By.XPATH, '//button[.//div[text()="Ativar"]]')
  )
)

Comment: E como o @Paulo Marques disse, evite usar o XPATH.


Different way to form the power set

Question: The power set can be constructed as a "Cartesian product" as in the following example. Suppose $S=\{a, b, c\}$ and that $\times$ is a modified Cartesian product operator (see following paragraph), then:
$$Pset(S)=\{\emptyset,\{a\}\}\boxtimes \{\emptyset,\{b\}\} \boxtimes \{\emptyset,\{c\}\}$$
The difference being that the pairs of the product are actually unified together to make one set. For example, the pair $(\emptyset, \emptyset)$ yields $\emptyset$, the pair $(\emptyset, \{a\})$ yields $\{a\}$.
Does this operation have a standard name/notation? I want to prove that the resulting set is actually the power set but I need notation or try to introduce appropriate notation.
Note: This construction tells us that the cardinality is $2^{|S|}$ right away which is true.
Comment: How is what you do any different from $2^S = \{ S \to \{\mathbf{0},\mathbf{1}\}\}$?
Comment: You should probably use a symbol other than $\times$ for your *modified* Cartesian product to avoid confusion.
Comment: Maybe $\boxtimes$ or $\otimes$ (`\boxtimes`, `\otimes`)?
Comment: @WillieWong That's what I'm trying to prove!
Comment: What do you mean that's what you are trying to prove? [What I wrote is a definition](http://en.wikipedia.org/wiki/Power_set#Representing_subsets_as_functions).
Comment: @WillieWong It's an observation. Where do they say that it's a definition?
Comment: @RahulNarain Any suggestions?
Answer: The set you describe is not the power set of $\{a,b,c\}$. It is a set that has the same cardinality as the power set, but its elements $x$ do not satisfy $x\subseteq S$.
EDIT: after the clarifications and modifications it all makes sense now. I never saw the definition $A\boxtimes B=\{a\cup b\mid a\in A,b\in B\}$, which in the context of axiomatic set theory makes sense. It does not make sense universally in naive set theory though. The equality $\mathcal P(S)=\{\emptyset ,\{s_1\}\}\boxtimes \cdots \{ \emptyset, \{s_n\}\}$ makes sense and is true when $S=\{s_1,\cdots , s_n\}$. With a bit of care it can be extended to infinite sets and infinite box products.
Comment: what makes it the power set?
Comment: It is the power set! It's not the Cartesian product that's way I put it in quotes.
Comment: Try and list all the components of the set. You can try with a set that has 1 or two elements.
Comment: if the context of the question is axiomatic set theory (say ZF) then the existence of power sets is an axiom, not a definition. If the context is naive set theory, then the power set of $S$ is the set of all subsets of $S$. What you describe is not the power set, but rather a set of the same cardinality.
Comment: The OP is using $\times$ to denote something different from the usual Cartesian product. In their notation, $A\times B=\{a\cup b:a\in A,b\in B\}$.
Comment: @Saadtaame: There is not reason to be rude or hostile, that is uncalled for.  Also, Ittay Weiss is not wrong - this is essentially the subtle difference between two objects being isomorphic rather than equal.
Comment: @EricNaslun You are right. Apologies Ittay.

Different way to form the power set