text:
Q: MVC App System.Data.SqlClient.SqlException (0x80131904): I have an ASP.NET MVC web application that throws an error (shown below). I am using Entity Framework 6 with a code-first approach. I have other ASP.NET MVC applications running on the same server and they can connect to the database.
Here is my connection string
<add name="RADSystem"
     connectionString="data source=**.***.**.**\NAMED_INSTANCE;initial catalog=RAD_System;persist security info=True;user id=sa;password=****;multipleactiveresultsets=True;application name=EntityFramework"
     providerName="System.Data.SqlClient" />

The error thrown is:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
        at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
        at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
        at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
        at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
        at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
        at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
        at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
        at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
        at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
        at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
        at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
        at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
        at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
        at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
        at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
        at System.Data.SqlClient.SqlConnection.Open()
        at System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate)
        at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
        at System.Web.Profile.SqlProfileProvider.GetPropertyValuesFromDatabase(String userName, SettingsPropertyValueCollection svc)
        at System.Web.Profile.SqlProfileProvider.GetPropertyValues(SettingsContext sc, SettingsPropertyCollection properties)
        at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
        at System.Configuration.SettingsBase.SetPropertyValueByName(String propertyName, Object propertyValue)
        at System.Configuration.SettingsBase.set_Item(String propertyName, Object value)
        at System.Web.Profile.ProfileBase.SetInternal(String propertyName, Object value)
        at System.Web.Profile.ProfileBase.set_Item(String propertyName, Object value)
        at System.Web.Profile.ProfileBase.SetPropertyValue(String propertyName, Object propertyValue)
        at TotalDeskMVCVer4.Controllers.HomeController.Index(UserCustom model)
      ClientConnectionId:00000000-0000-0000-0000-000000000000
      Error Number:-1,State:0,Class:20
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
  at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
  at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
  at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
  at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
  at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
  at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
  at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
  at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
  at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
  at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
  at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
  at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
  at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
  at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
  at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
  at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
  at System.Data.SqlClient.SqlConnection.Open()
  at System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate)
  at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
  at System.Web.Profile.SqlProfileProvider.GetPropertyValuesFromDatabase(String userName, SettingsPropertyValueCollection svc)
  at System.Web.Profile.SqlProfileProvider.GetPropertyValues(SettingsContext sc, SettingsPropertyCollection properties)
  at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
  at System.Configuration.SettingsBase.SetPropertyValueByName(String propertyName, Object propertyValue)
  at System.Configuration.SettingsBase.set_Item(String propertyName, Object value)
  at System.Web.Profile.ProfileBase.SetInternal(String propertyName, Object value)
  at System.Web.Profile.ProfileBase.set_Item(String propertyName, Object value)
  at System.Web.Profile.ProfileBase.SetPropertyValue(String propertyName, Object propertyValue)
  at TotalDeskMVCVer4.Controllers.HomeController.Index(UserCustom model)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:-1,State:0,Class:20

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[Exception: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate)
   at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
   at System.Web.Profile.SqlProfileProvider.GetPropertyValuesFromDatabase(String userName, SettingsPropertyValueCollection svc)
   at System.Web.Profile.SqlProfileProvider.GetPropertyValues(SettingsContext sc, SettingsPropertyCollection properties)
   at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
   at System.Configuration.SettingsBase.SetPropertyValueByName(String propertyName, Object propertyValue)
   at System.Configuration.SettingsBase.set_Item(String propertyName, Object value)
   at System.Web.Profile.ProfileBase.SetInternal(String propertyName, Object value)
   at System.Web.Profile.ProfileBase.set_Item(String propertyName, Object value)
   at System.Web.Profile.ProfileBase.SetPropertyValue(String propertyName, Object propertyValue)
   at TotalDeskMVCVer4.Controllers.HomeController.Index(UserCustom model)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:-1,State:0,Class:20]
   TotalDeskMVCVer4.Controllers.HomeController.Index(UserCustom model) +7319
   lambda_method(Closure , ControllerBase , Object[] ) +104
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +181
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9667432
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: Make sure you that...

*

*You have spelled correct values in connection string.

*Are you able to successfull connect to database in SQL server with your servername, UserId and password.

I think your SQL server management studio or Sql Server in not working normally.


text:
Q: why are parts of the standard library in a separate namespace Why are some parts of the C++ standard library (and it seems like in more recent standards it is getting more common) not directly in the ::std namespace, but rather in a nested namespace? std::chrono and std::filesystem are two examples that pop to mind.

A: The obvious reason is the same as for any other project: there would be name collisions without it. For example, std::filesystem::copy vs. std::copy.
This isn't a complete explanation though, because

*

*I can't immediately see any collisions in the std::chrono namespace

*the committee could just have chosen a non-conflicting name instead

More convincingly,

*

*these libraries are based on their Boost predecessors, because those have proved to be useful and are well-tested. That means there's existing code using them, and it's easier to port that code to the C++11 versions if the namespace structure doesn't change, and no new conflicts are introduced.

*more broadly, C++ best practice has evolved since the first version of the standard library.

Note that (as Default points out in a comment), the regex library chooses consistency with Boost over namespace best practice, so it seems like #1 is more important. The same is true for std::thread etc.

Separating the factual from the speculative and hypothetical:

*

*The discussed libraries are based on Boost predecessors

*The discussed libraries keep the namespace structure of their Boost predecessors

*The discussed libraries' namespace structures are not consistent among themselves (or with the rest of the standard library)

*Changing namespace structure in C++, even without name collisions, can have side-effects related to ADL (so it isn't a trivial search-and-replace)

Conclusion: the namespace structure was chosen for consistency with Boost, rather than consistency with the rest of the standard library or even among the libraries added in C++11.

A: Having multiple namespaces minimizes the chance of aliasing problems. Everything from the standard library must be within std::, ok, but the standard library is still quite big for a single namespace. For example, in std::filesystem you have the function std::filesystem::status. It is easy to imagine other parts of the library where a status function may be needed at some point. And the namespace also makes clearer the purpose or "domain" of the function when reading the code.
Also, if you are, for example, using namespace std; at some point in your code, you may have some status function yourself in the current namespace so this allows you to avoid repeating std:: without pulling every single thing from the standard library directly into your local namespace, or more selectively pick the specific subset of names that you want to bring in.
That said, breaking down an API into uncountable namespaces is not too practical either. Maybe someone more familiar with the C++ standarization process can give a more complete answer with details about how does the committee decide when to add a namespace, but in the end is a matter of design and style, and there are no unequivocal, unquestionable rules.

A: Consider std::filesystem::absolute.
Without filesystem subnamespace this function should have been named something like std::filesystem_absolute. This is viable approach but is less flexible than one with a subnamespace. Remember that you can use Namespace aliases.

it seems like in more recent standards it is getting more common

I think this is the case because standard library is getting more and more large.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solution to equation modulo p Under the assumptions that $$p\cong 1 \mod 5$$ and $$g = 2(c+c^{-1})+1$$ where $c$ has order $5$ modulo $p$. I need to show that $g^2 \cong 5 \mod p$.
I have that $$g^2=4(c^4+c^3+c^2+c)+9$$
I know that if I can somehow remove the $c^3$ term, I can solve the equation through quadratic reciprocity. Can anybody give me some hints?

A: The key thing to note here is that $c$ has order $5$ modulo $p$; this implies that $c^5 \equiv 1 \pmod p$, and factoring gives $(c-1)(1+c+c^2+c^3+c^4) \equiv 0 \pmod p$. So either you will have $c=1$, which is handled trivially, or you will have $c+c^2+c^3+c^4 \equiv -1 \pmod p$, allowing you to simplify your expression.


text:
Q: Typescript functions with same name in multiple files I'm moving an existing JavaScript app into TypeScript, but struggling with how to achieve this:
In JavaScript I could optionally declare a function on each page then call that function from a global file if it exists
In global.js:
function globalFunc() {
    if (window.pageFunc) {
        pageFunc();
    }
}

And on each page (optionally):
function pageFunc() {
    ...
}

The biggest problem in Typescript is the obvious 'Duplicate function implementation' error.
There are a few reasons for doing this; but a good real example is registering window events to control the order of actions; e.g. (in global.js):
window.onresize = function() {
    //global resize actions
    ...
    if (window.pageResizeFunc) {
        pageResizeFunc();
    }
}

Any tips on how I should implement this in TypeScript?

A: I have a solution, although it feels quite dirty!
In global.ts:
function globalFunc() {
    if ((<any>window)) {
        (<any>window).pageFunc();
    }
}

And on each page (optionally):
(<any>window).pageFunc = function() {
    ...
}

A: You could add your definition for pageFunc to the Window interface as a global augmentation. Using any castings everywhere pretty much defeats the point for using Typescript. See below.
declare global {
    interface Window {
        pageFunc?(...args: unknown[]): void;
    }
}

function globalFunc() {
    if (window.pageFunc) {
        window.pageFunc();
    }
}

Playground Link


text:
Q: Removing specific emacs x resources I have some X Resources associated with EMACS. I want to remove those EMACS resources? How can I use xrdb -remove? Have not found much information and even less examples on what to do?
xrdb -query -all | grep -i emacs

Emacs*Background:   #000000
Emacs*Dialog*background:    #000000
Emacs*Dialog*foreground:    #ffffff
Emacs*Foreground:   #ffffff
Emacs*XlwScrollBar.Background:  #000000
Emacs*XlwScrollBar.Foreground:  #ffffff
Emacs*backgroundToolBarColor:   #000000
Emacs*bottomToolBarShadowColor: #000000
Emacs*menubar*background:   #000000
Emacs*menubar*foreground:   #ffffff
Emacs*popup*Background: #000000
Emacs*popup*Foreground: #ffffff
Emacs*topToolBarShadowColor:    #000000
Emacs.default.attributeBackground:  #000000
Emacs.default.attributeForeground:  #ffffff
Emacs.mode-line.attributeForeground:    #ffffff
Emacs.scroll-bar.attributeBackground:   #000000
Emacs.scroll-bar.attributeForeground:   #ffffff
Emacs.tool-bar.attributeBackground: #000000
Emacs.tool-bar.attributeForeground: #ffffff

A: I don't believe xrdb persists resources across invocations as a native capability, so they should reset when you log out and log back in, or if you kill xrdb and restart it.
If they keep coming back across login sessions, they're probably being loaded from your shell init scripts somewhere. They're typically read via something like xrdb -load $HOME/.Xresources but that is only convention.
Search your personal and the shared rc scripts for your shell on the system and search your home directory for files that contain resource definitions.

A: xrdb (see source code) removes all of the X server data for what it terms SCREEN_RESOURCES or XA_RESOURCE_MANAGER.  You're only interested in the latter.  Removing that will do more than what you probably intended, so you'd have to use xrdb -q to get the current data, edit that, and reload it.
That's not necessarily simple, because resources can have continuation-lines.  Your example doesn't do that.  Limiting it to that (I don't think it's likely that you have configured screen resources, so the -all option is unnecessary):
xrdb -q | grep -v -i emacs > foo
xrdb -load foo

Referring to the manpage would be helpful...
Killing/restarting xrdb will have no effect on the X server data.
Not mentioned in the manpage (which needs some work), xrdb accepts abbreviations for all of its options, e.g. the -query option can be given as just -q:
            else if (isabbreviation("-query", arg, 2)) {
                oper = OPQUERY;
                continue;
            }

That 2 is the length of -q.  Incidentally, its code for -quiet allows the same length, but since that is tested after -query, you would have to abbreviate that as -qui.


text:
Q: 2D planes how it 2D inspite of it has 3 coordinates? We know that any point in the plane can be represented as an ordered pair $(a, b)$ of real numbers, where $a$ is the x-coordinate and $b$ is the y-coordinate.For this reason, a plane is called two-dimensional.
But why the equation of plane is $ax+by+cz+d=0$ which has 3 coordinates?

A: The dimension is not related to the total number of variables, but rather to the number of variables you can freely choose (degrees of freedom). For instance, if you pick some values for $x$ and $y$, you cannot freely choose the value of $z$: it will be determined by the equation.
For instance, the points that belong to the plane $x+y+z = 1$ can also be described as points of the form
$$
(x,y,z) = (0,0,1) + t (1,0,-1) + s(0,1,-1), \quad t,s \in \mathbb{R}
$$
So, choosing a point in that plane, amounts to deciding on the value of $t,s$, hence dimension 2.

A: The concept of a "plane" is intrinsic. Planes can exist inside other objects, and whatever is happening outside of that plane, i.e. whatever is extrinsic to that plane, is not particularly relevant to the fact that the plane is a plane.
So.... What is a plane?
Well, you can go back to axiomatic geometry, i.e. the axioms of Euclid as refined in the 19th century. Pasch's axiom says that if $P$ is a plane, and if $T$ is a triangle in $P$, and if $L$ is a line in $P$, and if $L$ does not contain a vertex of $T$, and if $L$ crosses one of the side of $T$, then $L$ must also cross one of the other two sides of $P$. I'm sure you can convince yourself that this is true in
$$(*) \quad P = \{(x,y,x) \in \mathbb R^3 \mid ax + by + cz + d = 0\} \quad\text{(assuming $(a,b,c) \ne (0,0,0)$, of course)}
$$

For a more Cartesian point of view, it is true that the plane $P$ given by $(*)$ is a subset of the 3-dimensional Cartesian coordinate space $\mathbb R^3$. And it is true that each point of $P$ has three coordinates $(x,y,z)$. However, those three coordinates do not vary independently within $P$. What distinguishes a plane in $\mathbb R^3$ from the whole of $\mathbb R^3$ is that within $P$ one may find two coordinates which vary independently over $P$, but one cannot find three coordinates which vary independently over $P$. And this fact is true of any plane embedded in $\mathbb R^3$ that is given by a formula like $(*)$.
For example, if you consider the plane $P$ in $\mathbb R^3$ given by the equation
$$3x + 2y + 5z = 7
$$
then the two coordinates $x,y$ vary independently over $P$, whereas the third coordinate $z$ is completely determined by the values of $x$ and $y$, which one sees easily by solving to get $z = -\frac{3}{5}x - \frac{2}{5} y + \frac{7}{5}$.


text:
Q: Pappus theorem and surface area of spherical zone I'm trying to use Pappus's theorem to find the surface area of a spherical zone of radius, say, a and height a/2. According to the formula for spherical zone 2$\pi rh$, the surface area should be $\pi a^2$.
However, when using Pappus's theorem and having determined that the circular arc length from height 0 to height a/2 is$\ (1/6)$$\pi a$. I multiplied this by circumference 2$\pi a$ resulting in a surface area of$\ (1/3)$$\pi^2 a^2$, which is off by 4.5%. What am I missing here?


text:
Q: How to change the Html file referred inside a div on server side using C#? I have div inside which contactUsFAQ.html is included.
    <div id="divContactUsFAQ" runat="server" >
    <!--#include virtual="../HTML/ContactUsFAQ.html" -->
    </div>

I need to include ContactIRP.html file and remove ContactUsFAQ.html on server side.

A: you can access the div as divContactUsFAQ from CodeBehind and it has .InnerHTML property containing <!--#include virtual="../HTML/ContactUsFAQ.html" --> - you can just assign what you need to .InnerHTML.


text:
Q: Vue 3 can't set value when using axios request in vee-validate I have a component to use custom input. I'm using veevalidate with it and it's working perfect.
But today I realize I can't set value when use with axios request.
It's working when set a just string or predefined data like this.a = '1' :value="this.a"
                  <CustomInput
                type="text"
                name="surname"
                placeholder="surname"
                :value="'testparam'" // or :value="this.a"
                inputClass="form-control form-control-solid h-auto mb-1 mt-2"
                />

but when try to set value(coming from backend) to component nothing show up.
Like this
data () {
    return {
      userInfo: {
        name: '',
        surname: '',
        phone: ''
      }
    }
  },

    async created () {
        await this.axios.get(this.$store.state.baseUrl + 'user/personalInfo').then((response) => {
          this.userInfo = response.data
          console.log(this.userInfo)
        })
      }

and set
<CustomInput
                type="text"
                name="surname"
                placeholder="surname"
                :value="this.userInfo.name" // doing nothing
                inputClass="form-control form-control-solid h-auto mb-1 mt-2"
                />

I tried async created and normal created with methots but nothing changed.
My CustomInput.vue
    <template>
  <input
    :name="name"
    :id="name"
    :type="type"
    :value="inputValue"
    :inputmode="type"
    :placeholder="$t(placeholder)"
    :class="[inputClass, { 'has-error': !!errorMessage, success: meta.valid }, notRequired ? 'notreq' : '']"
    @input="handleChange"
    @blur="handleBlur"
    maxlength="255"
  />
  <p class="help-message" v-show="errorMessage">
    {{ errorMessage }}
  </p>
</template>

<script>
import { useField } from 'vee-validate'

export default {
  props: {
    type: {
      type: String,
      default: 'text'
    },
    value: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    inputClass: {
      type: String,
      default: ''
    },
    notRequired: {
      type: Boolean,
      default: false
    }
  },
  setup (props) {
    const {
      value: inputValue,
      errorMessage,
      meta,
      handleBlur,
      handleChange
    } = useField(props.name, undefined, {
      initialValue: props.value
    })
    return {
      errorMessage,
      inputValue,
      meta,
      handleBlur,
      handleChange
    }
  }
}
</script>

<style scoped>

input {
  background-color: #f3f6f9;
  color: #3f4254;
  padding: 12px;
  border-radius: 0.42rem;
  width: 100%;
  border: none;
}

input::placeholder {
  color: #c9c9d4;
  font-weight: 400;
}

input:focus-visible {
  outline: none;
}

input:focus {
  background-color: #ebedf3;
  color: #3f4254;
}

.help-message {
  margin: 0;
  color: #fd6a57;
  font-size: 0.9rem;
  font-weight: 400;
  width: 100%;
  text-align: center;
}

.has-error {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23F64E60' viewBox='0 0 12 12'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23F64E60' stroke='none'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.325rem) center;
  background-size: calc(0.75em + 0.65rem) calc(0.75em + 0.65rem);
}

.success {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%231BC5BD' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.325rem) center;
  background-size: calc(0.75em + 0.65rem) calc(0.75em + 0.65rem);
}

.notreq {
  background-image: none !important;
}

.newsletter {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
</style>

A: I think this issue because of your axios request. Before the axios request fulfilled, CustomInput component rendered with default props and the useForm composition API initialized with empty value.
My solution:
You can watch value props in CustomInput component setup method. Then every time it's value changed, update the value:
watch(
    () => props.value,
    (newValue, oldValue) => {
       console.log("value props changed: ", newValue);
       inputValue.value = newValue;
    }
);

In addition you have an issue in CustomInput props. Try to send userInfo.name instead of this.userInfo.name in template section!
You can see my code in this codesandbox project.


text:
Q: How to load a file using source command in ANT script? Using  Linux environment with java,I'm having the config file which should be configured before executing the eclipse application from console,
This is the OpenspliceDDS config file  to source which is in the following directory
source  /../HDE/x86.linx2.6./release.com    --->Executed at command line
But i need to execute the source command in ANT script  can any one help me out in this .
Example :
I have created the property tag for the command
<property name="release.path" location="/opt/HDE/x86.linux2.6/release.com"/>

<exec executable="source ${release.path}" spawn="true">

</exec>

A: I think you will need to make a wrapper script for Ant to invoke. In the wrapper script, execute the "source" command and then the "sources" command. (You could pass parameters for the file to source and to execute).
Follow up
For the wrapper script, I just mean something like this:
#!/bin/bash

env_file=$1
script_to_exec=$2

. $env_file
exec $script_to_exec

The point being that you need to source a file and then execute a script in the same environment. So wrap those up into a script which you can execute from a different environment (Ant).
To invoke that from Ant, something like this:
    <exec executable="wrapper_script">
        <arg value="${release.path}"/>
        <arg value="script_to_execute"/>
    </exec>


text:
Q: Why INNER JOIN dont not work correct? I have one SQL query with INNER JOINS. I need to get all offers from table offers.
Table offers is empty now. But the following query returns one row with NULL field.
Why is it returned? How to fix that? I need to return 0 rows if table is empty.
Query:
    select *, SUM(offers.price * announcement_product.amount) AS total, announcements.user_id AS creator_ann, announcements.id AS ann_id,
 announcements.delivery AS deliveryAnn, announcements.payment AS
 paymentAnn, SUM(announcement_product.amount) AS amount,
 announcement_product.name as name_product
from `offers`
inner join `announcements` on `announcements`.`id` = `offers`.`announcement_id`
inner join `announcement_product` on `offers`.`announcement_product_id` = `announcement_product`.`id`
inner join `countries` on `countries`.`id` = `announcements`.`country`

where `offers`.`user_id` = 1 and `offers`.`status` = 1 and `offers`.`deleted_at` is null

A: You're using the aggregate function SUM(), but you don't have any GROUP BY clause.
When you do that you are instructing MySQL to add up all the row values in the column you mention in SUM(). It will do that even if there are no rows to add up.
For best results you should study up on the GROUP BY function and how to use it with SUM().  It's hard to guess what you want from your query.

A: I'm not sure, but I don't think
select *, ..
when there's multiple tables in the query is valid.
Try
select offers.*,..

A: This how Your select structure should be :
Select
    Id,
    Sku,
    Sum(Onhand),
    Sum(price)
From mytable
           Where mytable Onhand > 0
               Group by
                        Id,Sku
If you are going to use aggregate function such as Max,Sum,Min,....
you need to use group by for other table fields that your using in the select part.


text:
Q: How can I sort the child items from the deepest sub folder to highest one? I try to get the files of a folder together with the files in its subfolders by doing:
$files = Get-ChildItem "d:\MyFolders" -recurse
QUESTION:
How can I sort the $files by their folder hierarchy meaning the deepest files will be at the top in the array and the upper most one will be the last element?
P.S : The reason is if I rename some folders than the path of the files under those renamed ones will be invalid. So I want to process the deepest ones first and move to upper files.

A: It's not specifically sorted by depth, but it will group folders in the same parent together, because of the sorting.
$files | Sort-Object -Descending FullName | Select-Object FullName

If you really need to sort by folder depth, you can do it like this:
$files | Select-Object FullName, @{Name="FolderDepth";Expression={$_.DirectoryName.Split('\').Count}} | Sort-Object -Descending FolderDepth,FullName

Just remove -Descending if you want to reverse the sorting.

A: A way to do this is to parse your directory level by level : you start with a list of directories to check (initially, you just have your start folder in the list).
Then, for each folder in the list check all direct children : write the files in a result file, add the folders in a "next folders" list.
Do it again with your "next folder" list until this list is empty.
You will get a result file with your file sorted by depth (OK, deepest files are the last in the file, so you'll have to reverse it, but it is sorted by depth anyway :)
This can be done recursively this way :
function Parse-ByDepth ($dirs, $resultfile) {
    $nextdirs=@()

    # if you also want the folders names in the result file
    # write their names in the result file
    $dirs |% {
      echo "$_" >> $resultfile
    }

    # Parse each directory in the list
    foreach ($dir in $dirs){
        # note that the get-childitem here is non recursive.
        # only one level is checked.
        Get-ChildItem $dir | % {
            if ($_.getType().Name -eq "FileInfo") {
               # If the item is a file, append it to the result file
               echo "$($_.FullName)" >> $resultfile
            }else {
               # if it is a folder, add the folder path to the "next folders" list
               $nextdirs+=$_.FullName
            }
        }
    }
    # once all the item of the current level have been parsed, check if the list is empty
    if ($nextdirs.Length -gt 0) {
        # if the list contains more folder, parse them
        Parse-ByDepth $nextdirs $resultfile
    }
}

then, you can call the function this way :
$initdir=@("d:\MyFolders")
$resultfile=C:\result_by_depth.txt
Parse-ByDepth $initdir $resultfile


text:
Q: In Neo4j is the default isolation level always READ_COMMITTED or is it the case only when extending it with Java? I am reading the documentation provided by Neo4j https://neo4j.com/docs/java-reference/current/transactions/, but as the link says, the rules provided in that explanation are valid when talking about the java-extension, what about Neo4j without any extension? I am interested in particular in the default isolation level, what is the default one in the basic case?

A: The default neo4j isolation level in all cases is READ_COMMITTED, which means that a transaction (A) that reads a node/relationship does not block another transaction (B) from writing to that node/relationship before A has completed.


text:
Q: there is error of Fatal error: Cannot redeclare domain_exists(); I have error when trying to insert data in databse, i get the following message:

Notice: Undefined variable: host in C:\wamp64\www\email_verify\index.php on line 53
   Notice: Undefined variable: target in C:\wamp64\www\email_verify\index.php on line 53
   Notice: Undefined variable: target_ip in C:\wamp64\www\email_verify\index.php on line 53
  Fatal error: Cannot redeclare domain_exists() (previously declared in C:\wamp64\www\email_verify\index.php:13) in C:\wamp64\www\email_verify\index.php on line 13

how can i solve it....?
<?php
include_once('config.php');
if(isset($_POST["email_verify_btn"])) {

        $email = $_POST["email_verify"];

        if(strpos($email,"\n")) {

        $text = explode("\n",$email);

            foreach ($text as $abc) {

                    function domain_exists($abc)
                    {
                        $domain = substr(strrchr($abc, "@"), 1);

                        $arr = @dns_get_record($domain, DNS_MX);

                        if ($arr[0]['host'] == $domain && !empty($arr[0]['target'])) {
                            return $arr[0]['target'];
                        }
                    }
                    if(domain_exists($abc)){
                        $domain = substr(strrchr($fetch_email, "@"), 1);

                        $data = @dns_get_record($domain, DNS_MX);

                            if($data) {
                            $status = "email id is valid";
                        }
                        if (is_array($data) || is_object($data)) {

                            foreach ($data as $key1) {

                                $host = $key1['host'];
                                $target = $key1['target'];
                                $target_ip = gethostbyname($key1['target']);

                            }

                        }

                    } else {
                      $status = "mx recored not exist";
                    }

                    $c_by = 1;
                    $c_date = date('Y-m-d H:i:s');
                    $c_ip = $_SERVER['REMOTE_ADDR'];

                    $insert = $connect->query("INSERT INTO `email_verify_list`(`primary_email`,`host_name`,`target`,`target_ip`,`session`,`created_by`, `created_date`, `created_ip`) VALUES ('$abc','$host','$target','$target_ip','$c_ip','$c_by','$c_date','$c_ip')");

                    if($insert) {
                        $_SESSION['date_time'] = $c_date;
                        echo "";
                    } else {
                        echo "";
                    }

            }

        }

}
?>

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<meta charset="utf-8"/>
<title>BULK EMAIL VARIFIER</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"/>
<link rel="apple-touch-icon" href="pages/ico/60.png">
<link rel="apple-touch-icon" sizes="76x76" href="pages/ico/76.png">
<link rel="apple-touch-icon" sizes="120x120" href="pages/ico/120.png">
<link rel="apple-touch-icon" sizes="152x152" href="pages/ico/152.png">
<link rel="icon" type="image/x-icon" href="favicon.ico"/>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta content="" name="description"/>
<meta content="" name="author"/>
<link href="assets/plugins/pace/pace-theme-flash.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/bootstrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="assets/plugins/switchery/css/switchery.min.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="pages/css/pages-icons.css" rel="stylesheet" type="text/css" />
<link class="main-stylesheet" href="pages/css/pages.css" rel="stylesheet" type="text/css"/>

EMAIL VERIFY

<form  method="post" action="" >

        ENTER YOUR EMAIL

        <textarea cols="43" rows="9" name="email_verify"  style="border-color:white;border-width:thin;padding:4pt;" multiple/></textarea>

        <button type="submit" name="email_verify_btn" class="btn btn-lg btn-info"  style="padding:11pt;width:200px;"/>SUBMIT</button>

        PRIMARY EMAIL
        HOST NAME
        TARGET
        TARGET IP
        STATUS

        <?php

        $select = $connect->query("SELECT * from `email_verify_list` where session='".$_SESSION['date_time']."' order by id");
        while($row = $select->fetch_assoc()) {
        ?>

        <?php echo $row['primary_email']; ?>
        <?php echo $row['host_name']; ?>
        <?php echo $row['target']; ?>
        <?php echo $row['target_ip']; ?>
        <?php echo $row['status']; ?>

        <?php } ?>

</form>

A: Don't declare the function inside the loop.
Put this:
                function domain_exists($abc)
                {
                    $domain = substr(strrchr($abc, "@"), 1);

                    $arr = @dns_get_record($domain, DNS_MX);

                    if ($arr[0]['host'] == $domain && !empty($arr[0]['target'])) {
                        return $arr[0]['target'];
                    }
                }

... before this line:
        foreach ($text as $abc) {

Next, you need to declare the variables $target and $target_ip on the same level as you're trying to use them, i.e. on the same level as this line:
$insert = $connect->query("INSERT INTO `email_verify_list`(`primary_email`,`host_name`,`target`,`target_ip`,`session`,`created_by`, `created_date`, `created_ip`) VALUES ('$abc','$host','$target','$target_ip','$c_ip','$c_by','$c_date','$c_ip')")


text:
Q: Run SQL queries without external database I have a text file of tab separated data. Millions of rows so I can't open it in Excel.
Is there a way to use some SQL client to load the file and run queries on it without uploading the file to a database? I.e. can my local machine function as my database?
I know I could solve this with command line scripting but I'm trying to find a solution that I can then share with the accounting department and they're scared of the command line.

A: You can create an ODBC datasource based on the Microsoft Text Driver. That driver should come pre-installed on any Windows PC. This uses the Jet Engine which is still somewhere in the Windows OS. Then you can use any Query tool (even MS Query) to analyse your data.


text:
Q: JS function change text on button click only works on Desktop I have a function set up so that when a button labeled "The Night" is clicked, dark mode is activated, and the buttons text changes to "The Day". This works fine in my Desktop navigation, but for some reason it doesn't work when put into my mobile navigation. You can view the site here to see what I mean: https://blanklandscape.com/
HTML

            The Forest
            The Ocean
            The Sky
            The Mountain
            <input type="button" value="The Night" id="dark-btn" class="dark-mode" onclick="myFunction(); change();" />
            About

                The Forest
                The Ocean
                The Sky
                The Mountain
                <input type="button" value="The Night" id="dark-btn" class="dark-mode" onclick="myFunction(); change();" />
                About

JS
/* Day/Night Mode */

  function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}

/* Day/Night Button Text */

  function change() {
    var elem = document.getElementById("dark-btn");
    if (elem.value=="The Night") elem.value = "The Day";
    else elem.value = "The Night";
}

A: well the id of each node should be unique as per the rules, So instead of giving both buttons id you can give them a common class and achieve the result.

            The Forest
            The Ocean
            The Sky
            The Mountain
            <input type="button" value="The Night" id="dark-btn-1" class="dark-mode dark-btn" onclick="myFunction(); change();" />
            About

                The Forest
                The Ocean
                The Sky
                The Mountain
                <input type="button" value="The Night" id="dark-btn-2" class="dark-mode dark-btn" onclick="myFunction(); change();" />
                About

and in your js code
/* Day/Night Button Text */

  function change() {
    var elems = document.querySelectorAll(".dark-btn");
    elems.forEach(elem => {
        if (elem.value=="The Night") elem.value = "The Day";
        else elem.value = "The Night";
    })

}

or if you don't care about the rules and still want to have both of them same id. you can still get the expected behavior by this js code
function change() {
    var elems = document.querySelectorAll("#dark-btn");
    elems.forEach(elem => {
        if (elem.value=="The Night") elem.value = "The Day";
        else elem.value = "The Night";
    })

}


text:
Q: $http.get in angularjs showing "TypeError: boolean is not a function" I am using angularjs $http.get in a factory to execute an API call.  When I ran my angularjs app, it returns the data.  however, when I looked in the console tab using F12, it has:
"TypeError: boolean is not a function"

This error is generated from angular.js file.  Please see below for the factory code and the listController code.
Does anyone have any idea why the following code cause angular.js to generate:
"TypeError: boolean is not a function" and how to fix the following code to resolve this error?

Here is the code in the factory:
app.factory('MyFactory', function ($http) {
    var dataFactory = {};
    var urlBase = 'api/suppliers/search?&q=';
    dataFactory.search = function (searchString) {
        var urlString = urlBase + searchString;
        return $http.get(urlString)
    }
    return dataFactory;
});

Here is the code that calling the factory:
var ListController = function ($scope, $location, MyFactory) {

    $scope.message = "List.html page";

    var searchstring = 'de';

    getSuppliers();

    function getSuppliers() {
        MyFactory.search(searchstring)
            .success(function (data) {
                $scope.suppliers = [];
                $scope.suppliers = data.items;
            })
            .error(function (error) {
                $scope.status = "Unable to load customer data: " + error.message;
            });
    }

};

A: $http returns a promise.  You need to call then() and pass your callbacks to it
function getSuppliers() {
    MyFactory.search(searchstring).then(function (data) {
       $scope.suppliers = [];
       $scope.suppliers = data.items;
    },function (error) {
       $scope.status = "Unable to load customer data: " + error.message;
    });
}


text:
Q: Python Dataframe get the NaN columns for each row I have a pandas data frame that looks like this:
      a     b      c
0   NaN   2.0  165.0
1   NaN   9.0    NaN
2   NaN   NaN    NaN
3  15.0  15.0    NaN
4   5.0   NaN   11.0

I would like to add a column that gives me something like a summary of missing values. So, I need a command which gives me the list of columns with missing values for every row. Something like this:
      a     b      c    summary
0   NaN   2.0  165.0          a
1   NaN   9.0    NaN      a + c
2   NaN   NaN    NaN  a + b + c
3  15.0  15.0    NaN          c
4   5.0   NaN   11.0          b

A: Here is one way.
import pandas as pd
import numpy as np

df = pd.DataFrame(
    [
        [np.nan, 2, 165],
        [np.nan, 9, np.nan],
        [np.nan, np.nan, np.nan],
        [15, 15, np.nan],
        [5, np.nan, 11]
    ],
    columns=['a', 'b', 'c']
)

df['Errors'] = df.apply(lambda row: ' + '.join(i for i in ['a', 'b', 'c'] if np.isnan(row[i])), axis=1)


text:
Q: How do I figure out who maintains a bower packge? bower info doesn't seem to show this information.
➔ bower info sugar --verbose
bower sugar#*                   cached git://github.com/andrewplummer/Sugar.git#1.4.1
bower sugar#*                 validate 1.4.1 against git://github.com/andrewplummer/Sugar.git#*

{
  name: 'sugar',
  version: '1.4.1',
  main: './release/sugar.min.js',
  ignore: [
    '/docs',
    '/lib',
    '/script',
    '/test',
    '/performance',
    '.gitignore',
    '.npmignore',
    '.travis.yml',
    'package.json'
  ],
  dependencies: {},
  homepage: 'https://github.com/andrewplummer/Sugar'
}

Available versions:
  - 1.4.1
  - 1.4.0
  - 1.3.9
  - 1.3.8
  - 1.3.7
  - 1.3.6
  - 1.3.5
  - 1.3.4
  - 1.3.3
  - 1.3.2
  - 1.3.1
  - 1.2.5
  - 1.2.4
  - 1.2.3
  - 1.2.2
  - 1.2.1
  - 1.1.3
  - 1.1.2
  - 1.1.1
  - 0.9.5
  - 0.9.4
  - 0.9.3
  - 0.9.2
  - 0.9.1
You can request info for a specific version with 'bower info sugar#<version>'

A: In your case, the maintainer is the owner of the github page of the Sugarjs - http://github.com/andrewplummer/Sugar.
It's a good practice putting information about the maintainer on the authors field of the bower.js, usually you can get on the bower.json file.

A: If you are asking about who maintains the registry, rather than who maintains the code, it depends on which registry you are using.  By default, you are probably using https://bower.herokuapp.com, but you can use a private registry as well.  See What is the default (official?) Bower registry URL? for a little more info.


text:
Q: PHP / MySQL Forum Post Order I have one table called cf_posts
ID pk
user INT
subject VARCHAR
body TEXT
datetime TIMESTAMP
parent INT
category INT
mod INT

When a post is submitted to the forum the default parent is 0, when a post is submitted as a reply, then its parent is the ID of the original post.
How can I make it so that the default view of the forum main page is ordered that the most recently updated post (including the latest replies) would be at the "top" of the pile, and working down in date order?  What would be the PHP/MySQL query?
The only workarounds I have seen for this are separate topics and reply tables, but I'd like to stay away from this approach if possible.
One workaround that I tried and failed was GROUP BY parent.
But this grouped all topics that had no replies together as one.
Another idea that I have yet to try is to make the parent id of the original post match the post ID, and not include matching ID and parent IDs in the output.
I look forward to hearing your thoughts.

A: SELECT mainPost.subject, lastPost.datetime
FROM cf_posts cfp,
(
 SELECT *
 FROM cf_posts subPost
 WHERE subPost.parent = mainPost
 ORDER BY subPost.datetime DESC
 LIMIT 1
)lastPost
WHERE mainPost.parent IS NULL

This is done briefly, so there may be some syntax issues but I think this should help.

A: You can do the following: query each separate thing that you need, so maybe a query for each topic, Then you can use UNION to bunch all of them together to get one list. Now the trick to preserve an order is as followed. For each separate query append a column to the returned result called sort and set each instance of that to a higher int value, then you can guarantee that the final result is properly sorted. Go review UNION for select statements to get a better understanding of what I'm talking about.


text:
Q: splice/merge/combine videos from array in Swift 5 I'm new to the AVFoundation part of swift. I am trying to splice multiple videos (URL's) into one video. (Splice meaning have one video play after another, in the order of the array) I have seen several threads on this but they're all outdated and no longer work.
Here's what I have so far:
var outputUrl: URL! //video goes here after recording
var videoArray = [URL]()

//after recording,
videoArray.append(outputUrl)

func splice() {
// I need help with this part;
 //splice each entry in videoArray
}

var splicedVideo: URL! //<-- I need to save the composition to this URL

Sorry if this question isn't what you're used to seeing; I'm trying to be as specific as possible but I'm not sure where to start.  Can someone help me write this function or point me to a thread with one?


text:
Q: Does this sum to $2^n-1\ $? $$N=\sum_{i=1}^{n} C^i_n = \sum_{i=1}^n\frac{n(n-1)\cdots(n-i+1)}{i!}$$
Does $N = 2^n-1$ hold ?
I mean, $C^i_n = \binom{n}{i}$. According to the binomial formula, if this summation sums from $i=0$ instead of $i=1$, then it's equal to $2^n$.
Because of this, does this sum to $2^n-1$?

A: Yes. We know that
$$
\sum_{i=0}^n \binom{n}{i} = 2^n.
$$
Therefore
$$
\sum_{i=1}^n \binom{n}{i} = \sum_{i=1}^n \binom{n}{i} + \binom{n}{0} - \binom{n}{0} = \sum_{i=0}^n \binom{n}{i}-\binom{n}{0}
= 2^n-1.
$$

A: A more combinatorial way to look at this:
We know that $\binom{n}{i}$ represents the number of ways to choose exactly $i$ elements from a collection of $n$ elements.
We sum this over $i=1,2,\ldots,n$; so, the result is the total number of ways to choose a set consisting of EITHER 1 element, 2 elements, 3 elements, ... up to $n$ elements, from a collection of $n$ elements.
In other words: it is the number of ways to choose a non-empty subset from a collection of $n$ elements.  There are $2^n$ ways to choose ANY subset (including the possibility of the empty subset); we can see this by noting that each element is either included or excluded, and we have to make $n$ such decisions.  And, there is only such sequence of choices that leads to the empty set.  So, the total number of non-empty subsets possible is just $2^n-1$.

A: We know that
$$(a+b)^n=\sum_{i=0}^n \binom {n}{i}a^{n-i}b^i$$
with $a=b=1$, it becomes
$$2^n=\sum_{i=0}^n\binom {n}{i} $$
$$=\sum_{i=\color {red} {1}}^n\binom {n}{i}+\frac {n!}{0!(n-0)!}$$
$$=N+1$$


text:
Q: Connection Refused When Running SparkPi Locally I'm trying to run a simple execution of the SparkPi example.  I started the master and one worker, then executed the job on my local "cluster", but end up getting a sequence of errors all ending with
Caused by: akka.remote.transport.netty.NettyTransport$$anonfun$associate$1$$anon$2: Connection refused: /127.0.0.1:39398

I originally tried running my master and worker without configuration but ended up with the same error.  I tried to change to 127.0.0.1 to test if it was maybe just a firewall issue since the server is locked down from the outside world.
My conf/spark-conf.sh contains the following:
export SPARK_MASTER_IP=127.0.0.1

Here is the order and commands I run:
1) sbin/start-master.sh (to start the master)
2) bin/spark-class org.apache.spark.deploy.worker.Worker spark://127.0.0.1:7077 --ip 127.0.0.1 --port 1111 (in a different session on the same machine to start the slave)
3) bin/run-example org.apache.spark.examples.SparkPi spark://127.0.0.1:7077 (in a different session on the same machine to start the job)
I find it hard to believe that I'm locked down enough that running locally would cause problems.

A: It looks like you should not set SPARK_MASTER_IP to a loopback address 127.0.0.1. The worker node will not be able to connect to the MASTER node using a loopback address.
You shall set it to a valid local ip address(e.g., 192.168.0.2) in conf/spark-env.sh and add the worker's IP in conf/slaves configuration file in both MASTER and the WORKER node.
Then you can use sbin/start-all.sh to start the cluster.
And then run "bin/run-example org.apache.spark.examples.SparkPi"


text:
Q: Accordion List Using Jquery and Ajax I'm Trying to Implement an accordion list. So basically this a bootstrap accordion. The title of the accordion is already set by PHP. When the user clicks the accordion it must display list of the session that is coming from server. I am using an ajax call for this, the issue every time I click the accordion only first elements get the results. Other elements didn't get the result just a blank view is displayed. I am fairly new to jquery. Here is my Html Code

    <?php foreach($modules as $module): ?>

                <button id="<?php echo $module->id;?>" type="button" class="btn" data-toggle="collapse"
                    data-target="#collapse<?php echo $module->id; ?>"><?php echo $module->module_name; ?></button>

        <div id="collapse<?php echo $module->id; ?>" class="collapse" aria-labelledby="headingOne"
            data-parent="#myAccordion">

                        '+data[i].session_name+'' +

    <?php endforeach; ?>

This is my Jquery and ajax code

Really appricate your help

A: You need to give your sessionlists unique ids aswell. Because when you append your myhtmlstring to #sessionlist it only ever takes the first one.
<ul id="sessionlist<?php echo $module->id; ?>" class="list-group list-group-flush">

     '+data[i].session_name+'' +

then you can append it to the right sessionlist in your ajax success:


text:
Q: Permisson Denied when tried to copied file from location to cointainer I'm follow steps in Here to set up a distributed test by Jmeter but in copy my local jmeter test into the master container I got a permission denied error, specifically
sh: 2: /jmeter/apache-jmeter-3.3/bin/: Permission denied

A: I'm not clear on what you're trying to do.
If you're trying to copy a file from your Host to Docker container, why not just mount the file/directory in to the container during runtime using --mount or -v. For example: docker run -v <local path>:<dst path on docker container> <ImageName>
Edit: This works between multiple containers as well. You can use SharedVolumes to share storage between 2 or more containers. Read more here: https://docs.docker.com/storage/volumes/

A: Execute the following commands:

*

*docker exec -t master chmod +x /jmeter/apache-jmeter-3.3/bin/jmeter.sh

*docker exec -t slave01 chmod +x /jmeter/apache-jmeter-3.3/bin/jmeter.sh

*etc.

This will make jmeter.sh script executable via chmod command

Also be aware that according to JMeter Best Practices you should always be using the latest version of JMeter so consider upgrading to JMeter 5.1 (or whatever is the latest version available at JMeter Downloads page) on next available opportunity.


text:
Q: Is i915 the right driver for my TigerLake-LP GT2 [Iris Xe Graphics] GPU? I just upgraded from 20.04 on an old laptop to 21.10 on a new one. The old one used the proprietary NVidia graphics driver - the new one uses i915. My GPU setup:
$ sudo lshw -C video
  *-display
       description: VGA compatible controller
       product: TigerLake-LP GT2 [Iris Xe Graphics]
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       logical name: /dev/fb0
       version: 01
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list fb
       configuration: depth=32 driver=i915 latency=0 mode=1920x1080 visual=truecolor xres=1920 yres=1080
       resources: iomemory:600-5ff iomemory:400-3ff irq:184 memory:603c000000-603cffffff memory:4000000000-400fffffff ioport:3000(size=64) memory:c0000-dffff memory:4010000000-4016ffffff memory:4020000000-40ffffffff

On my old laptop, when I opened "Software and updates", I could choose to replace the Nouveau driver with a proprietary NVidia one, but when I open Software and updates on my new machine, it says "There are no futher drivers available" and "No proprietary drivers are in use".
I'm having trouble getting my secondary display to display anything (it is detected - there's just no signal), and one of the first things to do is to figure out if the right driver is in use...


text:
Q: Find profit maximizing profit and quantity given willingness to supply curves and a merger This is a homework problem, but I'm at my wit's end.  I don't even know where to start on this, but I've tried a number of strategies.
Consider a regional market for wholesale electricity where there are 4  firms, who have submitted the following willingness-to-supply curve     functions, where P represents the price in $/MWh, and Q is the quantity of  MWh.
S1(P):      Qs  =  10 P     P  =  .10 Qs
S2(P):      Qs  =  2.5 P        P  =  .40 Qs
S3(P):      Qs  =  5 P      P  =  .20 Qs
S4(P):      Qs  =  7.5 P        P  =  .1333333 Qs

The total market demand is 2,000 MWh.  Suppose that firm 1 and firm 2   decide to merge, and that the merged firm has a total cost function given by
C  =  10,785  +   1.10 Q  +  .05 Q2

If the newly merged firm maximizes profits, then what is the profit     maximizing price and quantity of electricity?
I tried setting Q1 and Q2 equal to zero.  So I get (5+7.5)P = 2000 and therefore P= 160.  I know that this is a step, but I have no idea where to continue.

A: Find the market supply function: sum of quantities supplied by all firms as a function of price. Set it equal to the fixed demand 2000 MWh (I assume this is perfectly inelastic) to find the equilibrium price. The quantity must be 2000 MWh.
The merged firm's willingness to supply function comes from price equalling marginal cost.


text:
Q: Outlook 2013: select multiple emails and autoreply using template I am trying to get this code to work.
I want to select multiple emails from my inbox and send a auto reply using a template.
I am getting a run-time error: Object variable or With Block variable not set.
Any help would be appreciated. Also I would like to add a msg box telling me how many items were sent.
Option Explicit

Sub ReplywithTemplate()
Dim Item As Outlook.MailItem
Dim oRespond As Outlook.MailItem

For Each Item In ActiveExplorer.Selection

' This sends a response back using a template
Set oRespond = Application.CreateItemFromTemplate("C:\Users\Accounting\AppData\Roaming\Microsoft\Templates\scautoreply.oft")

With oRespond

    .Recipients.Add Item.SenderEmailAddress
    .Subject = Item.Subject

    ' includes the original message as an attachment
    .Attachments.Add Item

    ' use this for testing, change to .send once you have it working as desired
    .Display
End With
On Error Resume Next
Next
Set oRespond = Nothing

End Sub

A: I have noticed the following lines of code:
 For Each oRespond In ActiveExplorer.Selection

 ' This sends a response back using a template
 Set oRespond = Application.CreateItemFromTemplate("C:\Users\Accounting\AppData\Roaming\Microsoft\Templates\scautoreply.oft")

 With oRespond

You need to use a new variable for creating an auto-reply email from a template because the selected Outlook item is missed (replaced with a newly created one).
So, basically you can create an item from a template, add recipients from the selected Outlook item and call the Send method. Or you can use the Reply method of the selected item in Outlook, copy the required properties from a template and call the Send method. It is up to you which way is to choose.
Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.


text:
Q: Disabling hover rule from JavaScript I would like to disable a :hover rule when certain JavaScript code is triggered.
My css looks like this:
.headerfoldout a{
    background-color: red;
}
.headerfoldout a:hover{
    background-color: blue;
}

When this JavaScript is triggered, I change the headerfoldout color, but I want it to remain the same color, even when hovered.
The JavaScript I use to set the css is as follows:
document.getElementById("headerfoldout").setAttribute("style", "background-color: green;");

A: Instead of applying the styles with JavaScript is safer to do it with CSS and using classes in Js:
.headerfoldout a {
    background-color: red;
}

.headerfoldout a:hover {
    background-color: blue;
}

.green.headerfoldout a, .green.headerfoldout a:hover {
    background-color: green;
}

And in the Js:
// without checking the classname
document.getElementById("headerfoldout").className += " green";

Safer approach:
// checking the classname
var element, name, arr;
element = document.getElementById("headerfoldout");
name = "green";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
    element.className += " " + name;
}

Note: I prefer className over classList because it will work in all browsers.
Edit:
As mentioned in the comments, classList could be used to simplify the code:
 document.getElementById("headerfoldout").classList.add("green");

But be careful, it is not supported in IE9.


text:
Q: python dictionary from config parser if value and "%(" in value: argument of type 'int' is not iterable Getting this error in as random, sometimes appear, sometimes not:
for i in range(1,32):
    sezione = "GRP"+str(i)
    dizionarioGRP = dict(config.items(sezione))
    print int(dizionarioGRP['r'])

and this is the error
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/home/pi/gigi.py", line 436, in run
    self.esegui()
  File "/home/pi/gigi.py", line 307, in esegui
    L.gruppo(idgruppo)
  File "/home/pi/gigi1.py", line 282, in gruppo
    dizionarioGRP = dict(config.items(sezione))
  File "/usr/lib/python2.7/ConfigParser.py", line 655, in items
    for option in options]
  File "/usr/lib/python2.7/ConfigParser.py", line 663, in _interpolate
    if value and "%(" in value:
TypeError: argument of type 'int' is not iterable

why it is referring as int, if I've converted it in a string?

A: Somewhere in your code you're doing this:
config.set('something', 'something', 0) # or some integer

Or optionally you're passing in a non-string value in your ConfigParser constructor dict.
This is subtly against what the docs say:

If the given section exists, set the given option to the specified
  value; otherwise raise NoSectionError. While it is possible to use
  RawConfigParser (or ConfigParser with raw parameters set to true) for
  internal storage of non-string values, full functionality (including
  interpolation and output to files) can only be achieved using string
  values.

So whenever you call ConfigParser.set, make sure you wrap what you're setting in str.  Otherwise it throws an error when it runs through all the values in _interpolate.  (I consider some part of this behavior a bug, but it's probably kept as-is for backwards compatibility.  Or something.)
Another good thing to do is use SafeConfigParser which will throw a TypeError if you try to set a non-string value, so you know this won't happen again.


text:
Q: Grep printing a line that doesn't contain a set of numbers I'm trying to get Grep to print all lines in a txt file that do not contain the numbers 834.  When I try "grep [^834] file.txt"  it still prints all the lines containing 834 but just doesn't highlight them.

A: Try
grep -v '[834]' file

From man grep
   -v, --invert-match
          Invert the sense of matching, to select non-matching lines.  (-v
          is specified by POSIX.)

A: You ask grep to print all lines that contain a pattern consisting of a character that is not a 8, 3 or 4. Depending on what your file consists of, this will probably find almost anything.
To show "everything but" grep has the -v switch. E.g. something like grep -v "8\|3\|4" should work. Or if you specifically want to throw out the number 834: grep -v 834


text:
Q: addEventListener isn't triggering on keypress I'm trying to add custom keys to trigger events. I can get the keyup and the keydown events to work but for some reason the keypress event isn't working. I have seen many duplicates to these but most is in jquery.
In addition, in researching this, I came across the documentation that states that keyCode is deprecated and key should be used instead. However if I write
if (event.key === 74)

the code doesn't work
The code below is a simple example of what i'm trying to do.

window.addEventListener('keypress', function(event) {
  if (event.keyCode === 74) {
    console.log('Show me');
  }
});

A: Your code works just fine (assuming you are entering a capital J).
If you also want to check against a lowercase J, the keyCode would be 106:

window.addEventListener('keypress', function(event) {
  if (event.keyCode === 74 || event.keyCode === 106) {
    console.log('Show me');
  }
});

A: The difference is in the capital and small j. You are using code for capital j only

window.addEventListener('keypress', function(event) {
console.log(event.keyCode)
  if (event.keyCode === 74 || event.keyCode === 106) {
    console.log('Show me');
  }
});

A: You need to use the even.which when you check for J(74):

window.addEventListener('keypress', function(event) {
  if (event.which === 74) {
    console.log('Show me');
  }
});

A: You can use key down instead, this will catch both upper and lower case j.

window.addEventListener('keydown', function(event) {
  if (event.keyCode === 74) {
    console.log('Show me');
  }
});


text:
Q: Rails 3.2.1 - wrong number of arguments (3 for 1) in app.call(env) - any idea? I've just upgraded my app to Rails 3.2.1, and when I start up the server, I get this: ArgumentError (wrong number of arguments (3 for 1)). It's happening with a bunch of my gems, but also this rack middleware I include.
def call(env)
  env['PATH_INFO'] = env['PATH_INFO'].downcase
  @app.call(env)
end

Has something about the call function changed?

A: The Rails upgrade and the middleware were both red herrings. Omniauth changed the way strategies work https://github.com/intridea/omniauth/issues/529 and that was breaking everything in my app.
Doubt this answer will be useful to anyone, but thanks for the help.


text:
Q: Ranger file manager becomes unresponsive on using some applications Suppose I open a text file using Emacs or a picture using Gimp then the Ranger file manager becomes unresponsive till you close this application.
However if I open the same text file say using Gedit or the picture using Eye of Gnome, then the Ranger file manager session is still active and I can use it to move around the folders, browse files and do the usual operations.
Why is this happening?
How to prevent this from happening?

A: Use & which will run the command asynchronously, so ranger will still be usable while you have the application open.
For example, in your rifle.conf use the following line:
mime ^text,  label editor = emacs & -- "$@"

instead of
mime ^text,  label editor = emacs -- "$@"

Similarly suppose you want to open an image with gimp then you can press r in ranger to open a list of available applications. The list might look like:
0 | eog -- "$@"
1 | feh -- "$@"
2 | eom -- "$@"
3 | gimp -- "$@"
:open_with

Then use 3 & instead of 3 to open the image in gimp while keeping ranger usable.
Sometime ranger may not be configured to recognize the correct application (for example mathematica). You can still choose that application by typing the name of the application at the prompt :open_with. However to keep the ranger still responsive use the flag f as in:
:open_with mathematica f

(the above method to use a flagf is from here)


text:
Q: Differential amplifier with current mirror I am having difficulties with sections e and g and would appreciate some assistance/guidance if possible.
As for section e, I figured I could use the following expression for the current to evaluate  \$V_{sd4}\$:
\$I_{sd4}=k_4(V_{gs4}+0.2)^2(1+0.05V_{sd4})\$, where \$I_{sd4}=23.745 \mu A\$ and was found in previous sections. The problem is that this yields \$V_{sd4}=0V\$ and \$V_{01_{dc}}=5V\$, which doesn't seem correct.
As for section g, I believe there's an error here, isn't there? How is \$r_{o6}\$ even relevant to the DC calculation asked for??


text:
Q: Constraining on a Minimum of Distinct Values with PuLP I've been using the PuLP library for a side project (daily fantasy sports) where I optimize the projected value of a lineup based on a series of constraints.
I've implemented most of them, but one constraint is that players must come from at least three separate teams.
This paper has an implementation (page 18, 4.2), which I've attached as an image:

It seems that they somehow derive an indicator variable for each team that's one if a given team has at least one player in the lineup, and then it constrains the sum of those indicators to be greater than or equal to 3.
Does anybody know how this would be implemented in PuLP?
Similar examples would also be helpful.
Any assistance would be super appreciated!

A: In this case you would define a binary variable t that sets an upper limit of the x variables. In python I don't like to name variables with a single letter but as I have nothing else to go on here is how I would do it in pulp.
assume that the variables lineups, players, players_by_team and teams are set somewhere else
x_index = [i,p for i in lineups for p in players]
t_index = [i,t for i in lineups for t in teams]
x = LpVariable.dicts("x", x_index, lowBound=0)
t = LpVAriable.dicts("t", t_index, cat=LpBinary)
for l in teams:
   prob += t[i,l] <=lpSum([x[i,k] for k in players_by_team[l]])
prob += lpSum([t[i,l] for l in teams]) >= 3


text:
Q: QT and OpenCV error: core.hpp not found i have installed qt 5.0.2 with opencv 2.4.5 with windows 7 32-bit following this tutorial but when i finished i tested it using the example mentioned in the previous link but i had this error
error: opencv2/core/core.hpp: No such file or directory

Update

top 5 errors:
C:\opencv\opencv_bin\install\include\opencv2\core\core.hpp:4341: In file included from ..\..\..\..\..\..\opencv\opencv_bin\install\include/opencv2/core/core.hpp:4341:0,
C:\Qt\Qt5.0.2\Tools\QtCreator\bin\test2\main.cpp:2: from ..\test2\main.cpp:2:
C:\opencv\opencv_bin\install\include\opencv2\core\operations.hpp:928: error: prototype for 'cv::Vec<_Tp, n> cv::Matx<_Tp, m, n>::solve(const cv::Vec<_Tp, m>&, int) const' does not match any in class 'cv::Matx<_Tp, m, n>'
C:\Qt\Qt5.0.2\Tools\QtCreator\bin\test2\main.cpp:2: In file included from ..\test2\main.cpp:2:0:
C:\opencv\opencv_bin\install\include\opencv2\core\core.hpp:495: error: candidates are: cv::Matx<_Tp, n, 1> cv::Matx<_Tp, m, n>::solve(const cv::Matx<_Tp, m, 1>&, int) const

Could anybody help me please to determine what's the matter and how to
 solve it.

A: In the tutorial, this guy actually tells you how to do that. Extract:
QT       += core
QT       -= gui
TARGET = myFirstOpenCVProject
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
INCLUDEPATH += C:\\OpenCV-2.3.1\\install\\include # <--- this
LIBS += -LC:\\OpenCV-2.3.1\\install\\lib \
    -lopencv_core231.dll \
    -lopencv_highgui231.dll \
    -lopencv_imgproc231.dll \
    -lopencv_features2d231.dll \
    -lopencv_calib3d231.dll

A: the problem has been solved... it was copmatability issues between the q creator and opencv,,, i've installed QTsdK  , opencv 2.3.1 and cmake 2.8.11 follwing the same tutorial   and every think goes in the right way :)


text:
Q: What would be the best solution for having a mobile application store/retrieve/update data I'm developing a web based application built on codeigniter which will also have a mobile application(blackberry, iphone, android etc.). The web application will be connecting to a (mysql) database to store/retrieve/update data. I would like to know what would be the best solution for having a mobile application store/retrieve/update data.
Taking into consideration performance, flexibility, Security

A: Look at your device no different than if it was a browser.  The are both clients.  All devices (well at least Android and iOS) provide you with ways to make xhr requests, just like your browser does.  So you need an API on your server that your device will use to get the data.  Note that if your application does not already have an API, you will need to develop one.


text:
Q: how to get rss feeds for new products from magento on facebook? i have enabled rss feeds from backend admin panel,
in frontend copy the url "www.mydomain.com/rss//catalog/new/store_id/1/" and paste it in facebook application graffiti to get feeds.
But what i get is the only one product feed even after adding more and more products.
I have searched alot for it but still with open hands for answer.
Thanks in advance.

A: I would like you to know that having the RSS Feed is not supported but the CSV is indeed supported. In the link: https://www.facebook.com/business/a/online-sales/dynamic-product-ads?__mref=message_bubble
it shows you how to create it with a sample of the CSV File.


text:
Q: Number with more than 15 digits converts to 0 while writing to CSV file I have to prepare a string with data and commas. Then write that string to a csv file using java.util.zip.ZipEntry.
Now the problem is: it works fine for the number which are less than or equal to 15 in length.
For numeric data more than 15 digits long gets converted to 0.
So I tried by using enclosing numeric data between double quotes for converting numeric data to string to avoid that issue. But that is not working.
ZipEntry ze = new ZipEntry("my.csv");
ByteArrayOutputStream ba = new ByteArrayOutputStream();
ZipOutputStream zo = new ZipOutputStream(ba);
zo.putNextEntry(ze);
String csv = "123456789012345,12345678901234567890,\"hello\",";

zo.write(csv.getBytes());
zo.closeEntry();

can anyone suggest something on this?

A: Just a guess: you are opening the generated csv in MS Excel.
Use a text editor to check the file.
There is a bug report which says: "Last digits are changed to zeroes when you type long numbers in cells of Excel"


text:
Q: ZIO : How to compute only once? I am using ZIO: https://github.com/zio/zio
in my build.sbt:
"dev.zio" %% "zio" % "1.0.0-RC9"

No matter what I tried, my results are always being computed each time I need them:
val t = Task {
  println(s"Compute")
  12
}

    val r = unsafeRun(for {
      tt1 <- t
      tt2 <- t
    } yield {
      tt1 + tt2
    })

    println(r)

For this example, the log look like :
Compute
Compute
24

I tried with Promise:

    val p = for {
      p <- Promise.make[Nothing, Int]
      _ <- p.succeed {
        println(s"Compute - P")
        48
      }
      r <- p.await
    } yield {
      r
    }

    val r = unsafeRun(for {
      tt1 <- p
      tt2 <- p
    } yield {
      tt1 + tt2
    })

And I get the same issue:
Compute - P
Compute - P
96

I tried with
    val p = for {
      p <- Promise.make[Nothing, Int]
      _ <- p.succeed(48)
      r <- p.await
    } yield {
      println(s"Compute - P")
      r
    }

first and I was thinking that maybe the pipeline is executed but not the value recomputed but I does not work either.
I would like to be able to compute asynchronously my values and be able to reuse them.
I looked at How do I make a Scalaz ZIO lazy? but it does not work for me either.

A: ZIO has memoize, which should do essentially what you want.  I don't have a way to test it just now, but it should work something like:
for {
  memoized <- t.memoize
  tt1 <- memoized
  tt2 <- memoized
} yield tt1 + tt2

Note that unless the second and third lines of your real code have some branching that might result in the Task never getting called, or getting called only once, this yields the same answer and side effects as the much simpler:
t flatMap {tt => tt + tt}

A: Does computing the results have side effects? If it doesn't you can just use a regular old lazy val, perhaps lifted into ZIO.
lazy val results = computeResults()
val resultsIO = ZIO.succeedLazy(results)

If it does have side effects, you can't really cache the results because that wouldn't be referentially transparent, which is the whole point of ZIO.
What you'll probably have to do is flatMap on your compute Task and write the rest of your program which needs the result of that computation inside that call to flatMap, threading the result value as a parameter through your function calls where necessary.
val compute = Task {
  println(s"Compute")
  12
}

compute.flatMap { result =>
  // the rest of your program
}


text:
Q: no content from Wikipedia API search Good morning
I am using the following API search, which used to return title, content and link of a Wikipedia entry:
https://it.wikipedia.org/w/api.php?action=opensearch&search=alessandro%20leogrande&format=json&utf8=1
Just recently I noticed that it is always returning an empty content part ([""]):
["alessandro leogrande",["Alessandro Leogrande"],[""],["https://it.wikipedia.org/wiki/Alessandro_Leogrande"]]
Can you please give me any insight?

A: It seems there is a problem with the OpenSearch API itself:
https://lists.wikimedia.org/pipermail/mediawiki-api/2019-December/004188.html


text:
Q: В каких задачах используется явный или неявный курсоры? В каких задачах вообще нужно использовать курсоры: явный или неявный?
В книге Oracle PL/SQL Для профессионалов в 15-й главе подчеркнул такую мысль:

явные курсоры для однотипных повторяющихся запросов

Что для неявных? И что понимается под однотипными запросами?

A: Полная цитата упомянутая ТС в вопросе и комментарии:

Поэтому вместо формулировки «явный или неявный?» лучше спросить:
«инкапсулированный или открытый?» И ответ будет таким: всегда
инкапсулируйте однострочные запросы, скрывая их за интерфейсом функции
(желательно пакетной) и возвращая данные через RETURN.

Осмелюсь сокращёно перефразировать: меньше надо уделять внимания выбору между явным и неявным курсором, лучше позаботится о включении повторяюшихся запросов в пакетные функции, скрыв их тем самым от пользователя.
Практические примеры для закрепления материала изложенного в книге:

Фейерштейн С., Прибыл Б. "Oracle PL/SQL. Для профессионалов" 6-е изд. — СПб.: Питер, 2015.
Глава 15, подглава "Выбор между явным и неявным курсорами"

Эти примеры помогут понять работу с 2-мя типами курсоров: явными и неявными, в случае явных курсоров со строгой и слабой типизацией результирующего сета данных.
Тестовые данные и спецификация пакета:
create table params as
    select 'key'||level key, 'value'||level value , 'memo about this param' memo
    from dual connect by level<=3;
/
create or replace package democursor as
    type paramtype is record (key varchar2 (8), value varchar2 (16));
    type weakcurtype is ref cursor;
    type strongcurtype is ref cursor return paramtype;
    type paramstype is table of paramtype;

    function getParam (key varchar2) return paramtype;
    procedure openParams (cur out strongcurtype);
    function getParams (likevalue varchar2) return paramstype;
end;
/
create or replace package body democursor as
    function getParam (key varchar2) return paramtype is
        param paramtype;
    begin
        select key, value into param
        from params
        where key = getParam.key;
        return param;
    exception when no_data_found then null;
    end getParam;
    procedure openParams (cur out strongcurtype) is
    begin
        open cur for
            select key, value
            from params order by key;
    end openParams;
    function getParams (likevalue varchar2) return paramstype is
        cur weakcurtype;
        params paramstype;
    begin
        open cur for select key, value from params
        where value like likevalue||'%' order by key;
        fetch cur bulk collect into params;
        close cur;
        return params;
    end;
end;
/

Пример различных случаев использования курсоров и функций с ними из пакета:
var rc refcursor;
declare
    param1 democursor.paramtype;
    param2 democursor.paramtype;
    params democursor.paramstype;

    function getParam (nth int) return democursor.paramtype is
        cur democursor.strongcurtype;
        ret democursor.paramtype;
    begin
        democursor.openParams (cur);
        <<fechnth>> loop
            fetch cur into ret;
            exit fechnth when cur%rowcount = nth or cur%notfound;
        end loop;
        return ret;
    end;
begin
    param1 := democursor.getParam (key=>'key1');
    param2 := getParam (nth=>2);
    params := democursor.getParams (likevalue=>'val');

    open :rc for
        select 'got first param' what, param1.key||'='||param1.value param from dual union all
        select 'got nth=2 param' what, param2.key||'='||param2.value param from dual union all
        select 'got val% params' what, params.key||'='||params.value from table (params) params;
end;
/

Результат работы:
WHAT            PARAM
--------------- -----------------------------------------------------------------
got first param key1=value1
got nth=2 param key2=value2
got val% params key1=value1
got val% params key2=value2
got val% params key3=value3

Воспроизводимые примеры выше поместил на db<>fiddle для изменения с целью, попробовать и лучше понять отделные моменты работы с курсорами.


text:
Q: Date difference not more than 90 days I need to compare two dates (entered through textbox using calendar extender dd/MM/yyyy format) difference not exceed more than 3 months(90 days..)How will i do it in javascript?
Thanks

A: First thing that you have to do is to create a Date object from the input string. If it is like 21/11/2013, you have to do call split('/') on this string to get the day, month and year.
You can do this with the two dates and compare them.

A: function dateDiff(d1str, d2str) {
    var d1 = new Date(d1str),
        d2 = new Date(d2str);
    return (d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 // diff in days
}

dateDiff("11/11/2011", "11/12/2011"); // returns: 1


text:
Q: debug issue how i can solve C:\Program Files\Java\jdk1.8.0_151\bin\javaw.exe (Mar 4, 2020, 12:02:48 PM)
I have placed a breakpoint, but when I run the code in debug mode, it keeps skipping the breakpoints and I don't see any variables:

I'm new to this can someone help me out here, thank you.

A: You have somewhere a so-called trigger point that have to be hit first to enable the breakpoint in line 11.
Trigger points are decorated with a T and regular breakpoints are, if there are trigger points, decorated with a crossed-out T (like the breakpoint in line 11). In your case, with the trigger point not be hit the regular breakpoint will not become active and your program runs to the end without stopping at a breakpoint (terminated means finished and exit value: 0 means successfully).
To disable, delete or convert the trigger point(s):

*

*Go to the Breakpoints view

*Do one of the following with all trigger points (those decorated with a T):

*

*Uncheck them to disable them

*Select them and hit Delete to delete them

*Select them one after the other and uncheck the Trigger Point checkbox to convert them into regular breakpoints


text:
Q: No test is available in dll, Make sure that installed test discoverers & executors, platform & framework version I am trying to run a test from azureDevop pipeline and I am getting the error:
Warning: No test is available in D:\data\CHT.....\myTest.dll. Make sure that installed test discoverers & executors, platform & framework version settings are appropriate and try again
Those are the nugets I use in myTest project:

This is what I have in the output directory:

In myTest.cs file I have a test method:
    [TestMethod]
    public void ValidateLoading()
    {
        driver.Navigate().GoToUrl(urlToTest);
    }

I can run it locally in VS. Only when this checkbox is disable (in tools->options):

What am I missing?


text:
Q: How does the step algorithm work in Molek-Syntez? There are various places that discuss the bonding priority for a single atom in Molek-Syntez, which is often enough to get by for simple cases, but for optimizing complicated setups you need to be aware of the global rules: What happens when multiple Hydrogens are being added/removed in a single step, molecules are being pushed while hydrogenated, etc.
I'm looking for a total outline of the algorithm that's used to process a single step in the game, as far as that's possible to reverse-engineer by looking at the results of actions.

A: The algorithm proceeds in phases organized by the type of action.

*

*Hydrogen Removals and Shunts fire together. These go in Beam Emitter order, although this only matters when multiple emitters target the same atom and it runs out of Hydrogens.

*Hydrogen Additions fire. You would think these would get lumped in with the removals, but they definitely process after. (Observable when removals and additions target the same atom with no pre-existing Hydrogen.) There is no way these can conflict, so no observable in-phase ordering.

*Pushes, pulls and rotates fire. This is a two-step process: First, the targets are determined by seeing which molecules the emitters are hitting (and for rotates, the center of rotation). If two emitters target the same molecule, the lower number wins. Then, all affected molecules are rotated/slid simultaneously into their new positions. This means that a push and a pull can cooperate, or (in extremely precise circumstances) you can push a molecule through the teeth of another one that's turning, like a gear.

*Bond fixup: New bonds are made, old ones are broken if the current state is not stable. This is the exciting (and most complicated) part, and gets its own section below.

*Trashing and outputting: Much like the push/pull phase, targets are determined and then the result happens. If two (or more) emitters target the same molecule, the lowest one wins. This only really matters if you target the same molecule for both trashing and outputting.

*Emitter left/right movement occurs. This can't conflict with anything else, so it's technically unordered with respect to the others, but I'm arbitrarily putting it last.

Knowing the details of the above let you do some non-intuitive tricks, like adding or removing Hydrogens in the same step as the molecule gets moved. This works even when the addition splits the moved molecule in two, because movement happens before bond fixup. Sometimes this is the best way to get the bonds you want.
I haven't fully cracked the details of Bond Fixup yet. Here's what is known for sure, for simple cases:

*

*I'm fairly certain that unbonding happens before bonding. This can lead to non-local bond changes (bonds forming between two atoms when neither atom was touched this step).

*When bonding, single bonds are preferred to double bonds are preferred to triple bonds. Unbonding works in the reverse order (break triple bonds first).

*When the above is tied, bonds prefer specific atoms. Cl < F < S < O < P < N < C (Carbon is most preferred), and the opposite for unbonding. (F and P are specific to the extra puzzles.)

*For individual atoms, when dealing with the same bond order and type of atom, bonding starts clockwise from the line of the Emitter Beam, and when unbonding it goes counterclockwise. So, for example, adding a single hydrogen to Cyclohexane will always unbond the bond CCW around the ring, because if you start tracing from the atom along the line of the Emitter Beam and continue CCW, that's the first atom you'll encounter. However, this doesn't seem to generalize when multiple bonds are happening:

Changing the angles on emitters can change which bond is chosen in this case, but in other cases it will always chose the same one of the two, no matter what. Also, if all three events don't happen at the same time, the interaction becomes simpler and follows the rules above.