text:
Q: Remove message from a queue in ActiveMq I have an application with several activeMq queues. I would like to list the messages in them and remove any of them from any of the queues based on the id of the message.
Here is my code so far.
public void killMessage(String id) {
    try {
        ActiveMQConnection activeMqConnection = (ActiveMQConnection) connectionFactory.createConnection();
        activeMqConnection.start();

        DestinationSource destinationSource = activeMqConnection.getDestinationSource();
        Set<ActiveMQQueue> queues = destinationSource.getQueues();

        QueueSession queueSession = activeMqConnection.createQueueSession(true, Session.CLIENT_ACKNOWLEDGE);

        for(ActiveMQQueue queue : queues) {
            QueueBrowser browser = queueSession.createBrowser(queue);
            Enumeration<?> messagesInQueue = browser.getEnumeration();
            while (messagesInQueue.hasMoreElements()) {
                Message message = (Message) messagesInQueue.nextElement();
                System.out.println("Current id: " + message.getJMSMessageID());
                if(message.getJMSMessageID().equals(id)){
                    System.out.println("-----message id found-------");
                }
            }
        }

        activeMqConnection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

I iterate through all the queues, then I iterate through all messages in each queue. I even find the message I want to delete, but I cannot find a way to remove it from the queue.
Edit:
I also created a consumer. I am not sure how the consumer should make the messages disappear from the queue. My attempt at it, which have no effect at all, messages remain in the queue, and I get no error message and no exception is thrown which could indicate the consumer did not match a message:
if(message.getJMSMessageID().equals(id)){
    System.out.println("-----message id found-------");
    MessageConsumer consumer = queueSession.createConsumer(queue, "JMSMessageID='" + id + "'");

    consumer.receive();
    consumer.close();
}

A: If you want to use the JMS API to do this then you'll have to create a consumer and use a selector to consume the message with the ID that you want. A queue browser cannot consume messages; it can only browse them.
In the code you pasted you're creating a transacted session which means when you consume the message you'll need to commit the session otherwise the message will never be acknowledged. That said, you're probably better off creating a non-transacted session with AUTO_ACKNOWLEDGE instead.
Also, you probably want to call receive(int) (i.e. with a timeout) so that if the selector can't find the message for some reason your application doesn't just sit there forever waiting on the method to return.


text:
Q: Appending on text file not working just like the answers here on SO, I'm trying to append a text file. My code goes like this:
if countdownTimer > 0 {
   let dir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first!
   let fileurl = dir.URLByAppendingPathComponent(fileName)

   let date = NSDate()
   let calendar = NSCalendar.currentCalendar()
   let hour = calendar.component(.Hour, fromDate: date)
   let minutes = calendar.component(.Minute, fromDate: date)
   let seconds = calendar.component(.Second, fromDate: date)

   newLine = "\(hour):\(minutes):\(seconds),\(someValue),\(someValue)\n"

   let data = newLine.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

   if NSFileManager.defaultManager().fileExistsAtPath(fileurl!.path!) {
      do {
          let fileHandle = try NSFileHandle(forWritingToURL: fileurl!)

          fileHandle.seekToEndOfFile()
          fileHandle.writeData(data)
          fileHandle.closeFile()
       } catch {
          print("Can't open fileHandle \(error)")
       }
   } else {

    }
        countdownTimer -= 1
}

The difference on my implementation is that I am creating the file on separate event (and I'm sure that the file exists before appending) and appending the text file is inside a timer which loops every second. What am I doing wrong? Thanks.

A: I write code that will help you to understand where you could make a mistake.
Firstly create Error types and file name where we going to log our info.
let file = "logger1.txt"

enum Throwing: Error {
    case impossibleToWrite
    case impossibleToRead
}

Than two functions that will writeToFile and readFromFile.
func writeToFile(file:String, log: String) throws {

    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        let path = dir.appendingPathComponent(file)

        do {
            let writer = try FileHandle(forWritingTo: path)
            writer.seekToEndOfFile()
            writer.write(log.data(using: String.Encoding.utf8)!)
            writer.closeFile()
        }
        catch {
            throw Throwing.impossibleToWrite
        }
    }
}

func readFromFile(file:String) throws {

    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        let path = dir.appendingPathComponent(file)

        do {
            let text = try String(contentsOf: path, encoding: String.Encoding.utf8)
            print(text)
        }
        catch {
            throw Throwing.impossibleToRead
        }
    }
}

Than small loop that will iterate and create log with date. Usage of the try! is bad practice but for test purpose it is ok.
func logTimeInLoop() {

    for _ in 0..<10 {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
        let text = formatter.string(from: Date()) + "\n"

        try! writeToFile(file: file, log: text)
    }

    try! readFromFile(file: file)
}

This is output of the data in the file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Anonymous users can connect to MongoDB with security.authorization enabled I have enabled the security.authorization setting in /etc/mongod.conf
security:
  authorization: enabled

But I am still able to connect to the mongo shell without providing credentials.
mongo

Enabling security.authorization seems to enforce access control on the databases and the anonymous user doesn't seem to be able to perform any actions such as listing databases and/or collections.
I have attempted to enable auth in the /etc/mongodb.conf file, but this didn't seem to have any effect and I can still connect anonymously.
auth = true

How do I set the mongo shell to require authentication so that anonymous connections are blocked.

A: The authorization mode in mongodb does not work like mysql.
It will prevent non authorized or anonymous users to read or write the DB but it won't forbid people to connect to your DB.
Anonymous users will always be able to connect themselves but can't do anything.
If you want to block the connection from unknown users or server, you can enable the net.bindIp parameter to allow only the selected IP to connect to your database.


text:
Q: Open WebView not browser from preferenceScreen Android From my PreferenceScreen I want to open links in WebView not browser. Any ideas?
Here is part of my xml:
 <PreferenceCategory
      android:title="@string/about">
     <PreferenceScreen
            android:title="@string/eula"
            android:summary="">
        <intent android:action="android.intent.action.VIEW"
                android:data="http://www.tara.com/m/EULA.aspx" />
    </PreferenceScreen>

    <PreferenceScreen
            android:title="@string/privacy_policy"
            android:summary="">
        <intent android:action="android.intent.action.VIEW"
                android:data="http://www.tara.com/m/Legal/Privacy.aspx" />
    </PreferenceScreen>
    <PreferenceScreen
            android:title="@string/version"
            android:summary="@string/version_name">
    </PreferenceScreen>

    <PreferenceScreen
            android:title="@string/customer_support"
            android:summary="@string/email_description">
            <intent android:action="com.tara.android.turboweather.EMAIL_ACCUWX"
             />
    </PreferenceScreen>
    <PreferenceScreen
            android:title="@string/branding"
            android:summary="">
    </PreferenceScreen>
</PreferenceCategory>

So where the URLs are I want to open an Android WebView, not open the phone's browser.

A: You should the use a click listener on your preference item and when it s clicked, open your activity.
in XMl, replace the PreferenceScreen by a Preference and give it a key
<Preference android:title="About"
            android:summary="Details about the app"
            android:key="aboutPref" />

then in your preference activity, after loading the preference file :
Preference pref = findPreference( "aboutPref" );
pref.setOnPreferenceClickListener( myListener );

where myListener is an instance of an inner class that will launch your activity and pass the url to open in intent extra data.
Regards,
 Stéphane


text:
Q: Why Ctrl+C randomly goes to another piece of the code? My first question here.
As I'm writing code normaly, sometimes I need to copy. And like every 50-100 Ctrl+C copys, the mouse pointer goes to another part of the code and it doesn't copy what was selected (I mainly use eclipse IDE, but I believe this happened in other editors). It's like I was pressing Ctrl+LMB.
This kinda happens randomly and I can't seem to replicate it. I believe I'm misclicking a key but I never do realize what I just did.
This can really piss me off and I can't find anything online related.
Is it just me? Does anyone have an ideia what could be happening?


text:
Q: EJS conditional IF newbie to EJS here,
Tried to get data from MongoDB and display in view. If there is no data, display "otherCondition", if there is data, do loop and display "repeat" and "unrelated"
 <% if (typeof eventData == 'object'){ %> // check if its empty/undefined
     <% eventData.forEach(function(event) { %> // loop if exists

            ...                           // other code

     <% }) %>                             // end of loop

            ...                           // other code (again)

 <% } else { %>                           // else condition

            ...                           // other code (again)

 <% } %>

EJS code above, route code below:
router.route('/').get(function(req, res, next) {
        mongoose.model('Event').find({}, function(err, events) {
            if (err) {
                return console.error(err);
            } else {
                res.format({
                    html: function() {
                        res.render('events', {
                            eventData: events,
                            user: req.user,
                        });
                        if (typeof eventData == 'object')
                            console.log('display new events: ' + eventData);
                        else
                            console.log('no events, sorry :(');
                    }
                });
            }
        });
    })

Probably another silly question, but can anyone help me how to fix this? In console, I get no events, sorry :( but my

  doesn't get displayed.
Thanks in advance.

A: Here eventData is always an Array, Because in server side your using query is find() method,
So typeof eventData will always return an object hence your first condition is always true so the controller never goto otherCondition.
Better you check the lenth of eventData in first if condition

<% if(constructor.eventData === Array && eventData.length > 0){ %>
   <% eventData.forEach(function(event) { %> // loop if exists

        ...                           // other code

   <% }) %>                             // end of loop

        ...                           // other code (again)

<% }else{ %>

        ...                           // other code (again)

<% } %>


text:
Q: Docker container run with error: Exception in thread "main" java.lang.ClassNotFoundException: I am doing build images:
docker build -t jkh9 .

and running container:
docker run jkh9

and get exception:
C:\Users\kulik\IdeaProjects\JkhPaymentTemplateService>docker run jkh9
Exception in thread "main" java.lang.ClassNotFoundException: ru.kulikovskiy.jkh.jkhpaymenttemplate
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:471)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:589)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:151)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:398)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:109)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)

this project success start from command line
java -jar target\JkhPaymentTemplateService-1.0-SNAPSHOT.jar
My DockerFile:
FROM maven:3.6.0-jdk-11-slim AS build
ENV DB_HOST localhost
ENV DB_PORT 2376
COPY pom.xml /pom.xml
RUN mvn -f pom.xml clean
RUN mvn -f pom.xml install
RUN mvn -f pom.xml package
RUN mvn dependency:copy-dependencies

FROM openjdk:11.0-jdk
COPY --from=build /target/JkhPaymentTemplateService-1.0-SNAPSHOT.jar JkhPaymentTemplateService.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/JkhPaymentTemplateService.jar"]
CMD java -classpath JkhPaymentTemplateService

My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>JkhPaymentTemplateService</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
    </parent>

    <properties>
        <start-class>ru.kulikovskiy.jkh.jkhpaymenttemplate.JkhPaymentTemplateService</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>postgresql</artifactId>
            <version>1.10.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.zonky.test</groupId>
            <artifactId>embedded-database-spring-test</artifactId>
            <version>1.5.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>ru.kulikovskiy.jkh.jkhpaymenttemplate</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <configuration>
                    <skip>false</skip>

                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>ru.kulikovskiy.jkh.jkhpaymenttemplate.JkhPaymentTemplateService</mainClass>
                        </manifest>
                    </archive>
                    <images>
                        <image>
                            <build>
                                <entryPoint>
                                    java -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -cp
                                    '/maven/*' play.core.server.ProdServerStart
                                </entryPoint>
                            </build>
                        </image>
                    </images>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

This project is
and i get error.
What should I change in pom or dockerfile?
IDE - Intellage idea.
UPD:
I am change pom.xml, but but the error remained
   <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

A: From my experience you only need this configuratin of your spring-boot-maven-plugin
<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

A: Working solution:
I am delete plugin io.fabric8 from pom.xml, and modify DockerFile.
After i am ran command docker build -t <name_container> .  That is all.
Correct DockerFile:
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/JkhPaymentTemplateService-1.0-SNAPSHOT.jar
/usr/local/lib/JkhPaymentTemplateService-1.0-SNAPSHOT.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/usr/local/lib/JkhPaymentTemplateService-1.0-
SNAPSHOT.jar"]


text:
Q: $\operatorname{GL}(n, \mathbb k)$ Contains a Finite Subgroup Minimally Generated by $n$ Elements Let $n$ be a positive integer. Let $\mathbb k$ be a field. Consider the general linear group $\operatorname{GL}(n, \mathbb k)$ that consists of invertible $n \times n$ matrices with entries in the field $\mathbb k$ under the operation of matrix multiplication.

Claim. There exists a finite subgroup $H$ of $\operatorname{GL}(n, \mathbb k)$ that is minimally generated by $n$ elements (i.e., there exist elements $h_1, \dots, h_n$ of $H$ such that $H = \langle h_1, \dots, h_n \rangle$ and no $n − 1$ elements of $\operatorname{GL}(n, \mathbb k)$ generate $H$).

Like several commenters have noted, the claim does not hold when $\mathbb k = \mathbb Z / 2 \mathbb Z$ and $n = 3.$
I had initially thought of the following. Let $I$ denote the $n \times n$ identity matrix. Given a permutation $\sigma$ of the symmetric group $\mathfrak S_n$ on $n$ letters, define the permutation matrix $E_\sigma$ that is obtained by permuting the rows of $I$ according to $\sigma,$ e.g., if $n = 3$ and $\sigma = (1, 2, 3)$ is the three-cycle, then $$E_\sigma = \begin{pmatrix} 0 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}.$$ Considering that permuting the rows of a matrix only affects the sign of its determinant, it follows that $E_\sigma$ is invertible and so belongs to $\operatorname{GL}(n, \mathbb k).$ Further, it can be shown that $E_\sigma E_\tau = E_{\sigma \tau}.$ Consequently, there is an injective group homomorphism $i : \mathfrak S_n \to \operatorname{GL}(n, \mathbb k)$ defined by $i(\sigma) = E_\sigma.$
I have looked for $n$ carefully chosen permutations, but in all cases, the subgroup of $\operatorname{GL}(n, \mathbb k)$ has been isomorphic to $\mathfrak S_n$ and so minimally generated by two elements -- namely the permutation matrices $E_\sigma$ and $E_\tau$ corresponding to the two cycle $\sigma = (1, 2)$ and the $n$-cycle $\tau = (1, 2, \dots, n).$ I would appreciate any comments or observations. Thank you for your time and consideration.

A: $\mathfrak S_n$ has a generating set of size $2,$ $\sigma=(12)$ and $\rho=(123\dots n).$ Then $\rho((k-1)k)\rho^{-1}=(k(k+1)).$ (Depending on the order that you compose permutations.) So $H\cong \mathfrak S_n$ won't do.
In a field not of characteristic $2,$  consider $H$ all the matrices of the form:
$$\operatorname{diag}\left(\pm 1,\dots,\pm 1\right)$$
Then $H$ is isomorphic to the additive group $\left(\mathbb Z/2\mathbb Z\right)^n.$ But this is a vector space over $\mathbb F_2$ and any set of group generators smaller than $n$ shows there is a basis for the $n$-dimension vector space with fewer than $n$ elements.

So you need to only deal with the case when $\mathbb k$ has characteristic $2.$
If we solve it for $\mathbb k=\mathbb F_2,$ you are done, since that will work for any $\mathbb k$ containing $\mathbb F_2.$ This thus reduces to the question for $GL(n,\mathbb F_2),$ which is a finite group.
From the comments, it is not true for $GL(3,\mathbb F_2).$
It is true for $n=2$ since the group itself is non-commutative and of order $6,$ and thus requires $2$ generators.
From a question I asked, for $n\geq 4,$ and $1\leq m\leq n$ the subgroup consisting of matrices of the form:
$$\begin{pmatrix}I_m&A\\0&I_{n-m}\end{pmatrix}$$ is isomorphic to the additive group of $m\times(n-m)$ matrices, which is a vector space over $\mathbb F_2$ of dimension $m\times(n-m).$
When $n\geq 4,$ we can take $2\leq m\leq n-2,$ then $m(n-m)\geq n,$ and take an $n$-dimensional subspace of this space.
This also  works if $n=3$ and $\mathbb k$ is of characteristic $2$ with more than $2$ elements. This is because give two distinct non-zero  $a,b\in \mathbb k$ we get an additive subgroup $V=\{0,a,b,a+b\}$ hitch is a vector space of dimension $2$ over $\mathbb F_2,$ so we can take the subgroup of matrices of the form:
$$\begin{pmatrix}1&0&v\\0&1&c\\0&0&1\end{pmatrix}$$ with $v_1\in V,c\in \mathbb F_2.$

So the only counterexample is $k\cong \mathbb F_2, n=3.$

In all the cases, we have found abelian subgroups isomorphic to $(\mathbb F_2^n,+),$ even when $\mathbb k$ is not of characteristic $2.$

A: Using the following lemma, one of my students suggested a very clever proof to me.

Lemma. Every finite subgroup of $\operatorname{GL}(1, \mathbb k)$ is cyclic.
Proof. Observe that $\operatorname{GL}(1, \mathbb k) \cong \mathbb k^\times$ by the map that sends $[a] \mapsto a.$ Every finite subgroup of the multiplicative group of units of a field is cyclic (e.g., see this proof). QED.

Credit is due to Wayne Voon Van Ng Kwing King for the following.
Proof. Recall that the direct sum of two matrices $A$ and $B$ is given by $$A \oplus B = \begin{pmatrix} A & O_A \\ O_B & B \end{pmatrix},$$ where $O_A$ is the zero matrix with the same number of rows as $A$ and the same number of columns as $B$ (and $O_B$ is defined analogously). Consequently, it follows that $\oplus_{i = 1}^n \operatorname{GL}(1, \mathbb k)$ consists of invertible $n \times n$ diagonal matrices (i.e., diagonal matrices with strictly nonzero diagonal entries). By the lemma, for each copy of $\operatorname{GL}(1, \mathbb k),$ there exists a finite subgroup $H_i$ that is generated by some invertible matrix $[a_i].$ Given that $\mathbb k$ is not the field with two elements, the unit $a_i$ can be chosen so that it is not equal to $1.$ For each integer $1 \leq i \leq n,$ define an $n \times n$ diagonal matrix $A_i$ whose $i$th diagonal entry is $a_i$ and whose other diagonal entries are $1.$ Consider the subgroup $H = \langle A_1, A_2, \dots, A_n \rangle.$ By definition, the matrices $A_i$ all satisfy $A_i^{n_i} = I$ for some positive integer $n_i.$ Consequently, we find that $H$ is a finite subgroup of $\operatorname{GL}(n, \mathbb k).$ Further, there is no way to write $A_i$ as a product of powers of the matrices of $\{A_1, \dots, A_n\} \setminus \{A_i\}$ because the $i$th diagonal entry of such a product is $1$ and $a_i$ can be chosen so that it is not equal to $1.$ Ultimately, we have found a finite subgroup of $\operatorname{GL}(n, \mathbb k)$ that is minimally generated by $n$ elements. QED.


text:
Q: Why lazy loading works without @Lazy on @Component I have a Spring @Component which is added as a dependency in another class with the annotation @Lazy. As per https://www.baeldung.com/spring-lazy-annotation , https://howtodoinjava.com/spring5/core/spring-bean-eager-vs-lazy-init/ , https://stackoverflow.com/a/50041333/6923588 the @Component itself should be annotated with @Lazy in order to work. But with the following code it seems to work without adding the @Lazy annotation.
Lazy component interface.
public interface Lazzy {
    public void doSome();
}

Lazy component implementation.
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
// @Lazy // annotation is commented out
public class LazzyImpl implements Lazzy {
    private static Logger logger = LogManager.getLogger(LazzyImpl.class);

    @PostConstruct
    private void init() {
        logger.debug("in init");
    }

    @Override
    public void doSome() {
        logger.debug("am called");

    }
}

Runner class.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/test-context.xml" })
public class LazyTest {
    private static Logger logger = LogManager.getLogger(LazyTest.class);

    @Autowired
    @Lazy
    private Lazzy lazzy;

    @Test
    public void test_Lazy() {
        logger.debug("in test_Lazzy");
        // lazy.doSome(); // intentionally commented out to check whether LazzyImpl is initialized or not
        logger.debug("in test_Lazzy over");
    }
}

When I run this, I see the following.
LazyTest.test_Lazy(LazyTest.java:25) - in test_Lazzy
LazyTest.test_Lazy(LazyTest.java:27) - in test_Lazzy over

If I take off @Lazy on private Lazzy lazzy; with lazy.doSome(); still commented out, I see following (as expected).
LazzyImpl.init(LazzyImpl.java:17) - in init
LazyTest.test_Lazy(LazyTest.java:25) - in test_Lazzy
LazyTest.test_Lazy(LazyTest.java:27) - in test_Lazzy over

Question:
Why is this code working (i.e. lazy initialized) without @Lazy annotation on LazzyImpl along with @Component?
The given example is using Spring 4.0.3.RELEASE version.


text:
Q: How come citation of author and page number using apacite does not work? I have recently been asked to use APA referencing and want to include specific page numbers for a book reference. I know that the apacite package allows this for example by typing \cite[pp.56-58]{Author2016}. This should come out like (Author 2016, pp.56-58). In stead it comes out like (?, ?)pp.56-58]Author2016.
I am using TexMaker with bibtex and the list of references compiles fine when I don't include specific page numbers but simply fails to recognise it as a reference when I do.
What seems to be the problem?
Here's the document setup I use:
\documentclass[a4paper, 12pt]{article}
        \usepackage[hidelinks]{hyperref}
        \usepackage{hyperref}
        \usepackage{apacite}
        \usepackage[english]{babel}
        \usepackage[footnote,marginclue,draft,danish,silent,nomargin]{fixme}
        \usepackage[pdftex]{graphicx}
        \usepackage{float}
        \usepackage{gensymb}
        \usepackage[strings]{underscore}
        \usepackage[a4paper]{geometry}
        \graphicspath{{Figure/}}
        \setlength\bibitemsep{1\baselineskip}

... according to \cite[pp.56-58]{Author2006}.

        \bibliographystyle{apacite}
        \newpage
        \bibliography{Bib}
        \end{document}

A: The apacite package supports two forms of citation commands, "classic", and natbib.  The syntax you are using for your citation is the natbib syntax, so you need to load the apacite package with the natbibapa option:
\usepackage[natbibapa]{apacite}

See the following question (or the apacite documentation) for more details:

*

*How to write "(e.g. Surname, 2018)" with apacite?


text:
Q: definition and derivation of sine - unit circle - rectangle sine is defined as:
$sin(\alpha) = \frac{opposite}{hypotenuse}$
My questions are:

*

*why is sine only defined on right angles?

*where does the definition comes from/is derived?

*is the unit circle used to define sine or just to show the values?

as far as I know sine is defined and derived with the idea of Similarity of Triangles
but I do not understand exactly why and why these triangles have to be right angles

A: I think there are ways to adequately explain why $\sin$ is defined the way that it is, but I think approaching this angle for every single mathematical definition is quite exhausting because this question will come up in other areas (ie why is a group defined the way it is, why are bijective/surjective/injective functions defined the way they are, etc).  I think one eventually has to come to terms with the fact that mathematical definitions are created and accepted because a plethora of constructive and applicable theory can be built off of those definitions.  If a definition does not build good theory, it needs to be revised.  Math is built off of things with nice properties.
In this case, we define $\sin=\frac{\text{opposite}}{\text{hypotenuse}}$ because it builds nice theory with the rest of trigonometry (and a ton of other math that is far beyond trigonometry).  One is able to derive certain relationships between other mathematical objects, and can build a ton of theory off of it.
Additionally, I would not restrict the definition of $\sin$ to right triangles exclusively.  One could easily define $\sin(x)=\Im(e^{ix})$ where $e^{ix}=\cos(x)+i\sin(x)$ is defined explicitly.  In this case, $\sin(x)$ is essentially the "$y$" coordinate in the unit circle.


text:
Q: Vincular elementos HTML Estou tentando fazer um projetinho só pra aprender mais sobre HTML5, CSS3 e Javascript. Nesse projeto tenho uma div que é tipo um panel e uma outra div que seria um quadrado que eu iria colocar dentro desse panel. Estou usando o drag and drop para poder arrastar esses elementos pela tela.
Minha pergunta é: como que poderia fazer para quando eu colocar a div dentro do panel ela se vincular a ele e quando eu tentar arrastar o panel, eu arraste ele e a div? E também esse panel se ajustar automaticamente ao tamanho da div?
Isso acontece no site da scrumwise...
O código que já tenho é esse aqui:
panel

Qualquer texto

Div

O javascript

Outra coisa, estou usando o bootstrap também!

A: Olhe esse exemplo que fiz no JsFiddle.
O javascript foi esse:
$(document).ready(function() {
  $("#panel").draggable();
  $(".div").draggable();
  $("#panel").droppable({
    accept: ".div",
    drop: function() {
      $(this).css({
        background: "red",
        height: "auto",
        width: "auto",
        display: "inline-block"
      });
      $(".panel .panel-body").css({
        height: "auto",
        width: "auto"
      });
      $('.div').draggable('destroy');
      $('.div').appendTo(".panel .panel-body");
      $('.div').css({
        position: "relative",
        left: 0,
        top: 0
      });
    },
    hoverClass: "hover"
  });
})

Primeiramente, defino a div.div e a div#panel com o .draggable(). Após isso uso o .droppable no #panel, para que seja possível o drop.
O .droppable recebe como argumento, um objeto que tem as seguintes chaves:

*

*accept - elemento aceitável no momento de drag.

*drop - callback para ser chamado após o drop down.

*hoverClass - class acionada no momento do drag.

O callback do drop, faço com que a div#panel se ajuste ao elemento "solto",
e faço um .draggable('destroy') na .div para que não seja mais possível arrastá-la. Depois adiciono essa div a div.panel-body, do seu #panel. E mudo um pouco do css da .div para que ela não fique mau ajustada.
No hoverClass uso apenas um tracejado, para a marcação do drag.
O resto do css você pode ver no fiddle, é bem simples.
Espero que tenha ajudado.


text:
Q: How to pass listbox items as arguments to a method in c#? For example i have these values stored in the listbox.
int pid = (int)reader["pid"];
string FirstName = (string)reader["Fname"];
string LastName = (string)reader["Lname"];
string gender = (string)reader["gender"];
string address = (string)reader["address"];
string email = (string)reader["email"];
string item = string.Format("{0} - {1} - {2} -{3} - {4} - {5}" pid,FirstName, LastName,gender,address,email);
this.listBox1.Items.Add(item);

How do i pass these items to another class method ?
Thanks

A: You can pass it like that:
public void YourMethod(ListBox.ObjectCollection items)

using:
YourMethod(listBox1.Items);

UPD: I created a windows form with empty listbox and 1 button. Clicking on button fills the listbox. Form1 class:
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            var itemGenerator = new ItemGenerator();
            itemGenerator.AddItems(listBox1);
        }
    }

ItemGenerator class:
public class ItemGenerator
    {
        private readonly string[] items = {"item1", "item2", "item3"};

        public void AddItems(ListBox listBox)
        {
            foreach (var item in items)
            {
                listBox.Items.Add(item);
            }
        }
    }

ItemGenerator has method AddItems which has ListBox in parameter. This method is called in Form1 class, so you can directly give a ListBox to processing.


text:
Q: Retrieving a Google Calendar Event with Zend_Gdata Library Using Event URL I'm trying to retrieve a Google Calendar event using the Zend Gdata library.
When I create an event I store in my database the event URL returned by the insertevent method. Initially I thought I could just use this URL to then delete the event later on. After a little research I realized that you actually need a special URL which is the event URL with an extra string of numbers appended to it. I looked at the various event retrieval methods in the Zend Gdata library but none of them seem to allow you to just pass the event URL in. They all seem to want a text or date range query. How would I go about retrieving the delete URL for an event whose URL I already know?

A: I ended up realizing that when you use the insertevent method you can query for the edit url by calling $createdEvent->getEditLink()->href; For example:
// ... All the code to connect to the calendar and create the event
$createdEvent = $gCal->insertEvent($newEvent);
$link_gcal = $createdEvent->getEditLink()->href;

Hopefully this helps someone else down the road. Enjoy!


text:
Q: E-A-V entity Attribute Value Generic Model with Min Max Values I have an entity consisting of several attributes (can be added, can be removed from entity - and new attributes made as well). I need to be able to store the values - so for example I have a list of Attribute / Value pairs . When assigning Attribute to Machine - the Machine also has a min max value for the Attribute - how can I structure the tables to create the proper relationship. Consider the following tables

*

*[Machine Table:  MachId],

*[Machine_EAV Table:  MachId, EavId, ?MinVal?, ?MaxVal?,
?Value?],

*[EAV Table: EavId, Name, TypeId] ,

*[Type Table:  TypeId, TypeName]

In order to store values and have min and max Should I have a Table for the specific dataTypes like this: IntType_Attributes IntId, Machine_EAVId,  MinVal, MaxVal, Value
If anyone needs more info I can add that just ask and I will do my best to provide.
Note the Machine Parameters are constantly changing .. it needs to be flexible.
I am going to need to present a proper view as well - so I will need to be able create a view from the tables..


text:
Q: How to select data between two characters Want select data from string which always start with * symbol and end with * OR |. For example, it must work for both strings: 232323*123456*123512  and 232323*123456|123512.
I try to parse like this :
declare @s varchar(max) = '232323*123456*123512'
select parsename(replace(@s, '*', '.'), 2)

But this one works only with 232323*123456*123512.
Need parser which will work with '232323*123456|123512' also.
Response must be for both strings : 123456.

A: Use another Replace on top of your existing replace to replace both the symbols to '.'
DECLARE @S VARCHAR(MAX) = '232323*123456|123512'

SELECT Parsename(Replace(Replace(@S, '*', '.'), '|', '.'), 2) --123456

Update: to handle . replace the . with any other symbol do the parsing then finally replace the symbol with .
SELECT replace(Parsename(Replace(Replace(replace(@S,'.','~'), '*', '.'), '|', '.'), 2),'~','.') --12.34.56

A: You can try replacing both '*' and '|':
declare @s varchar(max) = '232323*123456|123512'
select parsename(replace(replace(@s, '|', '.'), '*', '.'), 2)

A: One way of doing this is:
declare @s varchar(max) = '232323*123456|123512'

First replace all chars in order to have the same delimiters:
SET @s = REPLACE(@s, '|', '*')

Then select sub-string between first occurence of * and next occurence of *
SELECT SUBSTRING(@s, CHARINDEX('*', @s) + 1, CHARINDEX('*', @s, CHARINDEX('*', @s) + 1) - CHARINDEX('*', @s) - 1)


text:
Q: Azure Datafactory Upload to Salesforce and reference field on another object This is the scenario - we are using Azure DataFactoryV2 to run a series of pipelines that take account data from a local datasource, transform it and upload into Salesforce.
Currently we are wanting to Import an Account and relate it to another account. There is the standard Parent/Child relationship for Accounts (eg a Reseller account and a child account) and this is using the internal Salesforce ID.
We are also using an External ID for the purpose of Upserting and this ID is unique to each record.
According to SF Documentation: Here - when you manually call the API and pass it a JSON file, you are able to add a relationship within the JSON:
    {
   "Name" : "NewAccount",
   "account__r" :
   {
       "Ext_UID__c" : 123
   }

}

However, this doesn't appear to be doable in Azure DataFactoryV2 to specify a lookup relationship in the code, or if it is, I'm not sure how to do it.
For reference - here is the Pipeline JSON code:
{
"name": "Import_to_Salesforce",
"properties": {
    "activities": [
        {
            "name": "Load_to_Salesforce",
            "type": "Copy",
            "policy": {
                "timeout": "7.00:00:00",
                "retry": 0,
                "retryIntervalInSeconds": 30,
                "secureOutput": false,
                "secureInput": false
            },
            "userProperties": [
                {
                    "name": "Source",
                    "value": "[dbo].[Account]"
                },
                {
                    "name": "Destination",
                    "value": "Account"
                }
            ],
            "typeProperties": {
                "source": {
                    "type": "SqlSource"
                },
                "sink": {
                    "type": "SalesforceSink",
                    "writeBatchSize": 5000,
                    "writeBehavior": "upsert",
                    "externalIdFieldName": "Ext_UID__c",
                    "ignoreNullValues": false
                },
                "enableStaging": false,
                "enableSkipIncompatibleRow": true,
                "dataIntegrationUnits": 0,
                "translator": {
                    "type": "TabularTranslator",
                    "columnMappings": {
                        "Name": "Name",
                        "ParentId": "ParentId",
                        "BillingStreet": "BillingStreet",
                        "BillingCity": "BillingCity",
                        "BillingPostalCode": "BillingPostalCode",
                        "BillingCountry": "BillingCountry",
                        "ShippingStreet": "ShippingStreet",
                        "ShippingCity": "ShippingCity",
                        "ShippingPostalCode": "ShippingPostalCode",
                        "ShippingCountry": "ShippingCountry",
                        "Phone": "Phone",
                        "AccountNumber": "AccountNumber",
                        "Brand__c": "Brand__c",
                        "Account_Status__c": "Account_Status__c",
                        "Account_Type__c": "Account_Type__c",
                        "Preferred_Payment_Method__c": "Preferred_Payment_Method__c",
                        "Last_Account_Login__c": "Last_Account_Login__c",
                        "Ext_UID__c": "Ext_UID__c",
                        "Auto_Renew_Status__c": "Auto_Renew_Status__c",
                        "Account_Balance__c": "Account_Balance__c",
                        "Outstanding_Amount_30_days__c": "Outstanding_Amount_30_days__c",
                        "Outstanding_Amount_60_days__c": "Outstanding_Amount_60_days__c",
                        "Outstanding_Amount_90_days__c": "Outstanding_Amount_90_days__c",
                        "Account_Priority__c": "Account_Priority__c",
                        "Reseller__c": "Reseller__c",
                        "Last_Payment__c": "Last_Payment__c"
                    }
                }
            },
            "inputs": [
                {
                    "referenceName": "Staging_Source",
                    "type": "DatasetReference"
                }
            ],
            "outputs": [
                {
                    "referenceName": "Destination_Load_to_Salesforce",
                    "type": "DatasetReference"
                }
            ]
        }
    ]
},
"type": "Microsoft.DataFactory/factories/pipelines"}

Any input would be greatly appreciate.

A: Which SF connector you're using? If there's no meaningful name look at your API user's login history in Salesforce. It's probably listed as "Simba Technologies" or something like that?
For standard relationships you should be able to just type Account.Ext_UID__c Parent.Ext_UID__clike in this Contact load:

For custom lookups/master-detail fields if the field API name is Account__c you can map it for upsert as Account__r.Ext_UID__c.
Just make sure that parent accounts exist before child accounts reference them... Maybe you loaded them in previous job, maybe it's best to load it in two stages:

*

*Flat insert/upsert of all accounts without parent mapped

*Reparenting update/upsert that maps only this record's ext id and the parent's ext. id

A: Lookup Activity is available in ADF v2:

Here you can select the dataset and the row at which you want to lookup.
Hope this helps!


text:
Q: Creating simulation in windows application IDE: VS 2010, C#, .net 4.0
I have a requirement where I need to simulate object in isometric view.
Input parameter initial point start(x, y) of object, end point end(x,y). the object path. you can see following video for example
https://www.youtube.com/watch?v=OAcDqCS7Ur8

In this video you can assume ball as object o, bowler is releasing ball from start(x, y) points ball is pitching on a zone z. and on some angle it is pitching up, so Is it possible to simulate same thing in visual studio, if yes please let me know what techniques can be used, As I researched xna, opengl or directx can be used, what will be easiest and best to achieve this goal, so I can embed this with my winforms application.

A: You can try studying a Physics Engine. There is some implementation available for c#, google for it and find some that you think is good for you. Basically with a physics engine you can define bodies and forces applied to them, and have the position time by time.


text:
Q: unable to switch to Ubuntu after installing Ubuntu Gnome Recently I've had login loop problem, even after trying several solutions given in the forums. I ended up installing Gnome  as suggested here as Solution 3.
After rebooting, the desktop changed to Ubuntu Gnome, but still
didn't solve the loop problem. then I went to BIOS and changed the boot priority to another option, didn't work, then again came back to previous priority and now I can't even access to that login screen. When I switch the computer on I have purple screen suggesting *Ubuntu, Advanced options for Ubuntu, and System setup. Once I hit *Ubuntu it goes through some process
Then the screen gets  dark for about 4 seconds and quickly shows up
And this repeats infinitely.
I think I corrupted the Ubuntu system by trying too many things.
How can I solve this case?
If there is no way,How can I uninstall Ubuntu from my computer without damaging Windows system?
Thank you for your time and advice!


text:
Q: Setting custom gradients on TensorFlow 2.0 I am using a really simple neural network with the latest version of tensorflow 2.0, on a jupyter notebook running python 3.7.0.
From a matrix M, the NN computes a parameter P. Then I have a function F which from P computes another matrix M' that I want to use in my loss function.
I understand that TF2.0 automatically gives me the gradients from M to P.
I also have calculated the gradients from P to M', which I want to plug in using the chain rule in order to have the full gradients from M to M'.
I have searched on the TF site for documentation but didn't find any response to my issue. How should I proceed?
Edit: The code I am trying to make work is the following:
model = tf.keras.models.Sequential()

# Add the layers
model.add(tf.keras.layers.Dense(32, activation="relu"))
model.add(tf.keras.layers.Dense(16, activation="relu"))
model.add(tf.keras.layers.Dense(1, activation="relu"))

# The loss method
loss_object = tf.keras.losses.MeanSquaredError()
# The optimize
optimizer = tf.keras.optimizers.Adam()
# This metrics is used to track the progress of the training loss during the training
train_loss = tf.keras.metrics.Mean(name='train_loss')

def train_step(Data): #Data is: Blurred image; blurr matrix; max(true image); gvar; true image
    img = Data[4]
    MainGaussian_init(Data)
    for _ in range (K):
        with tf.GradientTape() as tape:
            Xip= model( M )
            MainGaussian_1_U () #Computes M' from Xip aka P
            print ("img=", img)
            loss= loss_object(M_true, M2) #with M2 as M'
            print ("loss=", loss)
        gradients = tape.gradient(loss, model.trainable_variables)
        print (gradients)
        optimizer.apply_gradients(zip(gradients, model.trainable_variables))
        train_loss(loss)

Let me know if any of this needs to be made any clearer!


text:
Q: "Unable to find any implementation of the contract" Exception in LightSwitch extension I'm teaching myself Visual Studio LightSwitch by porting Excel Importer extension.
I have all the pre-requisites (Visual Studio 2010 SP1 Ultimate edition, Visual Studio 2010 SP1 SDK, Visual Studio LightSwitch 2011 Extensibility Toolkit) except that I'm using LightSwitch Beta 2.
While trying to execute this line,
IServiceProxy sdkProxy = VsExportProviderService.GetExportedValue<IServiceProxy>();

I get the following exception:

The composition produced a single composition error. The root cause is

provided below. Review the CompositionException.Errors property for
    more detailed information.
1) Unable to find any implementation of the contract:
    'Microsoft.LightSwitch.Sdk.Proxy.IServiceProxy'

Any idea on how to resolve this?

A: When you call
IServiceProxy sdkProxy = VsExportProviderService.GetExportedValue<IServiceProxy>();

MEF (Managed Extensibility Framework) will try to find an implementation of the IServiceProxy interface. It seems that it cannot find any implementation.
Does that help you?

A: So I managed to solve my problem by doing a complete re-install of Visual Studio 2010 SP1 Ultimate edition, Visual Studio 2010 SP1 SDK, Visual Studio LightSwitch 2011 Extensibility Toolkit and LightSwitch.
I tried everything I could think of to avoid this but after finding that the Microsoft samples themselves failed to build with the exact same error, I concluded that some DLL that contained the implementation IServiceProxy was probably out of date or not registered.
I can now build the solution with no issues.


text:
Q: Angular - Check multiple Child components form as dirty I have some bunch of child components holding a form - value for the form will be send from the parent components - i have looped the child components in the parent and passed the data to the components
Child Component
<form #formType="ngForm">

                <ng-container *ngIf="item.Foundation">
                    {{item.Size.toUpperCase()}}

                    <input *ngFor="let val of item.Foundation" type="text" appNumbericInput maxlength="4" [(ngModel)]="val.Val" class="inputcustom text-right" [disabled]="(val.Val == null ? true : false) || disableChecker" (input)="enableSave=true" />
                </ng-container>

</form>

Child Component.ts
@Component({
    selector: 'app-base-mattress',
    templateUrl: './base-mattress.component.html',
    styleUrls: ['./base-mattress.component.css']
})

export class BaseMattressComponent implements OnInit {
    @Input() productSizes: IItemDetails[];
    @ViewChild('formType') formVariable: NgForm;
    blobURL: string = environment.blobURL;
    constructor() {}
    ngOnInit() {}
}

Parent Component html
<ng-container *ngFor="let slot of slotRequests; let j = index;">
    <ng-container *ngIf="slot.ItemGrouping.toLowerCase() === 'mattress'">
        <ng-container *ngFor="let data of slotRequests[j].Data; let i = index;">
            <app-base-mattress [productSizes]="data"></app-base-mattress>
        </ng-container>
    </ng-container>
</ng-container>

Now my problem is that i want to read the child component form variable?
I don't want a service to subscribe and check whether the form dirty, i have tried it many times it doesn't work.
I have tried to map my child with template reference variable like this
<app-base-mattress [productSizes]="data" #childData></app-base-mattress>
but it seems I'm looping the child component so it doesn't seem to act as an reference variable for specific component - Please help me to find out how can i read the child component form variable
Working version of my StackBlitz
Thanks in advance !!

A: use form element in your top level component
<form #formType="ngForm">
    <ng-container *ngFor="let slot of slotRequests; let j = index;">
        <ng-container *ngIf="slot.ItemGrouping.toLowerCase() === 'mattress'">
            <ng-container>

                    <app-base-mattress [productSizes]="data.ItemDetails"></app-base-mattress>

            </ng-container>
        </ng-container>
    </ng-container>
</form>

Use viewproviders to provide controncontainer which is super class for formDirectives the use existing ngForm group group together your form
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NgForm, ControlContainer } from '@angular/forms'

@Component({
  selector: 'app-base-mattress',
  templateUrl: './base-mattress.component.html',
  styleUrls: ['./base-mattress.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
})
export class BaseMattressComponent implements OnInit {
  @Input() productSizes: any[];

  constructor() { }

  ngOnInit() {
  }

}

Example:https://stackblitz.com/edit/angular-ch5yh2

A: You can do this:
parent.component.html:
<app-base-mattress #childCmp [productSizes]="data"></app-base-mattress>

parent.component.ts:
@ViewChildren('childCmp ')
childCmps: QueryList<BaseMattressComponent>;

and then iterate through them to achieve desired results
this.childCmps.forEach((item) => {
...
});


text:
Q: Restore SQL Server database I'm attempting to restore a SQL Server database that was on one server to a new server via SSMS. I right-click on Databases and select Restore Database....
From the Restore Database window, I select the Device radio button and add my .bak file to the Backup media list using the "Add" button. If I click the "Contents" button, everything looks great. The contents window shows all the info about the back such as the database name, the fact it was a full backup, the server name it was backed up from, username, etc...  So, I know the backup file is valid.
However, when I return to the Restore Database screen from the Select Backup Device window, nothing shows in the "Backup sets to restore:" grid and the OK button is disabled. So, I'm not able to restore the backup.
I'm not sure what version of SQL Server I'm coming from but the destination version is 11.0.6579.0


text:
Q: How to show only one element in a Gatsby .map function? I am new to Gatsby. I have lost with what to do here... please help me......
I want to show only one element(h4) when I click a button.
For example, I have 5 plans and each plan has one button and one h4 tag.
When I click the third button, only the third h4 tag will shows.
As expected by my code, when the button is clicked it displays every element's h4 tag of the map. Is there any way I could active/inactive the component for just one element of the map in this case?
Thank you in advance.
  import React, { useState } from "react"

  const TourPage = ({
      const [isOpen, setOpen] = React.useState(false)
      const toggleOpen = () => {
        setOpen(!isOpen)
      }

  return (

           {plans.map((plan, index) => {
              return (

                    <button
                      className="btn"
                      onClick={toggleOpen}
                    > button </button>
                    <div
                      className={`${isOpen ? "active" : "inactive"}`}
                    >

{plan.iternary}

               )
            })}

A: You need to have multiple states, state for each plan.
Here is a simple example, you can achieve it however you like, but the concept is the same: manage multiple states within the component.
const plans = [{ id: `id1`, iternary: "a1" }, { id: `id2`, iternary: "a2" }];

const INITIAL = {
  id1: false,
  id2: false
};

const TourPage = () => {
  const [openManager, setOpenManager] = React.useState(INITIAL);

  return (

      {plans.map(plan => {
        const onClick = () => {
          setOpenManager(prev => ({ ...prev, [plan.id]: !prev[plan.id] }));
        };
        return (

            <button className="btn" onClick={onClick}>
              button
            </button>
            <div className={`${openManager[plan.id] ? "active" : "inactive"}`}>

{plan.iternary}

        );
      })}

  );
};


text:
Q: Indy 10 HTTPS Proxy I have a small program here that uses idHTTP to download some things from a https server . I need to alter this program to use a HTTPS Proxy server .
I got two IP addresses for the proxy 1.1.1.1 8080 for HTTP , and 2.2.2.2 8084 for HTTPS .
I altered my code to look like this :
  try
   IdHTTP1:=TIdHTTP.Create(nil);
   try
    LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      // does not seem to do anything
      LHandler.TransparentProxy.Host:='2.2.2.2';
      LHandler.TransparentProxy.Port:=8084;
      LHandler.TransparentProxy.Enabled:=true;

      // this works even when using HTTP proxy for HTTPS
      idHTTP1.ProxyParams.ProxyServer:='1.1.1.1';
      idHTTP1.ProxyParams.ProxyPort:=8080;

      IdHTTP1.IOHandler:=LHandler;
      Src:= IdHTTP1.Get('https://csv.business.tomtom.com/extern?account='+company+'&username='+user+'&password='+password+'&apikey='+apikey+'&lang=en&action=showObjectReportExtern');
    finally
      LHandler.Free;
    end;
   finally
     IdHTTP1.Free;
   end;
  except on E: Exception do
//      Writeln(E.ClassName, ': ', E.Message);
  end;

Can someone please show me how do I tell idHTTP LHandler to USE the HTTPS Proxy ?
Thank you!

A: You need to use ONLY the TIdHTTP.ProxyParams by itself, and be sure to assign it the correct HTTP proxy to use for the protocol scheme you are requesting (HTTP vs HTTPS):
try
  IdHTTP1 := TIdHTTP.Create(nil);
  try
    LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdHTTP1.IOHandler := LHandler;

    IdHTTP1.ProxyParams.ProxyServer := '2.2.2.2';
    IdHTTP1.ProxyParams.ProxyPort := 8084;

    Src := IdHTTP1.Get('https://csv.business.tomtom.com/extern?account='+company+'&username='+user+'&password='+password+'&apikey='+apikey+'&lang=en&action=showObjectReportExtern');
  finally
    IdHTTP1.Free;
  end;
except
  on E: Exception do
    // Writeln(E.ClassName, ': ', E.Message);
end;

The TransparentProxy property does not work the way you think it does.
When you do not explicitly assign a TIdCustomTransparentProxy-derived component to the TransparentProxy property (which you are not), the property getter creates a default TIdSocksInfo component.  You do not want to use a SOCKS proxy in this situation, and besides, the TIdCustomTransparentProxy.Enabled property is the wrong way to enable a TIdSocksInfo, you have to use the TIdSocksInfo.Version property instead.


text:
Q: What does "the LCM of two distinct positive integers is divisible by the highest single digit power of 3 , while their HCF is 12. " mean?
The LCM of two distinct positive integers is divisible by the highest single digit power of 3 , while their HCF is 12. Which of the following could be the smaller of the two?

I think this means the LCM is divisible by $3^9$ but their HCF is 12.
So, one is $3 \cdot 2^2$, another is $3^{8+x} \cdot 2^2$ where $x \geq 0$?
A. 6
B. 24
C. 36
D. 300
E. 360
I heard B, and D are both correct but I don't see why.


text:
Q: Will concepts lite change the need of CRTP to achieve static polymorphism? Since I have discovered CRTP some years ago, I use it in many places to achieve compile-time polymorphism for very intensive computing oriented codes. It's great to "inject" member functions into classes in a generic way when one cares about both genericity and maximal performances at runtime.
I have read/watch several things on the concepts lite which will be (I hope) a part of the next C++ standard. It will be absolutely wonderfull to design functions in a more abstract and generic manner, avoiding the awfull lines of SFINAE/std::enable_if I currently use.
I have not tested the g++ branches that implements concepts to play with them and to investigate metaprogramming methods I like in a new way. But maybe some of you have. My first thought is that concepts will not solve the problem of static polymorphism, but as these kind of things may heavily relies on tricks, I may be wrong. So my question is the following: will the concepts lite be able to achieve compile-time polymorphism (as we currently can do through CRTP) in a more convenient way ? (examples of code are welcome).

A: I shouldn't think so. Concepts Lite will replace your use of enable_if, but I'm not sure that it allows for new techniques for CRTP. On the other hand, there may be some interesting things that can be done.
I will say that I ran into some CRTP issues with an earlier implementation of concepts lite. Checking constraints requires the type arguments to be complete types. If you have a base class parameterized over a derived class, you need to defer the check until the point of use. For example:
template<Fooable D>
struct crtp {
  void f() {
    static_cast<D*>(this)->g();
  }
};

struct derived : crtp<derived> { // Error!
};

When you try to check Fooable<derived>, derived won't have been defined yet. Better to write it this way:
template<typename D>
struct crtp {
  void f() requires Fooable<D>() {
    static_cast<D*>(this)->g();
  }
};

Now, Fooable<D>() is only checked when f() is called.
Just an FYI.

A:
So my question is the following: will the concepts lite be able to achieve compile-time polymorphism (as we currently can do through CRTP) in a more convenient way ? (examples of code are welcome).

No - they would not suppress CRTP in general. Concepts lite are mostly about ease of overloading and defining generic functions, plus ease of syntactic checks:
template<typename T>
concept bool EqualityComparable()
{
    return requires(T a, T b)
    {
        bool = {a == b};
        bool = {a != b};
    };
}

template<InputIterator I, EqualityComparable T>
I find(I first, I last, T x);
// or
template<InputIterator I>
I find(I first, I last, EqualityComparable x);

I think concepts lite would suppress many use cases of std::enable_if.
CRTP has different use cases, some of them are related to overloading indeed, for example:
template<typename Derived>
void do_something(const CRTP_Base<Derived> &x);

But CRTP is not limited to overloading, it has other applications: for example main use case for std::enable_shared_from_this does not imply any overloading:
class Widget : std::enable_shared_from_this<Widget>
{
    // ...
};

Some of use cases of CRTP involve even virtual functions - for instance automatic implementation of Cloneable interface:
// Simple example, no covariance, etc
struct Base
{
    typedef unique_ptr<Base> Unique;

    virtual Unique clone() const = 0;
    virtual ~Base() = default;
};

template<typename Derived>
struct ImplementCloneable: protected Base
{
    Unique clone() const override
    {
        return Unique(new Derived(static_cast<const Derived&>(*this)));
    }
protected:
    ~ImplementCloneable() = default;
};

struct Widget: ImplementCloneable<Widget>
{
};

A: As I understand it, it should be possible to use Concepts Lite to define a kind of 'static interface' which says that a Concept requires certain member functions to exist on a class and to be callable with certain signatures. This seems like it could be useful for static polymorphism in some situations.
I don't think this is really the intended use for Concepts Lite however. In talks I have seen the suggestion seems to have been that there should be relatively few Concepts and they should be fairly fundamental (thinks like the concept of a  'forward iterator') rather than being used for defining ad-hoc static interfaces.


text:
Q: Send NSDictionary as an parameter in @selector How can I send my NSDictionary on my selector, as a parameter, and how I can read it?
NSDictionary * dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"idOferta",@"test", nil];
NSThread * viewsThread = [[NSThread alloc] initWithTarget:self selector:@selector(updateViewStatistic:) object:dict];
[viewsThread start];

- (void)updateViewStatistic:(NSThread *)mt {
      NSLog(@"dictionary %@",dict);
}

A: Change your updateViewStatistic: method to something like this:
- (void)updateViewStatistic:(NSDictionary *)dictionary
{
    NSLog(@"Dictionary: %@", dictionary);
}


text:
Q: model.destroy() returning errors with sinatra backend I'm having an issue getting my model.destroy method to work properly in backbone. This is my function
deleteEvent: function(){
    var self = this;
    var check = confirm("Are you sure you want to remove record " + this.model.get("ticket_id"));
    if (check == true){
        this.model.id = this.model.get('session_id');
        this.model.destroy({
            wait: true,
            success: function(model, response, options){
                console.log(options);
                console.log(response);
                self.$el.remove();
            },
            error: function(model, xhr, response){
                console.log("ERROR:");
                console.log(model);
                console.log(xhr);
                console.log(response);
            }
        });
    }
    else return;
},

The model looks like this:
vkapp.EventRecordModel = Backbone.Model.extend({
urlRoot: '/user_event',
idAttribute:"_id",
defaults: {
    "ticket_id": '',
    "start": '',
    "end": ''
},
validate: function(attrib){ //This is only called when setting values for the model, not on instantiation
    if (attrib.ticket_id == null)
        alert("no ticket number");
    if (attrib.start == undefined)
        alert("no start time");
    if (attrib.end == null)
        alert("no end time");
    if (attrib.start > attrib.end)
        alert("start can't be before the end time.");
}

});
And this is what the route looks like in my sinatra.
delete '/user_event/:session_id' do
    user_event = ProjectTimer.get(:session_id => params[:session_id])
    user_event.destroy
end

I am not sure why I am getting an error return.

A: If you follow the advice from this answer
delete '/user_event/:session_id' do
  user_event = ProjectTimer.get(:session_id => params[:session_id])
  user_event.destroy
  halt 204
rescue => e
  # do something with the exception, maybe log it
  halt 500
  # or set status to 500 and re-raise
end

See Halting in the Sinatra docs for more.

A: I did get this working properly however by setting the dataType to "text." I found that Backbone.sync expects JSON of the object deleted to be returned in order to be successful. So, if we change the dataType to Text it over-rides that JSON expectancy. This is my final code
deleteEvent: function(){
    var self = this;
    var check = confirm("Are you sure you want to remove record " + this.model.get("ticket_id"));
    if (check == true){
        this.model.id = this.model.get('session_id');
        this.model.destroy({
            dataType: "text",
            wait: true,
            success: function(model, response, options){
                self.$el.remove();
            },
            error: function(model, xhr, response){
                console.log("ERROR:");
                console.log(model);
                console.log(xhr);
                console.log(response);
            }
        });
    }
    else return;
},


text:
Q: Adding to an array with an asynchronous function assume I have an array of files, file_urls, I want to parse through and add the results to a result array:
var requestImageSize = require('request-image-size');

function parse_file(file) {
    return new Promise(function(resolve, reject) {
        /*this is an asynchronous function from an external library,
         it returns attributes about the file such as its size and dimensions
        */
        requestImageSize(file).then(function(result) {
            resolve(result);
        }
        .catch(function(err) {
            reject(err);
        });
    })
}
var results = [];
var promise;

//assume file_urls is already populated with strings of urls to files
file_urls.each(function(index, elem) {
    //if it's the last element then return the promise so we can return the final results at the end
    if (index == file_urls.length-1) {
        promise = parse_file(this);
    }
    //otherwise process the promise
    else {
        parse_file(this).then(function(result) {
            results.push(result);
        }
    }
});

//add the final element and return the final results
promise.then(function(result) {
    results.push(result);
    return result;
});

Since parse_file returns a promise and I'm iterating through many promises, how do I ensure that the results array has the correct number (and possibly order) of elements?
so far in my project it is returning an erratic number of elements, what should I do differently?

A: The idiom you're looking for is Promise.all combined with .map:
Promise.all(file_urls.map(parse_file)).then(results => ...)

Promise.all ensures you get all results in correct order, it doesn't enforce any particular order of execution though.


text:
Q: How can I fix WOW64.dll error My system shows an error message;

C:\Windows\system32\wow64.dll is either not designed to run on
  windows or it contains an error. Try installing the program again
  using the original installation media or contact your system
  administrator or the software vendor for support.

This message appears when trying to open all programs, internet explorer, windows live, office suite programs etc.
How can I fix this?

A: I started experiencing the WOW64.DLL error when my Windows updates failed. I spent a total of 9 hours battling this issue as no application or internet browser launched causing more frustration. I finally resolved this issue with the following steps:

*

*Procure a copy of WOW64.DLL located at C:\Windows\System32 from a different Windows 7 PC (I used a friend's PC). Copy it to a USB drive.

*Restart your PC in Safe Mode (press the F8 key during the boot process).

*Navigate to C:\Windows\System32, right-click on Wow64.dll and select Properties.

*Within the Wow64.dll Properties window, go to the Security tab and click on Advanced.

*Go to the Owner tab and change the Owner to Administrators (the current owner normally would be TrustedInstaller). Alternatively, this can also be achieved using an elevated Command Prompt:

*

*Within the elevated Command Prompt, navigate to C:\Windows\System32

*Enter the following command:
TAKEOWN /F WOW64.DLL

You should receive a confirmation message saying "SUCCESS: The file (or folder): "filename" now owned by user "Computer Name\User name"."

*Upon success, enter the following command:
ICACLS WOW64.DLL /grant administrators:F

*Delete or move your current Wow64.dll to a different folder.

*Copy the external copy of Wow64.dll (from step 1 above) to your system's C:\Windows\System32 folder.

*Restart your PC normally.
These steps resolved my issue.

A: Try using opening the command prompt with administrative privileges and run
sfc /scannow

A: I had the same issue and all of provided instructions did not work. What worked for me is to finish all the updates.

A: This is an excerpt from this Microsoft Answers post.

Windows Live Media have these four dll's linked to them;

C:\Windows\System32\ntdll.dll C:\Windows\System32\wow64.dll
  C:\Windows\System32\wow64win.dll C:\Windows\System32\wow64cpu.dll

Manually register the dependent .dll files for this error and see if this resolves the issue.
To do this, click the Start ORB / in the Search Line Type Command / Right Click on the Command Prompt from the programs list / Select RUN AS ADMINISTRATOR.
In the command prompt type regsvr32 /s ntdll.dll and hit enter,
then regsvr32 /s wow64.dll and hit enter,
then regsvr32 /s wow64win.dll and hit enter,
then regsvr32 /s wow64cpu.dll and hit enter.

You've not answered whether Windows works normally in Safe Mode. It is recommended you try as @pincopallino suggests to run sfc /scannow while in Safe Mode. After that, try uninstalling Windows Live Essentials and reinstall it.

If you are still having trouble after that, you may want to do a factory recovery to start from a fresh install of Windows.


text:
Q: Random Forest Bias in Permutation Importance. I just read on several blogs something at the form: Variable Importance using permutation will lead to a bias if the variables exhibit correlation. It is for instance stated by https://blog.methodsconsultants.com/posts/be-aware-of-bias-in-rf-variable-importance-metrics/ that

"The mean decrease in impurity and permutation importance computed from random forest models spread importance across collinear variables. For example, if you duplicate a feature and re-evaluate importance, the duplicated feature pulls down the importance of the original, so they are close to equal in importance."

In the article by Strobl et. al (2008): https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-9-307 it is argued that correlated variables will show too high variable importance, where it is stated

"We know that the original permutation importance overestimates the importance of correlated predictor variables."

Furthermore, it is described in https://scikit-learn.org/stable/modules/permutation_importance.html that

"When two features are correlated and one of the features is permuted, the model will still have access to the feature through its correlated feature. This will result in a lower importance value for both features, where they might actually be important."

The three quotes seem rather contradicting. The second quote states that correlated variable will show too high variable importance, where the third states that the variable importance will be too low. The quote agrees with this.
Do anyone know what is true? Is the variable importance overestimated or underestimated when variables are correlated?

A: The blog quote is identical to what was stated in the scikit learn and based on my personal experiments that are true however I also found the second quote confusing.
let me share my experiments to make that point clear.
t-test score is a distance measure feature ranking approach which is calculated for 186 features for a binary classification problem in the following figure.
the higher the value of t-score the better the feature is

looking into it we can obviously see that the best features are in the range of 45 and it neighboring while the less informative features are in the range of 90 to 100.
now let's look into the correlation between the features in the following figure.

and also the following figure is showing the classwise distribution of this binary class.

looking into the correlation figure, it is obvious that features in the range of 90 to 100 have the minimum correlation while other ranges of features that were highly informative are highly correlated.
now lest having a look into the random forest feature importance calculated based on permutation importance using scikit learn in the following figure.

now all the feature which were informative are actually downgraded due to correlation among them and the feature which were not informative but were uncorrelated are identified as more important features.
therefore we can conclude that using random forest feature selection approach for datasets with highly correlated features are not a suitable choice.


text:
Q: When clicking on an item that has a submenu on a phone the submenu toggle action acts only on the arrow next to the text and not on the text When clicking on an item that has a submenu on a phone the submenu toggle action acts only on the arrow next to the text and not on the text. I tried adding the class of the text in the on click function which makes the text slide up as with the arrow icon but it does not open the submenu like the arrow does.
Below is the javascript code for this.
Any ideas on how to customize the js code?

function rep_menu(){
 $('.toggle-mobile-menu').on('click',function(event){
  event.preventDefault();
  $(this).parents('.main-nav').toggleClass('active');
  if($(window).width()<768){
   $('.main-nav li.menu-item-has-children').append('');
   $('.main-nav li.menu-item-has-children>.btn-toggle-mobile-menu').on('click',function(event){
    $(this).toggleClass('active');
    $(this).prev().stop(true,false).slideToggle();
   });
  }
 });
}

I also found this part of code in my main js file.

function init_MobileMenu(){

    $('body')
    .on('click','#hamburger-icon',function(e){
      e.preventDefault();
      $(this).toggleClass('active');
      $('body').toggleClass('opened-nav-animate');
      setTimeout(function(){
        $('body').toggleClass('opened-nav');
      }, 100)

    });

    $('.open-submenu').on('click', function(e){
      e.stopPropagation();
      e.preventDefault();
      $( this ).closest('li').toggleClass('active-menu-item');
      $( this ).closest('li').children( '.sub-menu-dropdown, .engo-megamenu-wrapper' ).slideToggle();
    });

    $(window).resize(function(){
      var $navHeight = $(window).height() - $('.navbar-container').height();
      $('.main-nav-mobile').css({'max-height': $navHeight});
    });

  }

I add a link to my website here: Link to Website


text:
Q: Tweepy Twitter get all tweet replies of particular user I am trying to get all replies of this particular user. So this particular user have reply_to_user_id_str of 151791801. I tried to print out all the replies but I'm not sure how. However, I only manage to print out only 1 of the replies. Can anyone help me how to print out all the replies?
My codes are:
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
    for item in page:
            if item.in_reply_to_user_id_str == "151791801":
                print item.text
                a = api.get_status(item.in_reply_to_status_id_str)
                print a.text

A: user_name = "@nameofuser"

replies = tweepy.Cursor(api.search, q='to:{} filter:replies'.format(user_name)) tweet_mode='extended').items()

while True:
    try:
        reply = replies.next()
        if not hasattr(reply, 'in_reply_to_user_id_str'):
            continue
        if str(reply.in_reply_to_user_id_str) == "151791801":
           logging.info("reply of :{}".format(reply.full_text))

    except tweepy.RateLimitError as e:
        logging.error("Twitter api rate limit reached".format(e))
        time.sleep(60)
        continue

    except tweepy.TweepError as e:
        logging.error("Tweepy error occured:{}".format(e))
        break

    except StopIteration:
        break

    except Exception as e:
        logger.error("Failed while fetching replies {}".format(e))
        break

A: First, find the retweet thread of your conversation with your service provider:
# Find the last tweet
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
    for item in page:
        if item.in_reply_to_user_id_str == "151791801":
            last_tweet = item

The variable last tweet will contain their last retweet to you. From there, you can loop back to your original tweet:
# Loop until the original tweet
while True:
    print(last_tweet.text)
    prev_tweet = api.get_status(last_tweet.in_reply_to_status_id_str)
    last_tweet = prev_tweet
    if not last_tweet.in_reply_to_status_id_str:
        break

It's not pretty, but it gets the job done.
Good luck!


text:
Q: TestCases is not passing, while the console.log's are correct The problem is below
/* Write a program to build a `Pyramid of stars` of given height */

const buildPyramid = () => {
    // Write your code here
};

/* For example,
INPUT - buildPyramid(6)
OUTPUT -
     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

*/

module.exports = buildPyramid;

I added the code to get the desired pattern as below
const buildPyramid = (n) => {
        var output;
    if(Number.isInteger(n)){
        for(var i=1; i<= n; i++){
            var output =  ' '.repeat(n-i)+'* '.repeat(i)+' '.repeat(n-i);
            console.log(output);
            return output;
       }

    }else{
        console.log('Not a number');
        return '';
    }
};

module.exports = buildPyramid;

This is the test cases provided
const chai = require('chai');
const expect = chai.expect;
const pyramid = require('../solutions/q1_pyramid_of_stars.js');

describe('Testing - pyramid_of_stars', () => {
    it('module return type test case', (done) => {
        expect(typeof pyramid).to.deep.equal('function');
        done();
    });

    it('positive test case for odd count of height', (done) => {
        expect(pyramid(5)).equal(
            '     *  \n    * *  \n   * * *  \n  * * * *  \n * * * * *  \n');
        done();
    });

    it('positive test case for even count of height', (done) => {
        expect(pyramid(6)).equal(
            '      *  \n     * *  \n    * * *  \n   * * * *  \n  * * * * *  \n * * * * * *  \n');
        done();
    });

    it('negative test case', (done) => {
        expect(pyramid('invalid value')).to.deep.equal('');
        done();
    });
});

But I'm missing something, due to which, all the test cases are failed, as I think, I'm not passing the resultant output, can you help me what is that I'm missing
Testing - pyramid_of_stars
    √ module return type test case
    *
    1) positive test case for odd count of height
     *
    2) positive test case for even count of height
Not a number
    √ negative test case

  2 passing (22ms)
  2 failing

  1) Testing - pyramid_of_stars
       positive test case for odd count of height:

      AssertionError: expected ....
      + expected - actual

      -    *
      +     *
      +    * *
      +   * * *

      at Context.it (test\q1_pyramid_of_stars.spec.js:12:22)

  2) Testing - pyramid_of_stars
       positive test case for even count of height:

      AssertionError: expected ' ...
      + expected - actual

      -     *
      +      *
      +     * *

      at Context.it (test\q1_pyramid_of_stars.spec.js:18:22)

when I run the code setting the value on n as local variable, it is getting desired output.

A: You're returning from a for loop, which is not required
As you can see from your output:
 + expected - actual

      -    *
      +     *
      +    * *
      +   * * *

Only the first row is what you actually return
This is because of your for loop:
for(var i=1; i<= n; i++){
    var output =  ' '.repeat(n-i)+'* '.repeat(i)+' '.repeat(n-i);
    console.log(output);
    return output;
}

Your for loop is not a function, so when you return, it returns from buildPyramid.
Either your test needs to mock the console.log, or build up the string. Here are two options for building up th string:
(old way)

function buildPyramid(n) {
  // create a variable outside of the for loop
  let pyramid = '';
  for (var i = 1; i <= n; i++) {
    var output = ' '.repeat(n - i) + '* '.repeat(i) + ' '.repeat(n - i);
    console.log(output);
    //update outer variable
    pyramid += `\n ${output}`;
  }
  // return it after the for loop is finished
  return pyramid;
}

console.log(buildPyramid(6))

(modern way)

const pyramidLevel = (level, totalLevels) => ' '.repeat(totalLevels - level) + '* '.repeat(level) + ' '.repeat(totalLevels - level)

// reduce an array of size n
const pyramid = n => Array.from(Array(n))
  .reduce((pyramid, value, level) => {
    // for each element in the initial array
    // append the new pyramid level to your previous state
    pyramid += `\n ${pyramidLevel(level, n+1)}`;
    return pyramid;
    // the last argument of reduce is your 'initial' state
  }, '')

console.log(pyramid(6));

Either way works but I prefer the modern way for various reasons, mainly that you don't need a variable to exist out side of the main scope you care about.


text:
Q: libnih-dbus1:amd64 and libnih1:amd64 update errors after 22.04 upgrade recently moved from 20.04 to 22.04.
Here is what I am getting. I forced removal via dpkg and did a -f with apt but can't get past the error.
Any thoughts? Thank you in advance.
Calculating upgrade... Done
The following packages have been kept back:
  gcc-10-base gcc-10-base:i386
The following packages will be upgraded:
  libnih-dbus1 libnih1
2 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
Need to get 0 B/63.0 kB of archives.
After this operation, 2,048 B of additional disk space will be used.
Do you want to continue? [Y/n] y
dpkg: error processing archive /var/cache/apt/archives/libnih-dbus1_1.0.3-12build1_amd64.deb (--unpack):
 package libnih-dbus1:amd64 (1.0.3-12build1) with field 'Multi-Arch: no' is not co-installable with libnih-dbus1 which has multiple installed instances
dpkg: error processing archive /var/cache/apt/archives/libnih1_1.0.3-12build1_amd64.deb (--unpack):
 package libnih1:amd64 (1.0.3-12build1) with field 'Multi-Arch: no' is not co-installable with libnih1 which has multiple installed instances
Errors were encountered while processing:
 /var/cache/apt/archives/libnih-dbus1_1.0.3-12build1_amd64.deb
 /var/cache/apt/archives/libnih1_1.0.3-12build1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: I had the same problem after upgrading. I solved this way:
sudo apt purge libnih1:i386 libnih-dbus1:i386 && sudo apt upgrade -y

I found the solution here: https://bugs.launchpad.net/ubuntu/+source/libnih/+bug/1948346


text:
Q: computational complexity exercise I'm reading "Data structures and algorithms" from Aho, Hopcroft & Ullman, and I'm confused with exercise 1.12 B:
Which is the computational complexity (expressed in Big O notation) of this Pascal procedure?
procedure mysterious( n: integer );
    var
        i, j, k: integer;
    begin
        for i := 1 to n - 1 do
             for j := i + 1 to n do
                 for k := 1 to j do
                    {mysterious statement of O(1)}
    end

Could you please help me?
Thanks!

A: It's O(n3). The big-O shows how execution time (or memory or whatever) is proportional to the size of the task (the proportionality coefficient is omitted).
In this cases the inner statement is executed times proportional to (n3). i runs from 1 to (n-1) - so everything inside the outer cycle is executed (n-1) times. j runs on average from (n/2) to (n) - so everything inside is executed (n-1)* (n/2) times. k runs on average from 1 to (3/4* n). This gets (n-1)* (n/2)* (3/4*n-1) executions of the inner statement. This is O(n3).


text:
Q: Get Acl from powershell and GetAccessControl from c# throw errorcode 50 for a folder created in NFS drive I am able to create folder in a NFS drive manually.  Say E drive and folder name is checkwrite
but when I run Get-Acl E:\checkwrite , I get the following exception:
Get-Acl : Method failed with unexpected error code 50.
At line:1 char:1
+ Get-Acl
+ ~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-Acl], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetAclCommand

When I run GetAccessControl over the folder from c# code ,  I get
Exception Message:  Method failed with unexpected error code 50.
Stack trace:
at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext)
  at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory)
  at System.Security.AccessControl.DirectorySecurity..ctor(String name, AccessControlSections includeSections)
  at System.IO.DirectoryInfo.GetAccessControl()

https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-?redirectedfrom=MSDN
from here, it looks like request is not supported.
but If i run the same command for local drive like folders in C, it works.
Any ideas here? How to debug this?


text:
Q: MySQL and Wicket: perform multiple queries parallel I have Wicket (8.6) application which access a MySQL (5.7) database. The mysql connection is established as follows in the spring-context.xml:
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"
    destroy-method="close">
    <property name="dataSourceClassName" value="com.mysql.cj.jdbc.MysqlDataSource" />
    <property name="maximumPoolSize" value="5" />
    <property name="maxLifetime" value="90000" />
    <property name="idleTimeout" value="90000" />
    <property name="connectionTimeout" value="90000" />
    <property name="dataSourceProperties">
        <props>
            <prop key="url">jdbc:mysql://${db.url}/${db.name}?useGmtMillisForDatetimes=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8</prop>
            <prop key="user">${db.username}</prop>
            <prop key="password">${db.password}</prop>
            <prop key="prepStmtCacheSize">250</prop>
            <prop key="prepStmtCacheSqlLimit">2048</prop>
            <prop key="cachePrepStmts">true</prop>
            <prop key="useServerPrepStmts">true</prop>
        </props>
    </property>
</bean>

I have the problem that I need to perform a very long SQL query which can easily take several minutes depending on the selected time range. I have expirienced that while the query is executed that the whole wicket application slows down to the point, that no other query is executed anymore. BTW: the long query is just a reading query. So it should not lock a table.
I would appreciate if anybody could help me to improve the connection between wicket and the mysql so that I can still run multiple queries while the long query is executed. I am not very familiar with the configuration of MySQL
Here are some settings from the my.cnf file:
skip-external-locking
innodb_file_per_table   = 1
innodb_file_format = Barracuda
internal_tmp_disk_storage_engine=MyISAM
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
query_cache_limit   = 1M
query_cache_size        = 16M

A: The problem you experience is that you keep the HTTP connection during the long period of SQL Select operation.
Wicket allows at most one request to a Page instance. I.e. once you click the button/link Get data it will make an HTTP request to a particular page instance (identified by the page id parameter in the url, ?123&...) and until the SQL operation returns the user cannot make another request to the same page instance. The user can make requests to other page instances or create new ones though!
How to solve the problem ?

*

*Change your button/link #onClick() callback method to make an asynchronous request to MySQL, i.e. in a new thread. This way the HTTP processing thread can continue and return an empty response.

*Store the DB result in some temporary place, e.g. in-memory, in temporary DB table, ...

*Show the data once it is available

*

*An easy way is to use AbstractAjaxTimerBehavior to poll every few seconds for the DB result. Once the result is ready just render it by updating the model of some invisible Wicket Component, like DataTable, and show it via AjaxRequestTarget#add(table)

*Use Wicket Native WebSocket to send the DB result as soon as possible. This way there is no need to store the result temporarily. You can even stream it


text:
Q: CSS Grid Display is Causing Tables to Have Disproportionate Heights In React, I am mapping tables, each with an unknown number of elements, into a container. Here is my css:
.markets-container {
  margin: 12.5px 0 0 0;
  min-height: 430px;
  max-height: 430px;
  overflow: auto;
  display: grid;
  grid-template-columns: auto auto;
  grid-column-gap: 10px;
}

Most of them look tidy, however there are cases when an element on the left (or right) changes height to match the element next to it. Look at the example of Over Under 0.5:

A more extreme example below:

Here is the relevant JSX:
 <Card.Body className="markets-container"> { filteredMarkets.map((market) => (

          {market.marketName}

 {market.selections.map((selection) => (

          {selection.name}
          { selection.price.toFixed(2) }

 ))}

 )) )} </Card.Body>

Is there a way to fix these unequal heights?

A: You can try Flexbox too, just use properties from here https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
Or you can try for Positions too, give the parent element relative, while the inner content absolute and give bottom, top, right or left.


text:
Q: VS2005 Setup and Deployment with Sharepoint i have project in C#, ASP.Net and SharePoint. i want to deploy it usung VS2005 Setup and Deployment tool (As i am not allowed to use any otther software). Can i deploy the Sharepoint part like webparts in VS2005. please tell me what steps i have to take for sharepoint.
All Suggestions are welcome.
Thanks in advance

A: In short using the VS2005 Setup & Deployment for deploying items to SharePoint is not recommended or not supported.
SharePoint by itself has it well know deployment way called SharePoint Solutions or WSP file. Almost all the items you will want to deployed to SharePoint can be done using WSP(this includes WebPart as well, not only webpart it will allow to add a safe control entry to WebConfig as well). As per your question you are not allowed to use any other tool. To create WSP solution you will not need any extra tool. You can create a WSP file just with notepad (ddf file) & makecab.exe (its avaliable in most of  the windows OS).
If you want to make it life simpler try out WSPBuilder and to install the WSP to sharepoint you can use the STSADM command or SharePointInstaller I have been using these tools for past 3 years and they work like charm.
You also have another option of doing it in the Visual Studio just by installing this template VSeWSS version 1.2!


text:
Q: iOS 9 : SecItemCopyMatching returns successful status code but key is nil I am trying to import private key into keychain usingSecItemAdd method returns OSStatus 0 but when I try to retrieve that key from key chain using SecItemCopyMatch, It returns nil data but OSStatus is 0 means success
Please refer from Apple developer forum link

A: The bug occurs due to malformed public key refer https://forums.developer.apple.com/thread/15129
If you use Basic Encoding Rules library here's the solution.
To fix your public key you need to insert nil byte before modulus data.
https://github.com/StCredZero/SCZ-BasicEncodingRules-iOS/issues/6#issuecomment-136601437
P.S. For me fix was as simple as:
const char fixByte = 0;
NSMutableData * fixedModule = [NSMutableData dataWithBytes:&fixByte length:1];
[fixedModule appendData:modulusData];

A: Thank you! you're my hero!
In my case.

*

*Before
NSData *modBits = [[NSData alloc] initWithBase64EncodedString:mod options:NSDataBase64DecodingIgnoreUnknownCharacters];

*After
const char fixByte = 0;
NSMutableData * modBits = [NSMutableData dataWithBytes:&fixByte length:1];

NSData *tmpmodBits = [[NSData alloc] initWithBase64EncodedString:mod options:NSDataBase64DecodingIgnoreUnknownCharacters];

[modBits appendData:tmpmodBits];


text:
Q: Why is the image of a compact operator separable? Let $A$ and $B$ be normed vector spaces and let $S\in \mathscr{K}(A,B)$ be a compact operator.

Question: How does it follow that the image of $S$ is separable?

Thanks for the help.

A: The space is a countable union of balls centered in zero:
$$A = \bigcup_{n\in N}B(0,n).$$
The image of $B(0,n)$ is precompact, therefore, separable. Countable union of separable sets is separable.

A: *

*A countable union of separable sets is separable (if $S_j$ is separable, let $\left(x^{j}_n\right)_{n\geqslant 1}$ be a dense sequence in $S_j$; then $\left\{x_n^{j},n,j\geqslant 1\right\}$ is countable and dense in $\bigcup_{j\geqslant 1}S_j$).

*A subset $K$ with compact closure is separable (consider the covers $\left(B\left(x,n^{-1}\right)\right)_{x\in K}$).

*$A=\bigcup_{j\geqslant 0}B\left(0,j\right)$ and $S(A)=\bigcup_{j\geqslant 0}S\left(B\left(0,j\right)\right)$.


text:
Q: Disabling the NavBar Edit Button I have a UITableView. On my navbar I have an edit button. I want to be able to enable and disable it depending on certain conditions. For instance, when the user deletes the last of a certain type of row I want to gray out the Edit button as there are no more of these rows to delete.
What I do at the moment is check in
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
to see if I want to disable the edit button (as this seems the most sensible place to do it since the user can only delete these rows with the red delete icon). I then call:
[self.tableView setEditing:NO animated:NO];
[self.navigationItem.leftBarButtonItem setEnabled:NO];

to gray-out the edit button. It works but the title of the edit button is still 'Done' and not 'edit'. Also, if the user adds some rows back and I check to see if I should enable the edit button again - I find that the editing mode is still YES (i.e. the edit button is blue coloured when re-enabled).
How should I approach this?

A: Are you using a navigationcontroller? If so, try setting the editing on the controller:
[self.navigationController setEditing:NO animated:NO];


text:
Q: Gnome crashes on Shutter screencap and closing of VLC player I have a problem with my Fedora 24 installation:
On some specific UI Action, the gnome shell crashes. Two of the actions fail nearly every time:
Closing the VLC player while it is playing a video and attemping to take a screen-selection with Shutter.
I am running Fedora on a notebook with the latest Intel graphic drivers provided by the distribution. The notebook has also an Nvidia graphics card and I was once running it on the proprietary Nvidia driver, but I uninstalled it because it hurt the battery too much. I think the driver might have left some garbage which causes the problems. (I uninstalled it via the official executable, though).
Here is a journalctl output just before such a crash: http://pastebin.ca/3720387
There are some errors, but I don't really know what they mean and Googling them does not give relevant information.

A: After studying my problem for over an hour, I find a solution/workaround just a few minutes after a post to StackExchange ;)
The problem was the Gnome-Extension "TopIcons". I have been using it for a long time now, but it seems to be unstable with the current version of Gnome on my system. After deactivating it, everything works fine for now.