text:
Q: Spring-jcl is writing to wrapper.log. What is the configuration required to redirect to correct file? This is wrapper.conf. An earlier version was redirecting logs to the correct log file, there was no configuration present. Now all logs are redirected to wrapper.log
Removed most of the jar inclusions to avoid cluttering
Can I include commons-logging.properties to resolve the issue or can i define some environment variables that could work?
#********************************************************************
# Wrapper Properties
#********************************************************************
# Java Application
wrapper.java.command=java
wrapper.working.dir=..

# Java Main class.  This class must implement the WrapperListener interface
#  or guarantee that the WrapperManager class is initialized.  Helper
#  classes are provided to do this for you.  See the Integration section
#  of the documentation for details.
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
set.default.REPO_DIR=lib
set.APP_BASE=.

# Java Classpath (include wrapper.jar)  Add class path elements as
#  needed starting from 1
wrapper.java.classpath.1=lib/wrapper.jar
wrapper.java.classpath.2=%CLASSPATH_PREFIX%
wrapper.java.classpath.3=%REPO_DIR%/com/rsa/netwitness/sms-server/18.9.1/sms-server-18.9.1.jar
wrapper.java.classpath.4=%REPO_DIR%/com/rsa/smc/esm-datastore/18.9.1/esm-datastore-18.9.1.jar
wrapper.java.classpath.5=%REPO_DIR%/com/rsa/netwitness/sms-common/18.9.1/sms-common-18.9.1.jar
wrapper.java.classpath.6=%REPO_DIR%/org/springframework/spring-context-support/5.3.18/spring-context-support-5.3.18.jar
wrapper.java.classpath.7=%REPO_DIR%/org/springframework/data/spring-data-mongodb/1.10.23.RELEASE/spring-data-mongodb-1.10.23.RELEASE.jar
wrapper.java.classpath.8=%REPO_DIR%/org/springframework/spring-tx/5.3.18/spring-tx-5.3.18.jar
wrapper.java.classpath.9=%REPO_DIR%/org/springframework/data/spring-data-commons/1.13.23.RELEASE/spring-data-commons-1.13.23.RELEASE.jar
wrapper.java.classpath.10=%REPO_DIR%/org/mongodb/mongo-java-driver/2.14.3/mongo-java-driver-2.14.3.jar
wrapper.java.classpath.11=%REPO_DIR%/com/googlecode/json-simple/json-simple/1.1.1/json-simple-1.1.1.jar
wrapper.java.classpath.12=%REPO_DIR%/commons-io/commons-io/2.8.0/commons-io-2.8.0.jar
wrapper.java.classpath.13=%REPO_DIR%/com/fasterxml/jackson/core/jackson-databind/2.11.1/jackson-databind-2.11.1.jar
wrapper.java.classpath.14=%REPO_DIR%/com/fasterxml/jackson/core/jackson-annotations/2.11.1/jackson-annotations-2.11.1.jar
wrapper.java.classpath.15=%REPO_DIR%/com/googlecode/java-ipv6/java-ipv6/0.17/java-ipv6-0.17.jar
wrapper.java.classpath.16=%REPO_DIR%/org/apache/commons/commons-math3/3.6.1/commons-math3-3.6.1.jar
wrapper.java.classpath.17=%REPO_DIR%/javax/el/javax.el-api/3.0.1-b06/javax.el-api-3.0.1-b06.jar
wrapper.java.classpath.18=%REPO_DIR%/org/springframework/spring-jcl/5.3.18/spring-jcl-5.3.18.jar
wrapper.java.classpath.19=%REPO_DIR%/com/rsa/smc/esm-core/18.9.1/esm-core-18.9.1.jar
wrapper.java.classpath.20=%REPO_DIR%/com/rsa/netwitness/sms-generated/18.9.1/sms-generated-18.9.1.jar
wrapper.java.classpath.21=%REPO_DIR%/jakarta/xml/bind/jakarta.xml.bind-api/2.3.3/jakarta.xml.bind-api-2.3.3.jar
wrapper.java.classpath.22=%REPO_DIR%/org/glassfish/jaxb/jaxb-runtime/2.3.3/jaxb-runtime-2.3.3.jar
wrapper.java.classpath.23=%REPO_DIR%/org/glassfish/jaxb/txw2/2.3.3/txw2-2.3.3.jar
wrapper.java.classpath.24=%REPO_DIR%/com/sun/istack/istack-commons-runtime/3.0.11/istack-commons-runtime-3.0.11.jar
wrapper.java.classpath.25=%REPO_DIR%/com/sun/activation/jakarta.activation/1.2.2/jakarta.activation-1.2.2.jar
wrapper.java.classpath.26=%REPO_DIR%/jakarta/activation/jakarta.activation-api/1.2.2/jakarta.activation-api-1.2.2.jar
wrapper.java.classpath.27=%REPO_DIR%/com/rsa/netwitness/sms-rule-engine/18.9.1/sms-rule-engine-18.9.1.jar
wrapper.java.classpath.28=%REPO_DIR%/com/rsa/asoc/launch/launch-api/7.8.0/launch-api-7.8.0.jar
wrapper.java.classpath.29=%REPO_DIR%/org/glassfish/jakarta.el/3.0.3/jakarta.el-3.0.3.jar
wrapper.java.classpath.30=%REPO_DIR%/org/hibernate/validator/hibernate-validator/6.1.5.Final/hibernate-validator-6.1.5.Final.jar
wrapper.java.classpath.31=%REPO_DIR%/jakarta/validation/jakarta.validation-api/2.0.2/jakarta.validation-api-2.0.2.jar
wrapper.java.classpath.32=%REPO_DIR%/org/jboss/logging/jboss-logging/3.3.2.Final/jboss-logging-3.3.2.Final.jar
wrapper.java.classpath.33=%REPO_DIR%/com/fasterxml/classmate/1.3.4/classmate-1.3.4.jar
wrapper.java.classpath.34=%REPO_DIR%/io/dropwizard/metrics/metrics-core/4.1.12.1/metrics-core-4.1.12.1.jar
wrapper.java.classpath.35=%REPO_DIR%/org/msgpack/jackson-dataformat-msgpack/0.8.20/jackson-dataformat-msgpack-0.8.20.jar
wrapper.java.classpath.36=%REPO_DIR%/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.11.3/jackson-datatype-jsr310-2.11.3.jar
wrapper.java.classpath.37=%REPO_DIR%/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.11.3/jackson-datatype-jdk8-2.11.3.jar
wrapper.java.classpath.38=%REPO_DIR%/org/springframework/security/spring-security-jwt/1.1.1.RELEASE/spring-security-jwt-1.1.1.RELEASE.jar
wrapper.java.classpath.39=%REPO_DIR%/io/projectreactor/reactor-core/3.3.11.RELEASE/reactor-
..............
wrapper.java.classpath.284=%REPO_DIR%/org/slf4j/slf4j-api/1.7.35/slf4j-api-1.7.35.jar

# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=lib
wrapper.java.library.path.2=%EXTRA_LIBRARY_PATH%

# Java Additional Parameters
#wrapper.java.additional.1=
wrapper.java.additional.1=-Xmx16g
wrapper.java.additional.2=-XX:+UseG1GC
wrapper.java.additional.3=-Djavax.net.ssl.keyStore=/etc/pki/nw/carlos/rsa-nw-sms-server.p12
wrapper.java.additional.4=-Dclover.initstring=/tmp/clover/clover.db
wrapper.java.additional.5=-Djavax.net.ssl.keyStoreType=PKCS12
wrapper.java.additional.6=-Dclover.initstring.basedir=/tmp/clover/
wrapper.java.additional.7=-Dcom.rsa.netwitness.carlos.common.enableDynamicPropertyReader=false

# Initial Java Heap Size (in MB)
#wrapper.java.initmemory=3

# Maximum Java Heap Size (in MB)
#wrapper.java.maxmemory=64

# Application parameters.  Add parameters as needed starting from 1
wrapper.app.parameter.1=com.rsa.netwitness.sms.server.SmsCommandLine
wrapper.app.parameter.2=--home
wrapper.app.parameter.3=/opt/rsa/sms

#********************************************************************
# Wrapper Logging Properties
#********************************************************************
# Format of output for the console.  (See docs for formats)
wrapper.console.format=PM

# Log Level for console output.  (See docs for log levels)
wrapper.console.loglevel=INFO

# Log file to use for wrapper output logging.
wrapper.logfile=/opt/rsa/sms/wrapper.log

# Format of output for the log file.  (See docs for formats)
wrapper.logfile.format=LPTM

# Log Level for log file output.  (See docs for log levels)
wrapper.logfile.loglevel=INFO

# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
wrapper.logfile.maxsize=20m

# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
wrapper.logfile.maxfiles=1

# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE

#********************************************************************
# Wrapper Windows Properties
#********************************************************************
# Title to use when running as a console
wrapper.console.title=RSA NetWitness SMS :: Server

#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.

# Name of the service
wrapper.ntservice.name=sms-driver

# Display name of the service
wrapper.ntservice.displayname=RSA NetWitness SMS :: Server

# Description of the service
wrapper.ntservice.description=RSA Netwitness System Monitoring Service Application

# Service dependencies.  Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=

# Mode in which the service is installed.  AUTO_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START

# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false

wrapper.logfile.rollmode=SIZE
wrapper.ping.timeout=360
configuration.directory.in.classpath.first=%CLASSPATH_PREFIX%
wrapper.ping.interval=30
wrapper.restart.delay=60


text:
Q: Drupal 7 - Where is the Menu Description stored? For the life of me I can't seem to track down where the "Menu Description" value's stored in Drupal 7!
For example:
I added a new menu link called "Cookie" and the menu description called "Yummy". I go into the Drupal database and I can't seem to locate the string "Yummy" in
menu_custom or menu_links or menu_router infact i dumped the database and searched for the string "Yummy" and still can't locate this.
Any help will be great

A: It should be in your menu_links table under the options field.  Note that it is not the only data in that field.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluate these limits by relating them to a derivative Evaluate these limits by relating them to a derivative.
$\lim\limits_{x \to 0} \frac{\sqrt{\cos{x}}-1}{x}$

A: Hint: Put $f(t) = \sqrt{\cos t}$, note that $f(0)=1$ and $f(0+x) = f(x) = \sqrt{\cos x}$, and $$\frac{f(0+x)-f(0)}{x}=\frac{\sqrt{\cos x} - 1}{x}$$
Can you take it from here?
Note: You may recognize the form on the left side of the last line better if you write $h$ (or$\Delta x$) instead of $x$.

A: HINT: rewrite it in the form
$$\frac{(\sqrt{\cos x}-1)(\sqrt{\cos x}+1)}{x(\sqrt{\cos x}+1)(\sqrt{\cos x}+1)}$$


text:
Q: Proving the map $\Psi: \mathcal{V}_pM\to T_pM$ defined by $\Psi[\gamma] = \gamma'(0)$ is well defined and bijective. I am reading Professor Lee's Intro to Smooth Manifolds book and one of the problems asks the following. How would you approach a proof to this? Also do I need to prove it is well defined? Or is that just a byproduct? Thank you for your time and help!
Let $M$ be a smooth manifold with or without boundary and $p\in M.$ Let $\mathcal{V}_pM$ denote the set of equivalence classes of smooth curves starting at $p$ under the relation $\gamma_1 \sim \gamma_2$ if $(f\circ \gamma_1)'(0) = (f\circ \gamma_2)'(0)$ for every smooth real-valued function $f$ defined in a neighborhood of $p.$ Show that the map $\Psi: \mathcal{V}_pM\to T_pM$ defined by $\Psi[\gamma] = \gamma'(0)$ is well defined and bijective.

A: I'm proving it for $p$ in the interior, other case is similar. Pick a suitable chart, such that write $\gamma = (x_1(t), \cdots, x_n(t))$ with $\gamma(0) = O$. Then by chain rule, $(f \circ \gamma)'(0) = \sum \frac{\partial f}{\partial x_i}|_O x_i'(0)$. So just set $f(x_1, \cdots, x_n) = x_i$ for all $i$ to conclude if $\gamma_1 \sim \gamma_2$, then $\gamma_1'(0) = \gamma_2'(0)$. This show the map is well defined.
It's bijective, because for any $v \in T_pM$, just pick a straight line parametrizing it (ie, identify $T_O(\mathbb{R}^n)$ with $\mathbb{R}^n$, and define $\gamma(t) = tv$) and consider it's class, this gives an well defined inverse (check it).


text:
Q: Why change UB that will always work as intended? In the legacy code base I'm working on, I discovered the line
n = ++n % size;

that is just a bad phrasing of the intended
n = (n+1) % size;

as deduced from the surrounding code and runtime-proved. (The latter now replaces the former.)
But since this code was marked as an error by Cppckeck, and caused a warning in GCC, without ever having caused any malfunction, I didn't stop thinking here. I reduced the line to
n = ++n;

still getting the original error/warning messages:
Cppcheck 1.80:

Id: unknownEvaluationOrder
  Summary: Expression 'n=++n' depends on order of evaluation of side effects
  Message: Expression 'n=++n' depends on order of evaluation of side effects

GCC (mingw32-g++.exe, version 4.9.2, C++98):

warning: operation on 'n' may be undefined [-Wsequence-point]|

I already learned that assignment expressions in C/C++ can be heavily affected by undefined evaluation order, but in this very case I just can't imagine how.
Can the undefined evaluation order of n = ++n; really be relevant for the resulting program, especially for intended value of n? That's what I imagine what may happen.
Scenario #1
++n;
n=n;

Scenario #2
n=n;
++n;

I know that the meaning and implications of relaying on undefined behaviour in C++, is hard to understand and hard to teach.
I know that the behaviour of n=++n; is undefined by C++ standards before C++11. But it has a defined behaviour from C++11 on, and this (now standard-defined behaviour) is exactly the same I'm observing with several compilers[1] for this small demo program
#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    cout << "n before: " << n << endl;
    n=++n;
    cout << "n after: " << n << endl;
    return 0;
}

that has the output

n before: 0
n after: 1

Is it reasonable to expect that the behaviour is actually the same for all compilers regardless of being defined or not by standards? Can you (a) show one counter example or (b) give an easy to understand explanation how this code could produce wrong results?

[1] the compilers a used

*

*Borland-C++ 5.3.0 (pre-C++98)

*Borland-C++ 5.6.4 (C++98)

*C++ (vc++)

*C++ (gcc 6.3)

*C++14 (gcc 6.3)

*C++14 clang

A: The increment order is precisely defined. It is stated there that
i = ++i + 2;       // undefined behavior until C++11

Since you use a C++11 compiler, you can leave your code as is is. Nevertheless, I  think that the expressiveness of
n = (n+1) % size;

is higher. You can more easily figure out what was intended by the writer of this code.

A: According to cppreference:

If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined:

i = ++i + 2;       // undefined behavior until C++11
i = i++ + 2;       // undefined behavior until C++17
f(i = -2, i = -2); // undefined behavior until C++17
f(++i, ++i);       // undefined behavior until C++17, unspecified after C++17
i = ++i + i++;     // undefined behavior

For the case n = ++n; it would be an undefined behavior but we do not care which assignment happens first, n = or ++n.


text:
Q: Serve Docker PHP FPM content through non-docker NGINX I'm trying to run MyBB forum software with Docker to run it on my server where I already have NGINX running serving other content.
This is how my docker-compose.yml currently looks like (I've been changing and testing stuff for a while now...):
services:
  mybb:
    image: mybb/mybb:latest
    volumes:
    - ${PWD}/mybb:/var/www/html:rw
    ports:
      - "9000:9000"

  postgresql:
    environment:
      POSTGRES_DB: mybb
      POSTGRES_PASSWORD: password
      POSTGRES_USER: mybb
    image: postgres:13.2-alpine
    volumes:
    - ${PWD}/postgres/data:/var/lib/postgresql/data:rw

version: '3.7'

And this is how the NGINX config file for this specific domain looks like:
upstream mybb {
    server 172.20.0.2:9000 weight=5;
}

server {
    listen 80;
    listen [::]:80;

    root /home/lobo/mybb_docker/mybb;
    index index.html index.php;

    server_name mydomain.com www.mydomain.com;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ inc/ {
        internal;
    }

    location ~ ^/(images|cache|jscripts|uploads)/ {
        access_log off;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass mybb;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

I've been changing stuff here also... I've tried different IP addresses: 127.0.0.1:9000, 0.0.0.0:9000...
But I'm not able to get it to work. When I access the website it simply returns: File not found.
Is there something I'm clearly doing wrong? Or anything else I can try?
Thank you!!
EDIT: adding /var/log/nginx/error.log:
2021/04/09 10:04:56 [error] 19714#19714: *3705 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: xx.xx.xx.xx, server: mydomain.com, request: "GET / HTTP/1.1", upstream: "fastcgi://172.20.0.2:9000", host: "www.mydomain.com"

A: The directory structure as seen by the container may differ from what it is on the host running Nginx, making SCRIPT_FILENAME and PATH_INFO invalid.


text:
Q: HttpClient inject into Singleton Lets say we have code like this:
services.AddHttpClient();
services.AddSingleton<IMyService, MyService>();

...

public class MyService : IMyService
{
    public MyService(HttpClient httpClient)
    {
    }
}

There are questions (probably stupid, but I just want to clear some things):

*

*Will it use HttpClientFactory to create an instance of HttpClient?

*I guess it uses HttpClientFactory but will it have issues with DNS changes in that case?

It's not quite clear if HttpMessageHandlers will be managed for singleton services, and should service be scoped anyway to get all benefits of HttpClientFactory usage.

A:

*

*Will it use HttpClientFactory to create an instance of HttpClient?

Yes. A default HttpClient is registered as a transient service during HttpClientFactory registration.

*I guess it uses HttpClientFactory but will it have issues with DNS changes in that case?

Correct, it still would. As you inject it into a singleton, HttpClient here will be created only once. In order to make use of HttpClientFactory's HttpMessageHandler pooling, you'd need your HttpClients to be short-lived. So, for this you would rather need to inject IHttpClientFactory itself and call CreateClient when you need one. (Note that short-living HttpClients only apply to HttpClientFactory usage). BTW switching to a typed client will not help when injecting into a singleton, HttpClient will still end up being created only once, see https://github.com/dotnet/runtime/issues/64034.
Also, you can actually avoid HttpClientFactory entirely and still have DNS changes respected. For that you may have a static/singleton HttpClient with PooledConnectionLifetime set to some reasonable timeout (e.g. the same 2 minutes HttpClientFactory does)
services.AddSingleton(() => new HttpClient(
    new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }
));


text: Q: change keyboard sign shortcut my keyboard has randomly changes the cmnd2 shortcut from @  to changing to the second tab open. until now it was all working perfectly. the computer is quite old but is working perfectly and I do remember something similar happening to me previously and can't seem to recall how I changes it back and cannot find any answer that is quite it online. does someone have any knowlege of what should I do?


text:
Q: How to remove OS X Installer for 10.10. to get back to 10.7, the originally installed OS? I ran OS X 10.7 latest version on my MacBookPro 2011.
Then I installed on an external USB stick 10.10.3 from my running system OS X 10.7.
The installation on the stick was successful.
After testing 10.10 for some minutes I restarted the system, took of the usb-stick and wanted to restart from my internal disk the 10.7 system.
However, now there is the installer and insists on installing 10.10, what I do not want to do.
The disk utility says that my internal disk is not writable and that I cannot modify it.
Starting with an external disk with 10.7 works, but does not allow to reactivate the internal disk.
Recovery with  Cmd ⌘   R   loads 10.7 via the internet (it therefore still know that the original system is 10.7), but I cannot recover the 10.7 system, since I cannot write to the internal disk.
The internal disk is now Master Boot Record partitioned.
I do not know if it was GUID before or not: At least it worked for three years before.
I have a backup, but since this is 1TB I do not want to load it via a USB 2.0 port.
How can I reactivate my internal disk with 10.7?
If reasonable I would change to 10.8 (but not higher) if there is a utility that works with 10.8 only.
Any proposal or links to tool to remove the OS X installer and allow me to restart from my internal disk with 10.7?
The output of gpt -r show /dev/disk0:
sudo gpt -r show /dev/disk0
results in:
       start        size  index  contents
           0           1         MBR
           1           1
           2  1466246608      1  MBR part 175
  1466246610           1
  1466246611   487278557      2  MBR part 175

I have a time machine backup.

A: Something really, really bad happened to your internal 1 TB drive:
The GUID partition table was somehow replaced by a dual (and therefore additionally false) MBR partition table.
You may recover the previous GUID and your missing volume with a disk recovery tool like Disk Warrior to some extent. But since you have a backup just restore it:

*

*In case you have a Time Machine backup:

*

*Boot to Internet Recovery Mode by pressing altcmdR. The prerequisites for an Internet Recovery are listed here: Recovery/Internet Recovery.
In a few words you need the latest firmware update installed, either ethernet or WLAN (WPA/WPA2) and a router with DHCP activated for a successful internet recovery.
On a 50 Mbps-line it takes about 4 min (presenting a small animated globe) to boot into the Recovery Netboot image which is loaded from an Apple server.
(Alternatively you may boot to an external drive containing a Recovery HD or a full OS X system or a OS X thumb drive.)

*Open "Disk Utility" and partition your internal disk: GUID partition scheme (use the "Options..." button at the bottom of the main pane for this), one partition, journaled HFS+.

*Close "Disk Utility".

*Attach your Time Machine backup drive.

*Open "Restore from Time Machine Backup" and restore your main drive if you have booted from a Recovery drive.
If you've booted from a full OS X external drive just open Time Machine and restore your internal drive.

*In case you have a different back-up app:

*

*Follow the instructions of the non-Apple back-up application


text:
Q: using guidelines for generics and IDisposable In item 5 of More Effective C#, the following is presented:
public class EngineDriver<T> where T : IEngine, new()
{
  public void GetThingsDone()
  {
    T driver = new T();
    using (driver as IDisposable)
    {
      driver.DoWork();
    }
  }
}

The goal here is to properly dispose of drive, if it implements IDisposable. This makes sense, but how is this implementation different from the more succinct:
public class EngineDriver<T> where T : IEngine, new()
{
  public void GetThingsDone()
  {
    using (T driver = new T())
    {
      driver.DoWork();
    }
  }
}

Shouldn't the code above behave in exactly the same way? In fact, isn't the original code dangerous in that the lifetime of driver is beyond the using block, but driver is disposed of at the end of said block?

A: It is kinda important that you use the tools that are available to you. Compile your proposed code.  I'll wait a few minutes.
Okay, you're back.  Yes, you need to add a constraint for IDisposable so that the using statement is always capable of disposing the object.  The code from the book is a hack around that restriction, it will work even if T does not implement IDisposable.  using (null) {} is valid.

A: No, because T does not necessarily implement IDisposable (unless IEngine itself implements it) - the second will not compile in this case, whereas the first will.
Regarding the scope of driver - it will still be accessible after the using block in the second example which is not ideal, and attempting to do so would usually result in an exception. Ideally you should have IEngine implement IDisposable or add an additional constraint to EngineDriver that T implement it.

A: Your second proposal will only work if IEngine implements IDisposable or if an extra constraint (for IDisposable) is added to the type parameter on EngineDriver. The original code is flexible enough to additionaly handle IEngine implementations that also implement IDisposable.
If you're really worried about using the object after it's been disposed of, you could create another scope to encompass the variable:
public class EngineDriver<T> where T : IEngine, new() {
  public void GetThingsDone() {
    {
      T driver = new T();
      using (driver as IDisposable) {
        driver.DoWork();
      }
    }
  }
}

But for this example, this is overkill; the scope of the method is enough. It would only make sense if your method was bigger, like:
public class EngineDriver<T> where T : IEngine, new() {
  public void GetThingsDone() {
    {
      T driver = new T();
      using (driver as IDisposable) {
        driver.DoWork();
      }
    }
    // do more stuff, can't access driver here ....
  }
}

But then again, I'm just showing what's possible here, I'd prefer to refactor it so that that block is isolated from the other code.
You can also have another scoping class:
public class DisposableWrapper<T> : IDisposable {
  public T Item { get; private set; }
  public DisposableWrapper(T item) { Item = item; }
  public void Dispose() {
    using (Item as IDisposable) { }
    Item = default(T);
  }
}

public static class DisposableWrapperExtensions {
  public static DisposableWrapper<T> AsDisposable<T>(this T item) {
    return new DisposableWrapper<T>(item);
  }
}

public class EngineDriver<T> where T : IEngine, new() {
  public void GetThingsDone() {
    using (var driver = new T().AsDisposable()) {
      driver.Item.DoWork();
    }
  }
}

It might make sense if you use many interface references that could implement IDisposable.


text:
Q: Adding a number of rows to another worksheet based on cell value on a certain column I am new to VBA, but had a situation where doing this manually would be extremely tedious, so I got to learning.
I needed a script that can find certain text values on a column and then copy a certain number of rows with all the row values into another worksheet. Full row values on the first row, and first 5 rows on the next rows. The text value that is searched is for example "DOL-1" or "VFD".
After lots of research and trial and error, I have managed to stitch together this script that does the job, but it is obviously badly written and not optimized. I have tried searching for similar questions and tried their answers, but I couldn't get anything to do what this script does.
I was wondering if there are some better and/or faster methods to achieve the same thing as this script does?
Sub Add_Rows()

Dim wbC As Workbook
Dim wbP As Workbook
Dim wsC As Worksheet
Dim wsP As Worksheet
Dim cell As Range
Dim r As Integer
Dim dataTable As Range

r = 8
'rownumber

Set wbP = Application.Workbooks.Open("C:\Projects\Feed_list.xlsx")
Set wsP = wbP.Worksheets("Feed_list")
' set paste destination (these variables aren't really even used because I couldn't get them to work)

Set wbC = Application.Workbooks.Open("C:\Projects\Generated_list.xlsm")
Set wsC = wbC.Worksheets("GEN")
' set copy location (these variables aren't really even used because I couldn't get them to work)

Windows("Generated_list.xlsm").Activate

Application.ScreenUpdating = False

For Each cell In Range("AB2:AB5000")

    If cell.Value = "DOL-1" Then

        Debug.Print cell.Address
        Windows("Generated_list.xlsm").Activate
        Range(cell, cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select

        'Debug.Print r

        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1
        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1
        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1
        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1

        Windows("Generated_list.xlsm").Activate
        Range(cell.Offset(, -21), cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

        Windows("Generated_list.xlsm").Activate
        Range(cell.Offset(, -21), cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select
        Selection.Offset(-1).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

        Windows("Generated_list.xlsm").Activate
        Range(cell.Offset(, -21), cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select
        'Rows(r).Select
        Selection.Offset(-1).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    End If

    If cell.Value = "VFD" Then

        Debug.Print cell.Address
        Windows("Generated_list.xlsm").Activate
        Range(cell, cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select

        'Debug.Print r

        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1
        Rows(r).Select
        Selection.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        r = r + 1

        Windows("Generated_list.xlsm").Activate
        Range(cell.Offset(, -21), cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

        Windows("Generated_list.xlsm").Activate
        Range(cell.Offset(, -21), cell.Offset(, -25)).Copy
        Windows("Feed_list.xlsx").Activate
        Sheets("Feed_list").Select
        Selection.Offset(-1).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    End If

'these if functions are repeated about 20 times with different text values and number of rows copied

Next

Application.ScreenUpdating = True
Windows("Feed_list.xlsx").Activate
Sheets("Feed_list").Select

End Sub

I made small example pictures. The Generated_list looks like this. (Notice column AB)
The Feed_list looks like this at first.
And after running the script it should look like this.

A: Sub Main()
    Call Add_Rows(8)
End Sub

Sub Add_Rows(whereToAdd As Long)
    Dim wb_Feed As Workbook, wb_Gen As Workbook
    Dim ws_Feed As Worksheet, ws_Gen As Worksheet
    Dim lastRow As Long, lastCol As Long, i As Long, idxType As Long

    Set wb_Feed = Workbooks.Open("C:\Projects\Feed_list.xlsx")
    Set wb_Gen = Workbooks.Open("C:\Projects\Generated_list.xlsm")

    Set ws_Feed = wb_Feed.Worksheets("Feed_List")
    Set ws_Gen = wb_Gen.Worksheets("Generated_List")

    ' Find the last row and last column of the data in Generated List
    ' Assume that the first column does not contain any blank data in middle
    lastRow = ws_Gen.Cells(ws_Gen.Rows.Count, "A").End(xlUp).Row
    lastCol = ws_Gen.Cells(1, ws_Gen.Columns.Count).End(xlToLeft).Column    ' First row is header

    ' Column AB is the last column
    idxType = lastCol

    With ws_Gen
        For i = 2 To lastRow
            If .Cells(i, idxType).Value = "VFD" Then
                ' Insert a row to Feed List
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert

                ' Copy entire row
                .Range(.Cells(i, 1), .Cells(i, lastCol)).Copy
                ' Paste
                ws_Feed.Range("A" & whereToAdd).PasteSpecial xlPasteAll
                Application.CutCopyMode = False

                ' Since VFD, insert extra 1 line according to your screenshot
                whereToAdd = whereToAdd + 1
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert

                ' Copy first 5 columns
                .Range(.Cells(i, 1), .Cells(i, 5)).Copy
                ' Paste
                ws_Feed.Range("A" & whereToAdd).PasteSpecial xlPasteAll
                Application.CutCopyMode = False

                ' Update where to add next
                whereToAdd = whereToAdd + 1

            ElseIf .Cells(i, idxType).Value = "DOL-1" Then
                ' Insert a row to Feed List
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert

                ' Copy entire row
                .Range(.Cells(i, 1), .Cells(i, lastCol)).Copy
                ' Paste
                ws_Feed.Range("A" & whereToAdd).PasteSpecial xlPasteAll
                Application.CutCopyMode = False

                ' Since DOL-1 insert extra 3 lines according to your screenshot
                whereToAdd = whereToAdd + 1
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert
                ws_Feed.Range("A" & whereToAdd).EntireRow.Insert

                ' Copy first 5 columns
                .Range(.Cells(i, 1), .Cells(i, 5)).Copy
                ws_Feed.Range("A" & whereToAdd).PasteSpecial xlPasteAll
                ws_Feed.Range("A" & whereToAdd + 1).PasteSpecial xlPasteAll
                ws_Feed.Range("A" & whereToAdd + 2).PasteSpecial xlPasteAll
                Application.CutCopyMode = False

                ' Update where to add next
                whereToAdd = whereToAdd + 3
            End If
        Next i
    End With

    ' You should close the workbook after you finish your job
End Sub


text:
Q: MySQL Docker Image on Apple Silicon stuck in Entrypoint Script I'm trying to get the official mysql docker image to run on apple silicon.
It does compose and boot up, but it only has 1 log entry and does not do anything else afterwards:
2021-08-04 14:39:12+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.35-1debian10 started.

My docker-compose file looks like this:
  database:
    platform: linux/amd64 // I also tried linux/x86_64
    image: mysql:5.7.35
    ports:
        - 3306:3306
    volumes:
        - ./mysql/create_dbs.sql:/docker-entrypoint-initdb.d/create_dbs.sql
    environment:
      - MYSQL_ROOT_PASSWORD=
      - MYSQL_DATABASE=cars
      - MYSQL_USER=cars
      - MYSQL_PASSWORD=cars
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes

Is there something else that needs to be done in order to get it working?


text:
Q: Java write test for inputStream with javax.ws.rs.client I'm having a GET api using java.ws.rs like this:
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getMyFile() throws AbsoluteException {
    StreamingOutput outputStream;
    Client client = ClientBuilder.newClient();
    try {
        final InputStream responseStream = client.target(myFileUrl).request().get(InputStream.class);
        outputStream = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException {
                int length;
                byte[] buffer = new byte[downloadBufferSize];
                while ((length = responseStream.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
                out.flush();
                responseStream.close();
            }
        };
    } catch (Exception ex) {

    }
    return Response
            .ok(outputStream, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename = " + myFile)
            .build();
}

I don't know how to write unitTest for it, using Mockito or any others.
My Test method as below but it doesn't work:
@Test
public void getMyFile_Success() throws IOException {
    final Client mockClient = Mockito.mock(Client.class);
    final File initialFile = new File("src/test/resources/TestFile.txt");
    final InputStream targetStream =
            new DataInputStream(new FileInputStream(initialFile));
    Mockito.when(mockClient.target("myUrl")
            .request().get(InputStream.class))
            .thenReturn(targetStream);
    Invocation.Builder request = target(CONTEXT_ROOT).request();
    Response response = request.get(Response.class);
    assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
}

A: I success with powermock that able to mock the constructor as well as static method.
Below is my code:
    Client mockClient = Mockito.mock(Client.class);
    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(ClientBuilder.class);
        PowerMockito.when(ClientBuilder.newClient()).thenReturn(this.mockClient);
    }

    public void getMyFile_Success() throws Exception {
        Invocation.Builder myBuilder = Mockito.mock(Invocation.Builder.class);
        WebTarget webTarget = Mockito.mock(WebTarget.class);
        Mockito.when(mockClient.target(myUrl)).thenReturn(webTarget);
        Mockito.when(webTarget.request()).thenReturn(myBuilder);
        final File initialFile = new File("src/test/resources/TestFile.txt");
        InputStream targetStream =
                new DataInputStream(new FileInputStream(initialFile));
        Mockito.when(myBuilder
                .get(InputStream.class))
                .thenReturn(targetStream);
        Invocation.Builder request = target(CONTEXT_ROOT).request();
        Response response = request.get(Response.class);
        assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
    }


text:
Q: advanced search functionality - query builder for the end-user I'd like to implement an "adavanced search" function into my website. It is a database application and therefore uses a mySQL database.
I was looking for a tool called query builder/ composer/ generator/ constructor ...
The user should be able to narrow down his/her search. I've done an internet search on my own for such tools and stumbled across many, but most of them are more like tools for programmers to support them writing SQL queries.
I stumbled across these two tools that do what I am looking for:

*

*EasyQuery/ EasyQuery.js (e.g. http://advangle.com/)

*RedQueryBuilder (http://redquerybuilder.appspot.com/)

Do you know more of them? I'd like to use PHP as programming language (Javascript in addition is okay). Open source and free is preferred.
Furthermore my data base structure (I only want to search one specific table) does not change dynamically over time.
Maybe you can also guide me to different keywords I have to look for to find other tools like those mentioned above.
Thanks,
Matthias
(PS: Please don't discuss security issues like SQL injections and so on.)

A: Yes, I dont know about redQuery Builder but know about EasyQuery. EasyQuery as name suggest is so easy to integrate. Its free also. It is available in .NET version , javascript version and PHP version. You just need to do some changes for database in its controller.


text:
Q: How to make a scrolling starfield I want to write a simple scrolling right to left starfield. I have printed out the stars randomly. Now, how do I target each star and randomly give it a speed (say 1-10) and begin moving it? I also need to put each star back on the right edge after it reaches the left edge.
Following is my code written so far:
<!DOCTYPE html>

Stars

<canvas id="can" width="400" height="400"style="border:2px solid #000100" ></canvas>

A: Here's a quick demo on Codepen. After saving the stars in an array, I'm using requestAnimationFrame to run the drawing code and update the position on every frame.
function stars() {
  canvas = document.getElementById("can");
  console.log(canvas);
  if (canvas.getContext) {
    ctx = canvas.getContext("2d");
    ctx.fillStyle = "black";
    ctx.rect(0, 0, 400, 400);
    ctx.fill();
    starfield();
  }
}
// Create random stars with random velocity.
var starList = []
function starfield() {
  for (i = 0; i < 20; i++) {
    var star = {
      x: Math.floor(Math.random() * 399),
      y: Math.floor(Math.random() * 399),
      vx: Math.ceil(Math.random() * 10)
    };
    starList.push(star);
  }
}

function run() {
  // Register for the next frame
  window.requestAnimationFrame(run);

  // Reset the canvas
  ctx.fillStyle = "black";
  ctx.rect(0, 0, 400, 400);
  ctx.fill();

  // Update position and draw each star.
  var star;
  for(var i=0, j=starList.length; i<j; i++) {
    star = starList[i];
    star.x = (star.x - star.vx + 400) % 400;
    ctx.fillStyle = "white";
    ctx.beginPath();
    ctx.arc(star.x, star.y, 3, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
  }
}

stars();
run();

A: Put your x,y coordinates in an array, and then make a function that draws the array.
var stars = [
  {x:110, y:80},
  {x:120, y:20},
  {x:130, y:60},
  {x:140, y:40}
]

Then make a function to alter the x,y coordinates (for example increment y=y+1) each time before using the draw function.
Bonus:
This array solution allows you to have each star move at its own speed, you could store a delta (say 1 upto 3) in that array, and do y=y+delta instead. This looks 3D.
You could even go further and have a seperate x and y delta, and have stars fly out from the middle, which is even more 3D!
Or even simpler/faster could be to have the render function accept an x,y offset. It could then even wrap around, so that what falls off the screen on one side comes back on the other. It looks like you are rotating in space.

A: I simple way to imitate star movement towards a point(like a center) is simply divide both X and Y by Z coordinate.

nx = x / z
ny = y / z

And simply decrease z value as you iterate. As z is big, your points will be around a point and as z decreases the result will be bigger and bigger which imitates "moving" of a stars.

A: Just providing a solution which uses jQuery because using it you can get the output with lesser lines of code compared to complete canvas solution.It uses two canvas divs to get the desired output:
Check this fiddle
Little updated code from the code posted in the question

Stars

    <canvas id="can1" width="400" height="400"style="border:2px solid #000100" ></canvas>
    <canvas id="can2" width="400" height="400"style="border:2px solid #000100" ></canvas>

jQuery
function playStars()
{
    $('#starBlocks').animate({
        scrollLeft : 400
    },10000,'linear',function(){
        $('#starBlocks').scrollLeft(0);
        playStars();
    });
}
playStars();

CSS
#starBlocks{
    white-space:nowrap;
    font-size:0px;
    width:400px;
    overflow:hidden;
}


text:
Q: javascript - Handling redirect from http response I am trying to build a html page that when I enter it, it will redirect me to another page, depending on an attribute in the session.
If there is an attribute named "username" in the session, it will not redirect me, and otherwise it will.
In order to do so, I wrote a javascript function that calles a java servlet that checks whether or not the attribute exists.
<script type="text/javascript">
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            var data = req.responseText;
        }
        document.write(req.readyState);
    }
    req.open('POST','sessionCheck',true);
    req.send(null);
</script>

The code in the servlet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession hs = request.getSession();
    String username = (String) hs.getAttribute("username");
    if (username == null)
            response.sendRedirect("/login.html");

}

I know that the resonse did send the redirect but the webpage was not redirected.
*Note: I am using Eclipse Java EE for Web Developers.
Thanks!

A: Javascript AJAX requests follow redirects. It is likely that your javascript code ended up requesting the page that you wished to redirect the browser to.
Try returning the page to redirect to as your response and then getting the browser to navigate to that page.
You can see that the XMLHttpRequest standard states that redirects will be followed:

HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.


text:
Q: What is the structural behaviour of SSIS in it's Pre-execute phase of package execution ? Why the heavy packages hangs in Pre-Execute phase? The poor production database schema directs me to do multiple left joins, Left join with range condition in on clause and character column joins.
Even though my packages is free from errors, it is hanging in Pre-execute phase.
I read many articles online which tells about how to prevent this. such as Delay validation, External metadata , ... etc.
So please help me to know what is the work of data flow,control flow and sql server engine in Pre-execute phase ?

A: It's always a good idea to enable logging in your SSIS packages.  Without logging, it can be hard to determine exactly what SSIS did, especially if your packages are executed overnight by a task scheduler!
To enable; right click, on the control flow, and select logging... from the menu.  A dialog will open.  You can use this screen to configure where the data is logged (Windows Event Log, SQL Server, Text File, etc) and what is logged.
I would recommend you log everything.  The output can be quite verbose.  I'm afraid reading the SSIS logs is an acquired skill.  There is a lot of detail, which you need, but that can make it hard to find the exact row(s) you are interested in.  There is no shortcut here, you will need to roll your sleeves up and get stuck in.
Packages that contain a lot of connections can take a while to get through pre-execution.  I've noticed packages with lots of connections to the file system are especially slow.
EDIT
I've just noticed I didn't actually answer the OPs question.  So here goes...
Although SSIS appears to be frozen/hung it probably isn't.  Log everything and review to fix.  You can view the log in-flight, which helps.


text:
Q: Mule ESB Bean property 'enableNotifications' is not writable I am working with Mule ESB 3.8.2 and I am receiving this error where I am compliling outside of Anypoint Studio.
Bean property 'enableNotifications' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Someone has a suggest what could be?

A: After some hours working on this issue I found the solution.
The file pom.xml we must have on plugin
<inclusion>
                        <groupId>org.mule.modules</groupId>
                        <artifactId>mule-module-apikit</artifactId>
                    </inclusion>

and the dependencies must be the version of mule that we're working on it.
<dependency>
        <groupId>org.mule.modules</groupId>
        <artifactId>mule-module-apikit</artifactId>`enter code here`
        <version>${mule.version}</version>
    </dependency>

I hope this could be helpfull for someone.


text:
Q: Node-Red Dashboard - Show Image from Dropbox I'm having a very annoying problem with my Node-Red running on IBM Cloud. I'm trying to show an image from Dropbox on my Node-Red dashboard. However, the image is not loading at all. I see that the image gets downloaded and can see it on debug node. However, I couldn't find any way to show it on dashboard as a widget.
My flow:
[{"id":"a3e43112.21c75","type":"dropbox","z":"8943788e.15f4e8","dropbox":"","filename":"home/pi/Pictures/recog/top_recog_temp.jpeg","name":"","x":350,"y":3340,"wires":[["ffc2533f.771cc"]]},{"id":"213a2eb6.80e722","type":"inject","z":"8943788e.15f4e8","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":100,"y":3340,"wires":[["a3e43112.21c75"]]},{"id":"e27103b.f8bec","type":"debug","z":"8943788e.15f4e8","name":"","active":true,"console":"false","complete":"true","x":1050,"y":3340,"wires":[]},{"id":"ffc2533f.771cc","type":"base64","z":"8943788e.15f4e8","name":"","action":"","property":"payload","x":620,"y":3340,"wires":[["1b05eeaf.0c9051"]]},{"id":"1b05eeaf.0c9051","type":"template","z":"8943788e.15f4e8","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"","output":"str","x":770,"y":3340,"wires":[["689d541d.99553c"]]},{"id":"689d541d.99553c","type":"ui_template","z":"8943788e.15f4e8","group":"a88a98c0.9666b8","name":"","order":0,"width":0,"height":0,"format":"

","storeOutMessages":true,"fwdInMessages":true,"templateScope":"local","x":900,"y":3340,"wires":[["e27103b.f8bec"]]},{"id":"a88a98c0.9666b8","type":"ui_group","z":"","name":"Image","tab":"a831db53.d7b128","order":5,"disp":true,"width":"6"},{"id":"a831db53.d7b128","type":"ui_tab","z":"","name":"3D Moving Device","icon":"dashboard"}]

I couldn't find any working solution to this. Your help would be very appreciated!

A: It seems the only solution is embedding the image into a div. To do this, get a share link for the image and change the last part of the URL to raw=1. Small detail to keep in mind! :)


text:
Q: Import CSV file in Mysql using PHP but only 214 rows out of 236 rows are imported I have to import a CSV file of 236 rows. But only 144/213 rows are imported.
My server only support mysql command. it doesn't support mysqli.
enter code here

fgetcsv($file);
fgetcsv($file);
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT into branchiss2 (date,bank_id,branch_id,coa_id,coa_des,amount,is_conv,off_ind,bl1,bl2,fig_ind,data_cat,field_des,bl3,bl4,bl5,bl6,bl7,bl8,bl9)
values ('".mysql_real_escape_string($getData[0])."','".mysql_real_escape_string($getData[1])."','".mysql_real_escape_string($getData[2])."','".mysql_real_escape_string($getData[3])."','".mysql_real_escape_string($getData[4])."','".mysql_real_escape_string($getData[5])."','".mysql_real_escape_string($getData[6])."','".mysql_real_escape_string($getData[7])."','".mysql_real_escape_string($getData[8])."','".mysql_real_escape_string($getData[9])."','".mysql_real_escape_string($getData[10])."','".mysql_real_escape_string($getData[11])."','".mysql_real_escape_string($getData[12])."','".mysql_real_escape_string($getData[13])."','".mysql_real_escape_string($getData[14])."','".mysql_real_escape_string($getData[15])."','".mysql_real_escape_string($getData[16])."','".mysql_real_escape_string($getData[17])."','".mysql_real_escape_string($getData[18])."','".mysql_real_escape_string($getData[19])."')";

$result = mysql_query($sql);
     }
fclose($file);

     }

A: It may be stopped because of memory issue please add this 2 line beginning of code hope it will help you or use phpexcel library.
ini_set("memory_limit","512M");
ini_set('max_execution_time', 0);

A: Please try this :
MYSQL LOAD DATA INFILE statement for reads rows from a text file into a table at a very high speed
for example :-
$import_query = <<<eof
    LOAD DATA INFILE '$fileName'
     INTO TABLE tableName
     FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
     LINES TERMINATED BY '\n'
    (column1,column2,column3)
     SET column4 = CURRENT_TIMESTAMP;
eof;

$db->query($import_query);

A: You can modified your php.ini file set max_execution_time to a time you think is apropiated.


text:
Q: MySQL Duplicate Entry for non Unique column update in WordPress In WordPress, I want to update the quantity by +1 if the record already exists in the cart by (query in the code).
Three columns are unique in the table. While updating qty column it is giving Duplicate Entry error in this code. However, If I use the direct query from console it is updating qty value without error.
Also this method I am calling in AjAX. That is returning undefined (probably in ajax error).
So how can I get this code work with Ajax, if no record than insert else just update the qty value by +1

$this->gs_db is the database class instance and $this->gs_db->db is $wpdb

Table
CREATE TABLE IF NOT EXISTS wp_gs_pg_cart (
id            BIGINT(20) AUTO_INCREMENT UNIQUE NOT NULL,
product_group BIGINT(20)                       NOT NULL,
qty           INT(11)                          NOT NULL,
group_id      BIGINT(20)                       NOT NULL,
group_admin   BIGINT(20)                       NOT NULL,
group_user    BIGINT(20)                       NOT NULL,
added_at      DATETIME DEFAULT NOW()           NOT NULL,
PRIMARY KEY (id),
INDEX pg_cart_index (ID, product_group, group_id, group_admin, group_user),
UNIQUE pg_cart_unique (product_group, group_id, group_user)
);

Class Method
/**
 * Add product group into the cart
 *
 * @param int      $group_id      group id
 * @param int      $product_group product group id
 * @param int|bool $group_user    group user / logged in id
 *
 * @return int inserted row id if new else update row id
 */
public function add_pg_to_cart($group_id, $product_group, $group_user = FALSE)
{

    $this->group_id      = $group_id;
    $this->qty           = 1;
    $this->product_group = $product_group;
    $this->group_admin   = $this->group_id;
    $this->group_user    = ($group_user) ? absint($group_user) : absint(get_current_user_id());

    // check if record is already exists
    $query = "SELECT * FROM wp_gs_pg_cart WHERE product_group = '%d' AND group_id = '%d' AND group_user = '%d'";

    $prepare = $this->gs_db->db->prepare($query, $this->product_group, $this->group_id, $this->group_user);
    $result  = $this->gs_db->db->get_row($prepare);

    if ($this->gs_db->db->num_rows > 0) {
        $this->qty += $result->qty;

        $this->gs_db->db->update($this->gs_db->get_pg_cart_table(), ['qty' => $this->qty], ['id' => $result->id], '%d');

        $this->id = $result->id;
    } else {

        // setup data to insert
        $this->data = [
            'product_group' => $this->product_group,
            'qty'           => $this->qty,
            'group_id'      => $this->group_id,
            'group_admin'   => $this->group_admin,
            'group_user'    => $this->group_user,
        ];

        // setup data format
        $this->format = [
            '%d',
            '%d',
            '%d',
            '%d',
            '%d',
        ];

        // insert record
        $this->gs_db->db->insert($this->gs_db->get_pg_cart_table(), $this->data, $this->format);

        // get the id for inserted record
        $this->id = $this->gs_db->db->insert_id;

    }

    return $this->id;

}

Ajax Callback Function
function gs_pg_add_to_cart_ajax()
{

    // Check if user is logged in
    if ( ! is_user_logged_in()) {
        // throw error if user is not logged in
        wp_send_json_error(__('Please login to order', 'group-shop'));

        // we use this manually as want to print error
        wp_die();
    }

    // check and validate nonce
    if ( ! check_ajax_referer('gs_nonce', 'nonce', FALSE)) {

        // throw error if validation fails
        wp_send_json_error(__('Do not be nasty with validation', 'group-shop'));
    }

    $group_id      = 0;
    $product_group = 0;
    $cart_id       = 0;

    // validate product_group
    if ( ! isset($_POST[ 'product_group' ]) || empty($_POST[ 'product_group' ]) || $_POST[ 'product_group' ] <= 0) {
        // throw error if validation fails
        wp_send_json_error(__('Product Group is not defined', 'group-shop'));
    } else {
        $product_group = absint($_POST[ 'product_group' ]);
    }

    // validate product_group
    if ( ! isset($_POST[ 'group_id' ]) || empty($_POST[ 'group_id' ]) || $_POST[ 'group_id' ] <= 0) {
        // throw error if validation fails
        wp_send_json_error(__('Group is not defined', 'group-shop'));
    } else {
        $group_id = absint($_POST[ 'group_id' ]);
    }

    // initialize cart object
    $cart = new Group_Shop_Cart();
    // insert record
    $cart_id = $cart->add_pg_to_cart($group_id, $product_group);

    // if record inserted
    if ($cart_id > 0) {

        // show success message once record inserted
        wp_send_json_success(__('Product is added to cart', 'group-shop'));

    } else {

        // throw error if fails to insert record
        wp_send_json_error(__('Something went wrong', 'group-shop'));

    }

    // stop further execution once all process done
    wp_die();

}

Javascript
(function ($) {

    $(function () {

        let response_alert = $('#response');
        response_alert.hide();

        $('form.gsGpAddToCart').on('submit', function (e) {
            e.preventDefault();

            let formData = $(this).serialize();

            $.ajax({

                method: 'POST',
                dataType: 'json',
                url: ajax_vars.ajax_url,
                data: formData + "&action=gs_pg_add_to_cart&nonce=" + ajax_vars.nonce,
                success: function (response) {

                    console.log(response);

                    let response_alert = $('#response');

                    if (response.success === true) {
                        response_alert.fadeIn().prepend(alerts('success', response.data));
                    }

                    if (response.success === false) {
                        response_alert.fadeIn().prepend(alerts('error', response.data));
                    }

                },
                error: function (response) {

                    let error_message = (response.data === undefined) ? 'Something went wrong!' : response.data;
                    response_alert.fadeIn().prepend(alerts('error', error_message));
                    gs_alert_stats();
                },
                complete: function () {
                }
            });

            return false;
        });

        // control dynamically created error with JS - close/hide
        function gs_alert_stats() {
            let gs_alert = $('.gs-message');
            $('.gs-close').on('click', function () {
                alerts('Clicked');
                $(this).parent(gs_alert).fadeOut();
            });
        }

    });

})(jQuery);

Javascript is returning this error response Something went wrong! which is in error: function (response)

A: You could simplify the whole logic by using MySQL INSERT ... ON DUPLICATE KEY syntax.
From the documentation:

If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs.

You already have the proper UNIQUE constraint in place, so you would just need to adapt the code of your class method to use the following query at once:
INSERT INTO wp_gs_pg_cart(product_group, group_id, group_admin, group_user, qty)
VALUES(%d, %d, %d, %d, 1)
ON DUPLICATE KEY UPDATE qty = qty + 1


text:
Q: create radio buttons automatically from a list I am writing a python web app for google app engine using jinja2 though my problem relates to HTML/javascript (jquery is good).
I have a menu guided by radio buttons.  I have two columns that I want to permanently be there and I want the next three to be generated depending on what the user selects from the first two.
I understand somewhat how to generate the radio buttons automatically with JQuery (though any suggested resources would be great but I can probably figure it out) but my main question revolves around the fact that my final radio button has around 100 possibilities depending on the previous ones that are selected (only 3-5 will be displayed at a time mind you).
So my main question.  Where should I store the names for the radio buttons and URLs that they will lead to? and how do I put these into the radio buttons as they are created?
Here is an image of what I want the final product to look like:

Thanks so much this is bending my mind for some reason!

A: Where are your 100 options stored now in javascript (front end)?
If all your options are stored on the front end you can implement your logic (which buttons to display based on the previous choices) on the front end. This would probably include an array of radio buttons.  As you can see this could start getting unweildy to maintaint.  Every time you want to update yoru logic you would have to manually update your js file.
If all the choices are stored in python/backend you will need to make an AJAX request from the front end to the backend.   This can be done easily using jquery framework.
This request would include the choices the user makes.  and it would return the correct radio buttons to display.


text:
Q: How to set Dynamic IssuerSigningKey and TokenDecryptionKey in AddJwtBearer options in ConfigureServices method on Startup.cs file I wrote an Authentication web api project with DotNet core 3.1 and Microsoft.IdentityModel.JsonWebTokens.
I have 3 client app-android, app-pwa and admin-panel. each client has specific SigningCredentials and EncryptingCredentials key on database.
When I want to generate access token, I use one of these client.
var token = new SecurityTokenDescriptor()
        {
            Audience = client.Audience,
            Claims = claims,
            Expires = DateTimeOffset.UtcNow.Add(client.AccessTokenLifeTime).DateTime,
            Issuer = client.Issuer.GetDisplayName(),
            CompressionAlgorithm = client.SupportCompression ? CompressionAlgorithms.Deflate : null,
            IssuedAt = DateTime.UtcNow,
            NotBefore = DateTime.UtcNow,
            EncryptingCredentials =
                new EncryptingCredentials(
                    new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(client.EncryptingKey)),
                    JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512),
            SigningCredentials =
                new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(client.SigningKey)),
                    SecurityAlgorithms.HmacSha256Signature),
        };

In Startup.cs file i need to set AddJwtBearer options
AddJwtBearer(x => x.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            TokenDecryptionKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes("encrypt_key")),
             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("security_key"))
        })

But I need to set these keys dynamicly per client
How can I do this?
thanks

A: I am working with Net Core 5, and I implemented some code that can guide you. Please be patient, because this example has a lot of code.
I stored at database the TokenValidationParameter information in the ApplicationCompany table, in my example:
[Index(nameof(AuthenticationScheme), IsUnique = true)]
[Table("application_company")]
public class ApplicationCompany
{
    [Key, Column("id")]
    public int Id { get; set; }

    [Column("authentication_schema")]
    public string AuthenticationScheme { get; set; }

    [Column("company_id"), ForeignKey("Company")]
    public int CompanyId { get; set; }

    [Column("application_id"), ForeignKey("Application")]
    public int ApplicationId { get; set; }

    [Column("environment_id"), ForeignKey("Environment")]
    public int EnvironmentId { get; set; }

    [Column("valid_audience")]
    public string ValidAudience { get; set; }

    [Column("valid_issuer")]
    public string ValidIssuer { get; set; }

    [Column("access_token_secret")]
    public string AccessTokenSecret { get; set; }

    [Column("refresh_token_secret")]
    public string RefreshTokenSecret { get; set; }

    [Column("access_token_expiration")]
    public int AccessTokenExpirationMinutes { get; set; }

    [Column("refresh_token_expiration")]
    public int RefreshTokenExpirationMinutes { get; set; }

    public virtual Company Company { get; set; }

    public virtual Application Application { get; set; }

    public virtual Environment Environment { get; set; }
}

Please remember it is not the purpose of this post to explain my database shema, neither how I implemented Unit Of Work and DBContext management.
Then, in the Startup.cs, at ConfigureServices() I obtained all my configured information at applicationCompanies variable. After that, I
configured "MyScheme" scheme, with my default options.
   public void ConfigureServices(IServiceCollection services)
    {
        ...

        // If you don't register IHttpContextAccessor explicitly before GetConfiguredApplications(), your DbContext class
        // will have optionsBuilder.IsConfigured = false at OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        // Reference: https://stackoverflow.com/questions/38338475/no-database-provider-has-been-configured-for-this-dbcontext-on-signinmanager-p
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        // Get ApplicationCompany list from Postgres database
        var applicationCompanies = GetConfiguredApplications(services);

        // Add Jwt Bearer
        var authBuilder = services.AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer("MyScheme", options =>
        {
            var key = Encoding.UTF8.GetBytes(Configuration["JwtConfig:AccessTokenSecret"]);

            options.SaveToken = true;
            options.RequireHttpsMetadata = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token
                IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
                ValidateIssuer = true, // The issuer of the token
                ValidateAudience = true, // The audience of the token
                ValidAudiences = Configuration["JWTConfig:ValidAudience"].Split(";"),
                ValidIssuer = Configuration["JWTConfig:ValidIssuer"],
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };
        });

        ...

After configuring my default JwtBearer processing in the ConfigureServices(), I iterated my applicationCompanies list and added more schemes to my Jwt processing:
        // Add other JWT Schemas
        foreach (var applicationCompany in applicationCompanies)
        {
            authBuilder.
                AddJwtBearer(applicationCompany.AuthenticationScheme, options =>
                {
                    var key = Encoding.UTF8.GetBytes(applicationCompany.AccessTokenSecret);

                    options.SaveToken = true;
                    options.RequireHttpsMetadata = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token
                        IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
                        ValidateIssuer = true, // The issuer of the token
                        ValidateAudience = true, // The audience of the token
                        ValidAudiences = applicationCompany.ValidAudience.Split(";"),
                        ValidIssuer = Configuration["JWTConfig:ValidIssuer"],
                        RequireExpirationTime = true,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });
        }
           // Consider ApplicationCompany modifications
        AddMultiSchemeJwtBearerAuthentication(services, Configuration, authBuilder);

Then, in the AddMultiSchemeJwtBearerAuthentication() I provide a "Selector" policy for the default authentication scheme, where I decide what schema to apply according to the received tokens. And in this same processing, I set dynamically AddJwtBearer options when I use services.PostConfigure.
    private static void AddMultiSchemeJwtBearerAuthentication(IServiceCollection services, IConfiguration Configuration, AuthenticationBuilder authenticationBuilder)
    {
        // Add scheme selector.
        authenticationBuilder.AddPolicyScheme(
            JwtBearerDefaults.AuthenticationScheme,
            "Selector",
            options =>
            {
                options.ForwardDefaultSelector = context =>
                {
                    string token = JwtUtils.GetToken(context);

                    if (!String.IsNullOrEmpty(token))
                    {
                        var jwtHandler = new JwtSecurityTokenHandler();

                        var decodedToken = jwtHandler.ReadJwtToken(token);

                        List<Claim> claimList = decodedToken?.Claims?.ToList();

                        if (claimList != null)
                        {
                            string scheme = claimList.Find(x => x.Type.Equals("scheme"))?.Value;

                            var applicationCompany = Startup.GetConfiguredApplicationByScheme(services, scheme);

                            if (applicationCompany != null)
                            {
                                // In order to update dinamically JWT configuration according to database
                                services.PostConfigure<JwtBearerOptions>(scheme, options =>
                                {
                                    var key = Encoding.UTF8.GetBytes(applicationCompany.AccessTokenSecret);

                                    options.TokenValidationParameters = new TokenValidationParameters
                                    {
                                        ValidateIssuerSigningKey = true, // this will validate the 3rd part of the jwt token using the secret that we added in the appsettings and verify we have generated the jwt token
                                        IssuerSigningKey = new SymmetricSecurityKey(key), // Add the secret key to our Jwt encryption
                                        ValidateIssuer = true, // The issuer of the token
                                        ValidateAudience = true, // The audience of the token
                                        ValidAudiences = applicationCompany.ValidAudience.Split(";"),
                                        ValidIssuer = Configuration["JWTConfig:ValidIssuer"],
                                        RequireExpirationTime = true,
                                        ValidateLifetime = true,
                                        ClockSkew = TimeSpan.Zero
                                    };
                                });
                                return scheme;
                            }
                        }
                    }
                    return "MyScheme";
                };
            }
        );
    }

In my Login() method I used the generated token to store a claim with the ClaimType "scheme". I used this claim type to decide what scheme to use in the AddMultiSchemeJwtBearerAuthentication() method at Startup.cs.
   authClaims.Add(new Claim("scheme", applicationCompany.AuthenticationScheme));

Also, I give you my way of obtaining the token:
    public static string GetToken(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];
        string token = null;

        if (authHeader != null && authHeader.Contains("Bearer "))
        {
            token = authHeader[7..];
        }

        return token;
    }

and the way I used to get my configured ApplicationCompany list from Database:
    private static List<ApplicationCompany> GetConfiguredApplications(IServiceCollection services)
    {
        List<ApplicationCompany> result = new List<ApplicationCompany>();

        try
        {
            var sp = services.BuildServiceProvider();

            var unitOfWork = sp.GetRequiredService<IUnitOfWork>();

            var task = Task.Run(async () => await unitOfWork.ApplicationCompanies.GetAllAsync());
            if (task.IsFaulted && task.Exception != null)
            {
                throw task.Exception;
            }
            result = task.Result as List<ApplicationCompany>;
        }
        catch (Exception)
        {
            Console.WriteLine("Cannot build Application Company list");
        }

        return result;
    }

I hope this help suits you well. And I feel glad on receiving constructive comments.


text:
Q: Cant render to ejs file Im learning node.js and now I'm trying to write and read data to/from JSON. I was able to find out how to write data from form to JSON file and how to get them on front end. But now I have a problem when I post new data from form, site should render back to test.ejs with message "File uploaded". Instead of that I get Error "dataTest is not defined.
Here is my test.ejs code from views folder

        <%= typeof msg != 'undefined' ? msg : '' %>
        <form action="test/send" method="post" role="form">
            Name:<input type="text" name="name" />

            Lastname:<input type="text" name="lastname" />

            Adress:<input type=="text" name="adress" />

            <input type="submit" value="Submit" >
    </form>

        <% dataTest.forEach(function(dat) { %>

                <%= dat.name %>
                <%= dat.lastname %>
                <%= dat.adress %>

        <% }); %>

and my test.js code from routes folder
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');

var router = express.Router();

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));

var dataTest = require('../data/dataTest.json');

// GET test page.
router.get('/', (req,res) => res.render('test', {dataTest: dataTest}));

// POST data to dataTest.json
router.post('/send', (req,res) => {
    var file = './data/dataTest.json';

    var name = req.body.name;
    var lastname = req.body.lastname;
    var adress = req.body.adress;

    var obj = { name: name,lastname: lastname,adress: adress };

// 1. Read the existing file
fs.readFile(file, (err, data) => {
    if (err && err.code === "ENOENT") {
        return fs.writeFile(file, JSON.stringify([obj]), error => console.error);
    }
    else if (err) {
        console.error(err);
    }
    else {
        try {
            const fileData = JSON.parse(data);
            fileData.push(obj);
            return fs.writeFile(file, JSON.stringify(fileData), error => console.error)
        } catch(exception) {
            console.error(exception);
        }
    }
});
res.render('test', {msg: 'File Uploaded!'});
})

module.exports = router;

Where did I make mistake?

A: If dataTest is not defined, you should probably define it:
res.render('test', {dataTest: [], msg: 'File Uploaded!'});

A: i guess this
var dataTest = require('../data/dataTest.json');

returns undefined which in return makes dataTest undefined here
res.render('test', {dataTest: dataTest}));

so i suggest you check dataTest contains a valid content. simply just do
console.log(dataTest);


text:
Q: Closing a Tornado handler I have a doubt.
I have this part of code:
#Code for retrieving the MAC address of the node
    como_url = "".join(['http://', options.como_address, ':', options.como_port,
                        '/ztc_config?netid=', netid,
                        '&opcode_group=', opcodegroupr,
                        '&opcode=', opcoder, '&start=-5m&end=-1s'])

    print como_url

    http_client = AsyncHTTPClient()
    response = yield tornado.gen.Task(http_client.fetch, como_url)

    ret = {}
    if response.error:
        ret['error'] = 'Error while retrieving the response'
        self.write(tornado.escape.json_encode(ret))
    else:
        for line in response.body.split("\n"):
            if line != "":
                value = int(line.split(" ")[6])
                ret['response'] = value
        self.write(tornado.escape.json_encode(ret))

and I want that, if the response from the server is null, the handler is closed.
I don't know if this
 if response.error:
        ret['error'] = 'Error while retrieving the response'
        self.write(tornado.escape.json_encode(ret))

is correct to close the handler and return in the page. Or if I have to do a self.finish.....
Thank you very much.

A: The solution is:
if response.error:
        ret['error'] = 'Error while retrieving the response'
        self.write(tornado.escape.json_encode(ret))
        self.finish()


text:
Q: How to create a shortcut in the launcher with specific enironment variable? I want to start emacs with LANG environment variable set to en_US.UTF-8, and I don't want to affect other programs.
In terminal, it could be realized using LANG=en_US.UTF-8 emacs. Then I created a shortcut in the launcher with this command. But when I clicked on it, an error dialog prompted out saying that:
Failed to execute child.
Failed to execute child process "LANG=en_US.UTF-8" (No such file or directory).

Why is that? And how to create such a shortcut?

A: Use the env program for the command in the launcher (setting the Exec key in the according .desktop file):

env LANG=en_US.UTF-8 emacs


text:
Q: Magento2 - Stop standard order email I am developing a solution with an external payment gateway. I create the order and then send the user to the gateway. When coming back from the gateway with a success i resend the order confirmation in my custom callback controller.
But the order confirmation email is sent once already when the order is first created. How do i intervene and stop this? I does not seem to find the correct event to do this in using an observer.

A: Method 1->
You can disable the standard order confirmation email from Admin-
Stores > Configuration > Sales > Sales Email > Order.
Method 2->
Here $this->orderSender->send($order, true); called which extends abstract class method() which check if Order confirmation email is enabled from backend or not so we need create plugin for that
To create a plugin, you need to use di.xml.
[Package_Name]\[Module_Name]\etc\di.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Model\Order\Email\Container\OrderIdentity">
        <plugin name="change_is_enable_method" type="\[Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container\OrderIdentityPlugin"/>
    </type>
</config>

[Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container\ OrderIdentityPlugin.php
<?php

    namespace [Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container;

    class OrderIdentityPlugin
    {
        /**
         * @param \Magento\Sales\Model\Order\Email\Container\OrderIdentity $subject
         * @param callable $proceed
         * @return bool
         */
        public function aroundIsEnabled(\Magento\Sales\Model\Order\Email\Container\OrderIdentity $subject, callable $proceed)
        {
            $returnValue = $proceed();

            if(some condition)
            {
                if($returnValue)
                    $returnValue = false;
                else
                    $returnValue = true;
            }

            return $returnValue;
        }
    }

A: I think a better approach would be to add any additional functionality that your are trying to achieve to magento order email. By creating your own order email will limit functionality such as "resend order email".
But if you want continue take a look at send(Order $order, $forceSyncMode = false) in magento2/app/code/Magento/Sales/Model/Order/Email/Sender/OrderSender.php
In your custom module create etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Sales\Model\Order\Email\Sender\OrderSender" type="Company\ModuleName\Model\Order\Email\Sender\OrderSender"/>
</config>

A: A better way to do this in newer versions of Magento 2 (2.2.7+) is to create an after plugin.
app/code/MagePal/DisableEmail/etc/frontend/di.xml
<type name="Magento\Sales\Model\Order\Email\Container\OrderIdentity">
    <plugin name="magePalDisableEmailPlugin" sortOrder="1"
            type="MagePal\DisableEmail\Plugin\Order\Email\Container\OrderIdentityPlugin"/>
</type>

app/code/MagePal/DisableEmail/Plugin/Order/Email/Container/OrderIdentityPlugin.php
Class OrderIdentityPlugin {

   public function __construct(
      .....

   ) {
      ...
   }

   public function afterIsEnabled(Magento\Sales\Model\Order\Email\Container\OrderIdentity $subject, $result)
   {
       if( some condition ){
           result = false;
       }

       return $result;
   }

}

A: Simply create a event observer to do prevent the order confirmation email
<event name="sales_order_place_after">
      <observer name="Test_Module_event_email_stopper" instance="Test\Module\Observer\EmailStopper\OrderEmailStop" />
 </event>

OrderEmailStop.php file

<?php
namespace Test\Module\Observer\EmailStopper;

class OrderEmailStop implements \Magento\Framework\Event\ObserverInterface
{

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try{
            $order = $observer->getEvent()->getOrder();
            $this->_current_order = $order;

            $payment = $order->getPayment()->getMethodInstance()->getCode();

            if($payment == 'Your Payament method code'){ // change your payement method code
                $this->stopNewOrderEmail($order);
            }
        }
        catch (\ErrorException $ee){

        }
        catch (\Exception $ex)
        {

        }
        catch (\Error $error){

        }

    }

    public function stopNewOrderEmail(\Magento\Sales\Model\Order $order){
        $order->setCanSendNewEmailFlag(false);
        $order->setSendEmail(false);
        try{
            $order->save();
        }
        catch (\ErrorException $ee){

        }
        catch (\Exception $ex)
        {

        }
        catch (\Error $error){

        }
    }
}


text:
Q: Difference between screen and only screen, as well as the 'and' keyword What are the difference between:
@media (max-width: width) { /* CSS Rules */ }

@media screen (max-width: width) { /* CSS Rules */ }

@media screen and (max-width: width) { /* CSS Rules */ }

@media only screen and (max-width: width) { /* CSS Rules */ }

@media only screen (max-width: width) { /* CSS Rules */ }

Also, is it required to add the 'and' keyword?


text:
Q: Using a Singleton to create a default administrative account I never used the @Singleton new feature of JavaEE 6 and i want to give it a try.
I was thinking in creating s Singleton to just hold a password that will allow the app adiministrator(The person that knows the password),to access some content of the app.
I tried to implement it following this tutorial, but it does not work.
This is what i did:
I created the singleton bean:
@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class AdminAcountEJB implements IAdminAcountEJB {

    private String password;

    @PostConstruct
    public void init() {
        password = "password";
    }

    @Lock(LockType.READ)
    public String getPassword() {
        return password;
    }
}

I extracted an interface
public interface IAdminAcountEJB {

    public abstract String getPassword();
}

Then i try to inject the singleton in a managed bean using @EJB
@Named("managementBB")
@SessionScoped
public class ManagementBB implements Serializable{

    @EJB
    private IAdminAcountEJB managementEJB;
    private String input;
    private boolean authorized;

    public String seeWhatsUp() {
        if(input.equals(managementEJB.getPassword())) {
            authorized = true;
            return "manage?faces-redirect=true;";
        }
        return "index?faces-redirect=true;";
    }

  //Get set methods...

}

The last thing i do is create some markup that is displayed in case the correct password is entered:
<h:form rendered="#{managementBB.authorized == false}">
            <h:inputSecret value="#{managementEJB.input}"/>
            <h:commandButton value="..." action="#{managementEJB.seeWhatsUp}"/>
        </h:form>

<h:form rendered="#{managementBB.authorized}">
             CORRECT PASSWORD!!
</h:form>

It all seems ok to me, but when i access the page, the console says:

javax.naming.NameNotFoundException:
  ejbinterfaces.IAdminAcountEJB#ejbinterfaces.IAdminAcountEJB not found

I don't understand why it don't work, this is how i inject other EJB's that are not Singletones but with @Singleton it does not work.
-How can i fix it?
-I am also interested in knowing what do you think about using a singletone for this purpose, you think is a good and safe idea?

A: I guess the problem is, that since you refer to your singleton within an EL expression in the view, it has to be annotated with @Named. If you use your beans only within others, this is not necessary.
Concerning your design, my 2 pennies are these:

*

*Since you are using Java EE 6, you won't need to specify an interface for it. If you want/need it nevertheless, don't call it ISomething (except you work for Apple ;-) but give it a domain related name.

*Using a singleton which allows concurrent read access is ok for core data. Only, I wouldn't put the password within the code, but into a database table, preferrably hashed and use the singleton as a provider for that which reads the table at startup.

*Singletons in general may always introduce a bottleneck into the application because by definition they don't scale. So for your use case it's ok, since we can assume the access rate is very low. The other problem which might be introduced are race conditions (also not in your case) if we have data that changes, since we only have one instance being called in parallel.


text:
Q: php preg_replace replace space in text file i am trying to remove some content from text file using preg_replace.Content in text like below
1
    *useless*Text
                                    Steve Waugh

How to convert content like
1    Steve Waugh

my code is below.It doesn't work.I don't know where am i making mistake?
$content = file_get_contents('test.txt');
$content = preg_replace('/\s[*]useless[*]Text\s/', '  ', $content);
file_put_contents('test.txt', $content);

A: If you want to keep the indenting before *useless*Text so that it is before Steve Waugh in the result, you could use a capturing group.
\h*\R(\h+)[*]useless[*]Text\s*

*

*\h*\R Match 0+ horizontal whitespace chars and a Unicode newline sequence

*(\h+) Capture group 1, match 1+ horizontal whitespace chars

*[*]useless[*] Match *useless*

*Text\s* Match Text and 0+ whitspace chars

See a regex demo | Php demo
In the replacement use $1
preg_replace('/\h*\R(\h+)[*]useless[*]Text\s*/', '$1', $content);

To replace with the predetermined spaces, you could use
\s*[*]useless[*]Text\s*

Regex demo
preg_replace('/\s*[*]useless[*]Text\s*/', '  ', $content);


text:
Q: How are ubuntu iso's built? I wanted to try making a custom iso with some extra packages. Though it is possible to do this manually (by editing a standard iso) using various tools, I want to do this automatically from the repositories, the same way the daily builds of the ubuntu iso is made.
How does the ubuntu server do it/ how can I reproduce it?


text:
Q: Extracting data points from a plot on a finer scale I want to extract data from a plotted graph I have in matlab. As such, I did the following:
f = openfig('spline.fig');
xdata = get(gco, 'xdata');
ydata = get(gco, 'ydata');

This does give me the data points of x and y respectively, but with a step of 0.5 between each points (e.g 1, 1.5, 2, 2.5...). I was hoping to get finer data points than that (e.g 1, 1.1, 1.2, 1.3, 1.4...), and the corresponding y-coordinates to these x-coordinates. How can I do this?

A: The way you got your ydata didn't work for me, I would use:
open testfigure.fig
D = get(gca, 'Children');
ydata = get(D, 'YData');

The ydata I obtained contains the original y-data used to plot the figure.
Now, if you need a finer resolution in the data you will have to interpolate that yourself.
Here's short example of how to interpolate this ydata to a resolution of 0.1:

*

*Define new x values xi to find y values for
xi = 0:0.1:10;

*Interpolate ydata to find new yi values at xi:
yi = interp1(xdata, ydata, xi); %// Using the default "linear"

You should read up on the kind of method you want to use (e.g. nearest neighbour, spline), this depends on your data and requirements.


text:
Q: Grouping Unique Strings in a Column and Performing Function On Separate Column Values In my dataframe, I have the column "away_lineup" which contains groupings of 5 strings as well as a "play_length" column that has a time duration value for each row. I know that np.unique can detect unique string values and the np.sum value adds values in a column, but how do I use a function like np.unique to detect each unique string and sum the values of "play_length" that the string occurs in a row with?
away_lineup                                                                play_length
0  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons     0:00:05
1  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons     0:00:10
2  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons     0:00:20
3  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons     0:00:07
4  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons     0:00:25
5  Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, JJ Redick       0:00:14

My desired output would be something like
player              play_length
Dario Saric             0:01:21
Robert Covington        0:01:21
Joel Embiid             0:01:21
Markelle Fultz          0:01:21
Ben Simmons             0:01:07
JJ Redick               0:00:14

Where unique names are pulled from "away_lineup", stored in a new column "player", and the rows where the player value are present have their "play_length" values added.

A: Use pandas.DataFrame.explode and pandas.to_timedelta:
Note: pandas.DataFrame.explode is available with pandas >= 0.25
df['away_lineup'] = df['away_lineup'].str.split(', ')
df['play_length'] = pd.to_timedelta(df['play_length'])
new_df = df.explode('away_lineup').groupby('away_lineup').sum()
print(new_df)

Output:
                 play_length
away_lineup
Ben Simmons         00:01:07
Dario Saric         00:01:21
JJ Redick           00:00:14
Joel Embiid         00:01:21
Markelle Fultz      00:01:21
Robert Covington    00:01:21

A: In case your pandas does not support explode:
df['play_length'] = pd.to_timedelta(df['play_length'])

new_df = pd.concat((df[['play_length']],
                    df['away_lineup'].str.split(',\s*', expand=True)),
                   axis=1)

(new_df.melt(id_vars=['play_length'],
             value_vars=new_df.columns[1:],
             value_name='artist')
   .groupby('artist').play_length.sum()
)

Output:
artist
Ben Simmons        00:01:07
Dario Saric        00:01:21
JJ Redick          00:00:14
Joel Embiid        00:01:21
Markelle Fultz     00:01:21
Robert Covington   00:01:21
Name: play_length, dtype: timedelta64[ns]

A: Check the trick of get_dummies
#df['play_length'] = pd.to_timedelta(df['play_length'])

df.away_lineup.str.get_dummies(',').mul(df.play_length,0).sum()
Out[372]:
 Ben Simmons        00:01:07
 JJ Redick          00:00:14
 Joel Embiid        00:01:21
 Markelle Fultz     00:01:21
 Robert Covington   00:01:21
 Dario Saric        00:01:21
dtype: timedelta64[ns]

A: you can use explode and group by like this
import numpy as np
import pandas as pd

## create dummy data
arr = [("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons", "00:00:05"),
("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons", "00:00:10"),
("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons", "00:00:20"),
("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons", "00:00:07"),
("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, Ben Simmons", "00:00:25"),
("Dario Saric, Robert Covington, Joel Embiid, Markelle Fultz, JJ Redick", "00:00:14"),]

df = pd.DataFrame(arr, columns=["Player", "Play Time"])
df["Play Time"] = pd.to_timedelta(df["Play Time"])

## Solution
df["Player"] = df["Player"].str.split(",")
df.explode("Player").groupby("Player").sum()

output
            Play Time
Player
Ben Simmons 00:01:07
JJ Redick   00:00:14
Joel Embiid 00:01:21
Markelle Fultz  00:01:21
Robert Covington    00:01:21
Dario Saric 00:01:21


text:
Q: Rest API from nodejs to https url with port 8443 throwing error I'm trying to make an API call from nodejs to tomcat server using http/https module
I have two options for api url

*

*http://samleapiurl.com/getdata - This works fine and i'm getting reponse
var options = {
    host: 'samleapiurl.com',
    port: 80,
    path: '/getdata'
};

http.get(options, function(resp) {
    var body = '';

    resp.on('data', function(chunk) {
        body += chunk;
    });
    resp.on('end', function() {
        res.end(body);
    });
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

*https://samleapiurl.com:8443/getdata
var options = {
    host: 'samleapiurl.com',
    port: 8443,
    path: '/getdata'
};

https.get(options, function(resp) {
    var body = '';

    resp.on('data', function(chunk) {
        body += chunk;
    });
    resp.on('end', function() {
        res.end(body);
    });
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

2nd option doesn't work and it throws an error like
Got error: 10232:error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert
internal error:openssl\ssl\s23_clnt.c:741:

I'm not sure why i'm getting this error if try to access 8443 in https mode.
Is there anyone who faced similar issue?

A: You might try restricting which ciphers tomcat can use, as noted in this blog, which suggests adding the following line to the SSL Connector section of server.xml:
ciphers="SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"


text:
Q: "Operation not permitted" on program start I am trying to run the YGOPro game on my Mac. However, whenever I try to run it, I get:
server:Ygopro Ingwie$ ./ygopro.app/Contents/MacOS/ygopro
-bash: ./ygopro.app/Contents/MacOS/ygopro: Operation not permitted

I know there have been previous questions - none solved it. I unlocked the binary file already, tried commands like
chflags nouchg ...

But they did not do a thing.
What could I do?


text:
Q: How can I add radiobuttons to a alert? So I am making a game powered by only alerts, prompts, and variables. How can I put radiobuttons inside of prompts or an alert? Progress so far:
alert("Welcome to...\nGRANDMA SIMULATOR 2014!\nEnjoy your stay, sweetie pie. Make yourself at home.\nCopyright (c) CookieModding. All rights served.")
var age = prompt("How old are you?")
alert("Wow! You are " + age + " already? Just yesterday it feels like I was giving you your bottle. You grow up so fast. *gives hug*")
alert("Would you like some cookies?") //I need radiobuttons that say, "YES" or "NO"

A: This is not possible using alert(). It is a method of the window object which cannot interpret HTML tags. So whilst you could add HTML in the string it wouldn't render it as html.
You would need to use a modal/dialog box in JavaScript.
E.g.

*

*http://getbootstrap.com/javascript/#modals

*http://jqueryui.com/dialog/


text:
Q: Point of convergence of series
Possible Duplicate:
How can I evaluate $\sum_{n=0}^\infty (n+1)x^n$

How do I compute the point of convergence of a series?
e.g. for example, How do I prove that,
$$\sum_{n=0}^{\infty}\frac{n}{2^{n+1}}=1$$
Can I do:
Point of convergence=
$\limsup_{n\rightarrow\infty}\sum_{k=0}^{n}\frac{n}{2^{n+1}}=\sup\{\frac{1}{4},\frac{1}{2},\frac{11}{16},\frac{13}{16},\frac{57}{64},\frac{15}{16},\dots\}=1$

A: $$\sum_{n=0}^\infty r^n=\frac1{1-r}$$ for $|r|<1$ and $r\ne1$
Applying derivative wrt $r,$ $$\sum_{n=0}^\infty nr^{n-1}=\frac1{(1-r)^2}$$
Put $r=\frac12,$ $$\sum_{n=0}^\infty \frac{n}{2^{n-1}}=\frac1{(1-\frac12)^2}=4$$
Now, divide both sides by $2^2$

Alternatively,
let $$S=1+2r+3r^2+4r^3+\cdots+ n\cdot r^{n-1}$$ with  $|r|<1$  and $r\ne1$
So, $$r\cdot S=r+2r^2+3r^3+4r^4+\cdots+(n-1)\cdot r^{n-1}+n\cdot r^n$$
On subtraction, $$(1-r)S=1+r+r^2+r^3+\cdots+r^{n-1}-n\cdot r^n=\frac{1-r^n}{1-r}-n\cdot r^n$$
If $n\to \infty, r\to 0$ as  $|r|<1$ , so does $n\cdot r^n$(Prove)
So, $$(1-r)S=\frac1{1-r}$$

A: If we denote S=$\sum_{n=0}^{\infty}\displaystyle \frac{n}{2^{n+1}}$, then
$$S-\frac{S}{2}=\sum_{n=2}^{\infty}\frac{1}{2^k}\longrightarrow S=1$$
Q.E.D.


text:
Q: How do I concatenate different column value to single cell? .
Hello guys,I need your inputs on the topic here.
I intend to combine or concatenate different value in different columns so its shown in a single cell.
Illustration is the following:

1:
Is it possible to do this without macro?

A: use
=CONCATENATE("The name of the painter: ",A3,CHAR(10), "The Hobby: ", B3, CHAR(10), "Tool used: ", C3,CHAR(10),"Remuneration: ", D3)

A: To answer your second question on how to do it with code:
Sub PopulateResultsToCell()
    Dim X As Long, MyArr As Variant, PrefixArr As Variant
    PrefixArr = Array("The name of the painter: ", "The Hobby: ", "Tool used: ", "Remuneration: ")
    MyArr = Application.Transpose(Application.Transpose(Range("A3:D3"))) '<-- Change this for the range to read
    For X = LBound(MyArr) To UBound(MyArr)
        MyArr(X) = PrefixArr(X - 1) & Trim(MyArr(X)) 'Note: Option base is zero but transposing creates a base 1 array hence the X minus 1
    Next
    Range("F3").Formula = Join(MyArr, vbLf) '<-- Change this for where to populate the result to
End Sub