text:
Q: A swiftUI problem: troubles on applying state property I'm trying to build a reminder using SwiftUI, which requires a timer.
My problem is, the time variables, including hour, minute, and second, could not update on the GUI because of the absence of a State variable.
While in my case, I don't know how to translate the binding variable times, which firstly go through the method ensure it is a two-digit String, to a State variable. The body variable doesn't allow me to do it inside, and I could not use the binding variable and function outside either. What should I do?
import SwiftUI

struct PresentView: View {
    @Binding var times: DataStorage
    @State private var hourOut = "" // Stuck at here
    @State private var AlertPresent = false
    @State private var timerRun = false

    let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()

    func DigitPresent(time: Int) -> String {
        guard time > 9 else {
            return "0\(String(time))"
        }
        return String(time)
    }

    var body: some View {
        VStack {
            Text("\(DigitPresent(time: times.hour)) : \(DigitPresent(time: times.minute)) : \(DigitPresent(time: times.second))")
                .font(.largeTitle)
                .fontWeight(.bold)
                .padding(.bottom)
                .onReceive(timer, perform: { _ in
                    if (timerRun == true) {
                        if (times.second > 0) {
                            times.second -= 1
                        } else if (times.minute > 0) {
                            times.minute += 59
                            times.minute -= 1
                        } else if (times.hour > 0) {
                            times.minute += 59
                            times.second += 59
                            times.hour -= 1
                        } else {
                            AlertPresent = true
                            timer.upstream.connect().cancel()
                        }
                    }
                })
                .alert(isPresented: $AlertPresent, content: {
                    Alert(title: Text("Time over"), message: nil, dismissButton: .default(Text("OK"), action: {
                        AlertPresent = false
                    }))
                })
            Button(action: {
                timerRun = true
            }, label: {
                Text("Start/Stop")
            })
        }
    }
}

struct PresentView_Previews: PreviewProvider {
    static var previews: some View {
        PresentView(times: .constant(DataStorage.data[0]))
    }
}

Now I'm trying to apply EnvironmentObject into this view. While the problem is, there are other views using binding property variable using a NavigationView links to this View, which cause an error of false datatype:
struct SetView: View {
    @Binding var cards: [DataStorage]
    @State private var sheetPresent = false
    @State private var newReminder = DataStorage.dataOutput()

    var body: some View {
        List {
            ForEach (cards) { card in
                NavigationLink(destination: PresentView(times: connect(to: card))) {
                    CardView(info: card)
                }
                .listRowBackground(card.color)
            }
        }
        .navigationTitle("information")
        .navigationBarItems(trailing: Button(action: {
            sheetPresent = true
        }, label: {
            Image(systemName: "plus")
        }))
        .sheet(isPresented: $sheetPresent, content: {
            NavigationView {
                EditView(storedData: $newReminder)
                    .navigationBarItems(leading: Button("Delete", action: {
                        sheetPresent = false
                    }), trailing: Button("Add", action: {
                        let information = DataStorage(title: newReminder.title, hour: newReminder.hour, minute: newReminder.minute, second: newReminder.second, color: newReminder.color)
                        cards.append(information)
                        sheetPresent = false
                }))
            }
        })
    }
    private func connect (to card: DataStorage) -> EnvironmentObject<DataStorage> {
        guard let cardNumber = cards.firstIndex(where: {$0.id == card.id}) else {
                fatalError("Can't find card")
        }
        return $cards[cardNumber] // The error starts here
    }
}

What should I do? To fix the connect function or change the "card" variable's property?

A: I can't see your DataStorage variable, but I would say make it a class that conforms to @ObservableObject, and then apply @Published to hour, minute, second.
Then declare times as @ObservedObject rather than @Binding .
I would also move the logic that you have in your onReceive into the DataStorage - your view should only be concerned with telling it to update, not how.


text:
Q: Prove $ \sum_{1\leq k < n} k^{\underline{m}}=\frac{n^{\underline{m+1}}}{m+1} $ by induction on $m$ I want to prove by induction the following sum:
$$ \sum_{1\leq k < n} k^{\underline{m}}=\frac{n^{\underline{m+1}}}{m+1} $$
but induction should be on $m$. Any hint will be helpful.
EDIT: $ k^{\underline{m}}= k (k-1) \cdots (k-m+1)$

A: The finite difference operator $\Delta$ on sequences $f: \mathbb{N} \to \mathbb{R}$ is defined by $\Delta(f)(n) = f(n+1) - f(n)$. This operator has inverse given by the "definite-sum" operator $\Sigma$, taking a sequence $g$ to the sequence $\Sigma(g)(n) := \sum_{k = 0}^{n-1} g(k)$. We have that $\Delta \circ \Sigma$ is the identity operator, and the fact that $\Sigma\circ \Delta$ acts as the identity on functions $f$ with $f(0) = 0$ is essentially the method of telescoping sums.
Let $\binom{x}{k} = \frac{x^{\underline k}}{k!}$ be the $k^{th}$ binomial coefficient polynomial. Then the Pascal triangle identity says that as a function of $n$ we have
$$\Delta \binom{n}{k} = \binom{n+1}{k} - \binom{n}{k} = \binom{n}{k-1}$$
or if you like $\Delta \frac{x^{\underline k}}{k!} = \frac{x^{\underline{k-1}}}{(k-1)!}$, or
$$\Delta \frac{x^{\underline{m+1}}}{m+1} = x^{\underline m}$$
after a change of variable. This leads to
$$\frac{n^{\underline{m+1}}}{m+1} = \Sigma (x^{\underline m})|_{x=n} = \sum_{k=0}^{n-1} k^{\underline m}$$
as claimed.
But if you really want to see $\Delta x^{\underline{m+1}} = (m+1)x^{\underline m}$ by an induction on $m$, I would write
$$x^{\underline{m+1}} = x^{\underline m}(x-m)$$
and then apply the product rule $\Delta(f g)(n) = \Delta(f)(n) g(n+1) + f(n)\Delta(g)(n)$, together with induction on $m$.

A: Note that there is a very simple algebraic proof. The left is
$$[z^{(n-1)-m}] \frac{1}{1-z}
\left(\frac{d}{dz}\right)^m \frac{1}{1-z}.$$
The right is
$$\frac{1}{m+1} [z^{n-(m+1)}] \left(\frac{d}{dz}\right)^{m+1}  \frac{1}{1-z}.$$
Now observe that
$$ \left(\frac{d}{dz}\right)^m \frac{1}{1-z}
= m! \frac{1}{(1-z)^{m+1}}$$
which you may prove by induction if desired.
This gives for the left side,
$$[z^{(n-1)-m}] \frac{1}{1-z} m! \frac{1}{(1-z)^{m+1}} =
[z^{n-1-m}] m! \frac{1}{(1-z)^{m+2}},$$
and for the right side
$$ \frac{1}{m+1} [z^{n-(m+1)}] (m+1)!  \frac{1}{(1-z)^{m+2}}
= [z^{n-1-m}] m! \frac{1}{(1-z)^{m+2}}.$$
The two are the same, QED.
We have used the fact that the generating function of the sum of the first $n$ terms of a sequence is obtained from the generating function of that sequence through multiplication by $1/(1-z).$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to configure CORS in API written in Play framework? I'm having very strange problem with probably CORS filter. I have react app which sends request to app (written in play framework (Scala)), catch JSON response and shows it on the screen. Both apps are deployed in azure cloud via GitHub Actions.
Console shows error (translated):
 "Same Origin Policy" doesn't let read data from "my_backend_app_here" (there is no header CORS "Access-Control-Allow-Origin").
And ok, it would be understandable but it's no matter if CORS in .conf file is disabled or enabled.
Below is my .conf file:
slick.dbs.default.profile="slick.jdbc.SQLiteProfile$"
slick.dbs.default.db.profile="slick.driver.SQLiteDriver"
slick.dbs.default.db.url="jdbc:sqlite:/ebiznes.sqlite"
slick.dbs.default.db.driver=org.sqlite.JDBC

play.evolutions.db.default.enabled=true
play.evolutions.db.default.autocommit=true
play.evolutions.db.default.autoApply=true

play.modules {
  # By default, Play will load any class called Module that is defined
  # in the root package (the "app" directory), or you can define them
  # explicitly below.
  # If there are any built-in modules that you want to disable, you can list them here
  #enabled += my.application.Module

  # If there are any built-in modules that you want to disable, you can list them here
  #disabled += ""
  enabled += "modules.SilhouetteModule"
}

play.filters.enabled += "play.filters.cors.CORSFilter"

play.filters.hosts {
  allowed = ["."]
}

play.filters.cors {
  pathPrefixes = ["/"]
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  allowedHttpHeaders = null
  supportsCredentials = true
}

include "silhouette.conf"

As you can see I accept all the hosts and prefixes.
My react app fetch looks:
export function getProducts() {

    return fetch("https://my_back_app_name_here/products").then((response) => response.json())
}

But as I said - it has no matter how it looks like. Now there are no headers, or no-cors mode etc. Sometimes it gives me 404 error.
I tried to disable CORS at my backend, but  it doesn't work as well.
Help me, it's very awkward problem.
PS: My backend app works fine with front which is running on my localhost! And this is odd too.


text:
Q: Read PDF through Java and get the HTML Content I want to read an existing PDF file, get not only the text, but also the format information like: Font (Bold, Italic),paragraphs,images, tables. Basically I want to write an HTML similar to PDF.
Is there an code library for doing this? I am looking for an Open Source Library.
Regards,
Tina Agrawal

A: Try the PDFBox or iText. They are open source, and can handle text, images ,tables,  etc.

A: If you want an exact version of the page, you may need to create an image of the page and put invisble text on it. Can can see some idea of what is possible on our blog at http://www.jpedal.org/PDFblog/2012/08/4-ways-to-convert-pdf-to-html5/ with PDF to HTML conversion.


text:
Q: I am trying to add livePerson SDK implementation and getting below error I am trying to implement the LivePerson SDK but I am getting this error. Your help is much appreciated.
Error:-E/LivePerson: [[ConnectionStateMachine_ConnectingState]]  [ERR_000000A4] Connection task IDP failed.
java.lang.IllegalArgumentException: No connectorId because EngagementDetails is null
at com.liveperson.monitoring.requests.GetEngagementRequest.handleResponse(GetEngagementRequest.kt:67)
at com.liveperson.monitoring.requests.BaseMonitoringRequest$execute$1.onSuccess(BaseMonitoringRequest.kt:94)
at com.liveperson.monitoring.requests.BaseMonitoringRequest$execute$1.onSuccess(BaseMonitoringRequest.kt:83)
at com.liveperson.infra.network.http.request.HttpRequest.reportSuccess(HttpRequest.java:81)
at com.liveperson.infra.network.http.request.HttpRequest.processResponse(HttpRequest.java:50)
at com.liveperson.infra.network.http.HttpHandler$1.onResponse(HttpHandler.java:120)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
// Implemented code below.
public void startUnauthFlow() {
    String brandID = "13453456";
    String appInstallID = "3c565659-72e3-4023663349-259a20c380d4";
    String APP_ID = "com.test.app";

    final MonitoringInitParams monitoringInitParams = new MonitoringInitParams(appInstallID);
    LivePerson.initialize(this, new InitLivePersonProperties(brandID, APP_ID, monitoringInitParams, new InitLivePersonCallBack() {
        @Override
        public void onInitSucceed() {
            LPAuthenticationParams lpAuthenticationParams = new LPAuthenticationParams(LPAuthenticationType.UN_AUTH);

            LivePerson.showConversation(HelpSupportActivity.this, lpAuthenticationParams, new ConversationViewParams(false));

            ConsumerProfile consumerProfile = new ConsumerProfile.Builder()
                    .setFirstName("Sanjeev")
                    .setLastName("kumar")
                    .setPhoneNumber("")
                    .build();
            LivePerson.setUserProfile(consumerProfile);
        }

        @Override
        public void onInitFailed(Exception e) {
            Log.d("LivePersion","Exception"+e+"....Message....."+e.getMessage());
        }

    }));
}


text:
Q: Using $_GET to create multiple pages automaticly with a loop please look the following code:
<?php
if ($_GET['picture'] == 1) {
    echo "";
} else if ($_GET['picture'] == 2) {
    echo "";
} else if ($_GET['picture'] == 3) {
    echo "";
}
?>

Now, when I click a link like index.php?picture=1, the picture 1.jpg will appear. But, when I have a thousand of these, I don't want to create every If statement myself: so how to I loop through this? How can I create a loop so these are automatically created?

A: You can include the value inside of the echo'd string. Just check to make sure its less than your maximum (1000 or whatever):
$picture = intval($_GET['picture']);
if (picture > 0 && $picture < maximum) {
  echo "";
}

A: You can try this, make sure to stereotype the $_GET value as an integer or you can have some serious XSS problems.
<?php
$picnum=(int)$_GET['picture']; // make sure the value is a number to avoid XSS
echo "";
?>

A: $picture = isset($_GET['picture']) ? (int)$_GET['picture'] : 0;
if($picture)
    echo '';


text: Q: Can every recursive problem be solved by dynamic programming I'm a newbie in DSA and I just realized that all of the DP problems have recursive solutions. By the way I was wondering if there can be always a dp solution for all of recursive problems? if so, then why don't we give up on divide and conquer and just use dp?


text:
Q: How can I use Lucene to search for Xml documents? I'm using Lucene to search through an index of XML documents. I'm supposed to look for documents that have certain words inside certain tags. What would be the best way to go about this?
I tried to use RegexQuery with something like "tag.*?word.*?tag", but that returned no results.
To clarify, and example of an XML:
<?xml version="1.0" encoding="utf-8"?>
<Legislation>
    <ENTRY COLNAME="COL1">
    <LegBody_1_1 ID="KEY_3">
        <ParagraphNum REFID="284:1" JUMP_LINK_KEY="0">1. </ParagraphNum>In the following pragraphs - </LegBody_1_1>
        <LegBody_1_2 ID="KEY_4">
            <Term>"Legal Guardian" </Term>
            <Definition> - a person to whom legal title to property is entrusted to use for another's benefit; </Definition>
        </LegBody_1_2>
        <LegBody_1_2 ID="KEY_5">
            <Term>"Authority" </Term>
            <Definition> - Any civil servant appointed by the department head or minister; </Definition>
        </LegBody_1_2>

.... more tags..

</Legislation>

A search looking for the word "legal" in the tag "definition" ("definition.*?legal.*?definition") should return this document.
Any ideas?

A: I'd have a look at Parsing, indexing, and searching XML with Digester and Lucene.

A: I'd also explore native XML databases.  eXist-db (http://exist-db.org) has Lucene built in, so you can keep your XML intact and query the structure with XQuery while applying Lucene indexes.


text:
Q: Why is gradient clipping not supported with a distribution strategy in Tensorflow? It looks like gradient clipping is not supported using a distribution strategy
https://github.com/tensorflow/tensorflow/blob/f9f6b4cec2a1bdc5781e4896d80cee1336a2fbab/tensorflow/python/keras/optimizer_v2/optimizer_v2.py#L383

("Gradient clipping in the optimizer "
"(by setting clipnorm or clipvalue) is currently "
"unsupported when using a distribution strategy.")

Any reason for this? I am tempted to define a custom def _minimize(strategy, tape, optimizer, loss, trainable_variables): with direct clipping the gradients.

A: GitHub user tomerk wrote:

There's two possible places to clip when you have distribution
strategies enabled:

*

*before gradients get aggregated (usually wrong)

*after gradients get aggregated (usually right & what people expect)

We want it working w/ the second case (clipping after gradients are
aggregated). The issue is the optimizers are written with clipping
happening in the code before aggregation does.
We looked into changing this, but it would have required either:

*

*api changes that break existing users of optimizer apply_gradients/other non-minimize methods

*changing the signatures of methods optimizer implementers need to implement, breaking existing custom optimizers

So rather than:

*

*quietly doing clipping in the wrong place

*increasing churn & breaking existing users or existing custom optimizers just for this individual feature

We instead decided to leave this disabled for now. We'll roll support
for this into a larger optimizer refactoring that solves a larger set
of issues.

This has now been implemented.


text:
Q: Understanding a step in an inductive proof that $n$ hyperplanes in $\mathbb{R}^d$ determine $\sum_{0\leq i\leq d}\binom{n}{i}$ cells ($d$-faces) In the book Lecture Notes on Discrete Geometry by Jirka Matousek, in page 127, a theorem is proved:

The number of cells ($d$-faces) in a simple arrangement of $n$ hyperplanes in $\mathbb{R}^d$ equals $\Phi_d(n)=\sum_{0\leq i\leq d}\binom{n}{i}$.

They prove it for $n=d=1$, assume the equation for dimension $d$ with $n-1$ hyperplanes. The step I don't understand is:

Since we assume general position, the $n-1$ previous hyperplanes divide the newly inserted hyperplane $h$ into $\Phi_{d-1}(n-1)$ cells by the inducative hypothesis.

Why is it true?
Clarifications:

*

*For a finite set of hyperplanes $H$ in $\mathbb{R}^d$, the cells of $H$ are the connected components of $\mathbb{R}^d \setminus \bigcup H$.

*$H$ is in a simple arrangement if and only if $H$ is in a general position, which means that the intersection of every $2\leq k\leq d+1$ hyperplanes is $d-k$-dimensional.

A: Apparently the part you quote explains an inductive step over $n$, a number of hyperplanes.
Consider a 2D case first: in a general configuration the $n$-th line (1D hyperplane) intersects $n-1$ previous lines and those points (zero-dimensional) of intersections dissect the line into $n$ segments - 1D cells. Each of those segments corresponds to some polygonal cell on the plane, defined by the previous $n-1$ lines, and it dissects that polygon into two. So when constructing the configuration by adding lines, the $n$-th increment in the number of 2D cells of the plane equals the $(n-1)$-st number of 1D cells.
Then 3D: the number of solids - 3D cells in a space, added by the $n$-th 2D plane equals a number of 2D polygonal cells defined by $n-1$ lines - 1D intersections of the plane with previous planes. Each of those polygons corresponds to a single polyhedral cell of the 3D space, which becomes dissected into two by the $n$-th plane.
And generally, when you add the $n$-th, $(d-1)$-dimensional hyperplane to a configuration of $n-1$ hyperplanes in a $d$-dimensional space, you get on the new hyperplane a configuration of $n-1$, $(d-2)$-dimensional intersections with previous hyperplanes. Then each of $\bbox[lightgray]{\Phi_{d-1}(n-1)}$ cells on the $n$-th hyperplane dissects one cell in the $d$-dimensional space into two, adding $1$ to a number of cells. Hence
$$\Phi_d(n) = \Phi_d(n-1) + \bbox[lightgray]{\Phi_{d-1}(n-1)}$$


text:
Q: C++ Preprocessor string literal concatenation I found this regarding how the C preprocessor should handle string literal concatenation (phase 6). However, I can not find anything regarding how this is handled in C++ (does C++ use the C preprocessor?).
The reason I ask is that I have the following:
const char * Foo::encoding = "\0" "1234567890\0abcdefg";

where encoding is a static member of class Foo. Without the availability of concatenation I wouldnt be able to write that sequence of characters like that.
const char * Foo::encoding = "\01234567890\0abcdefg";

Is something entirely different due to the way \012 is interpreted.
I dont have access to multiple platforms and I'm curious how confident I should be that the above is always handled correctly - i.e. I will always get { 0, '1', '2', '3', ... }

A: Yes, it will be handled as you describe, because it is in stage 5 that,

Each source character set member and escape sequence in character constants and
  string literals is converted to the corresponding member of the execution character
  set (C99 §5.1.1.2/1)

The language in C++03 is effectively the same:

Each source character set member, escape sequence, or universal-character-name in character literals and string literals is converted to a member of the execution character set (C++03 §2.1/5)

So, escape sequences (like \0) are converted into members of the execution character set in stage five, before string literals are concatenated in stage six.

A: The language (C as well as C++) has no "preprocessor". "Preprocessor", as a separate functional unit, is an implementation detail. The way the source file(s) is handled if defined by so called phases of translation. One of the phases in C, as well as in C++ involves concatenating string literals.
In C++ language standard it is described in 2.1. For C++ (C++03) it is phase 6

6 Adjacent ordinary string literal
  tokens are concatenated. Adjacent wide
  string literal tokens are
  concatenated.

A: Because of the agreement between the C++ and C standards. Most, if not all, C++ implementations use a C preprocessor, so yes, C++ uses the C preprocessor.


text:
Q: Calculate the probability that the $i$-th draw returns a red ball. $R$, $B$, and $k$ are positive integers. An urn initially contains $R$ red and $B$ black balls. A ball is drawn at random and its colour is noted. The ball is put back in the urn along with k balls of the same colour. The process is repeated many times.
Calculate the probability that the second ball drawn is red?
Calculate the probability that the $i$-th draw returns a red ball?

My approach
Initially urn contains : $R + B$
$$\begin{aligned}
P(\text{Red}) &= \frac{R}{R+B} ~\textbf{and}~ P(\text{Black}) \\
& =\frac{B}{R+B}  ~\textbf{and}~ \textrm{If red is drawn then } P(\text{drawing Next Red again}) \\
&= \frac{R+k}{R+B+k}\end{aligned}$$
Similarly we have  $\displaystyle P(\text{drawing Next Black again}) = \frac{B+k}{R+B+k}$
Now,
$$\begin{aligned}
P(\text{Second Red}) &= P(\text{Red} \land \text{Red}) + P(\text{Black} \land \text{Red}) \\
&= \frac{R}{R+B}\times\frac{R+k}{R+B+k} + \frac{B}{R+B}\times\frac{R}{R+B+k} \\
&= \frac{R}{R+B+k}  \left(\frac{R+k}{R+B} + \frac{B}{R+B} \right) \\
&= \frac{R}{R+B}\end{aligned}$$
Is it correct?
And how to do the next part: probability that the $i$-th draw returns a red ball?

A: Your approach is correct.
As for how to prove the general case, consider the following trick:
Suppose that you label the initial balls with $0$. For every $n$, when you add $k$ additional balls after the $n$-th draw, you label these new balls with the number $n$.
Let $p_0 = \frac{R}{R+B}$, and for all $n > 0$ let $p_n$ be the probability that the $n$-th ball drawn is red.
Suppose that the $i$-th ball you draw has the number $j$ on it (note that $j < i$). Then the probability that it is red is equal to $p_j$. With this, you can calculate the first few $p_n$ and form a hypothesis from there that you can prove inductively.

A:
Let us think of a basic Probability concept. Suppose, the original contents of the urn are w white balls and b black balls, and that after a ball is drawn from the urn, it is replaced along with d more balls of the same color. Then the probability that the second ball drawn is white is $\frac{w}{w+b}$, i.e. that this probability does not depend on d. Again, the probability that the second ball drawn is Black is $\frac{b}{w+b}$, i.e. this probability also does not depend on d. Please go through the diagram, where, the required probability does not depend on additional balls denoted by d has been established. Therefore, the probability that the 100th or nth ball you pick is black is  $\frac{b}{w+b}$ and White is $\frac{w}{w+b}$


text:
Q: Javascript Thread Safe I have a buffer:
websocketbuffer = []

Client event from html:
<button type="button" onclick="buttonClicked()"></button>
<script>
    function buttonClicked() {
    // add some data to websocketbuffer
}
</script>

Websocket receive event:
ws.onmessage = function (event) {
    // update some data inside websocketbuffer
}

The task:
websocket.onopen = function (event) {
    setInterval(wsRun, 1000);
};
function wsRun() {
    // delete or update some data inside websocketbuffer
}

As you can see above, there is access to the same buffer from 3 different places. In such a case, can another function run before one function completely finish his job on websocketbuffer?
How should I design the software in such a situation?
EDIT:
Actually, what I want to ask is during the for loop(websocketbuffer) in one function, Can the other function change this array?
function wsRun() {
    for ( let i = 0; i < websocketbuffer.length; i++ ) {
        //lets say i = 0
        websocketbuffer[0] = ... //Update array
        //User has clicked to button and In this point Does buttonClicked() function invoke or some data comes from websocket Does ws.onmessage function runs ? or waits to finish wsRun function?
        //Is this possible?
    }
}


text:
Q: Stop application while doing some operations I created an application that search a word in each file contained in a directory.
I wanted to implement a way to stop searching.
I created a method that calls other diffent methods according to each file type it find in the directory.
I have worked in one single class and I created a JButton that request stop searching:
 private void jButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
            System.out.println("Requesting stop");
    }

I need a way to stop the method that search into the directory, suppose my method is search(directory);.
I tried to search(directory); in this way:
private Thread a;
a = new Thread(new Runnable() {
     @Override
     public void run() {
       search(directory);
     }
        }
  );

and then while searching I click the jButton to stop search:
 private void jButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
            System.out.println("Requesting stop");
            a.stop();
    }

It works but I have been reading many posts about this and it's not a good way to stop a thread.
So any alternative? Could you give an example?
I have also tried this:
java.util.TimerTask timerTask;
ScheduledThreadPoolExecutor scheduledThread = new ScheduledThreadPoolExecutor(10);
timerTask = new  java.util.TimerTask() {
        @Override
        public void run() {
            search(directory);
        }
    };
scheduledThread.schedule(timerTask, 3, TimeUnit.MILLISECONDS);

and then in jButtonActionPerformed:
 private void jButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
       System.out.println("Requesting stop");
       scheduledThread.shutdownNow();
    }

It works too, but in this case I'm not able to start a new search when I try to do it. I need to close and reopen application.

A: One way:

*

*The code that does the searching should be in its own class.

*Your GUI controller (for instance, the ActionListener) will create an object of this class.

*When your GUI wishes for the Search class to do searching, it should call a method of the class, perhaps beginSearch() and do so on a background thread.

*The Search class should have a method for stopping an active search, say stopSearch() that a GUI controller can call.

*This method will probably set a boolean field, a flag, of the Search object, say called continueSearching or something similar, one that its search method intermittently checks during its searches. If the boolean is set to false, then the search should stop.

Also note that you are correct. Calling stop() on a thread is not only not recommended, but it is down-right dangerous. Please have a look at what the Thread API has to say on the subject:

Deprecated. This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.

Also please have a look at this link: Why is Thread.stop deprecated?.

Edit
You state:

the problem is that my application code is long and it will be hard to edit it like your way,...

The longer your class is, the more important it becomes to try to break it up into separate logical units. Else you'll end up with a debugging and enhancing nightmare.

i'm not an expert in programming and i'm still studying for that, that's why I wanted to know whether there was a way according to my situation.

The more you practice refactoring, the better you'll get at it and the easier it becomes. A good time to start is now.


text:
Q: Purging GNOME from system? I am trying to remove any part of GNOME from my system, and replace it with a different desktop environment. The problem is that I have no idea how to do that.
My idea was to run sudo apt-get purge gnome-*, but that seems to remove a HUGE amount of programs including blueman and network-manager which I'd like to keep.
Is it possible to remove everything gnome from my system, without removing the useful plugins that shouldn't be related to GNOME such as tlp, update-manager and so on?
NOTE: I installed Ubuntu Mate, so gnome isn't even the DE the system came packaged with. But ubuntu-gnome-desktop doesn't even exist.

A: If you are trying to replace GNOME with much more lightweight i3, it is expectable that many GUI applications depending on GNOME would be uninstalled due to dependencies, too.
Regarding your examples:

*

*blueman depends on gnome-icon-theme

*network-manager recommends network-manager-gnome
If you want to keep them, you will need to keep required parts of GNOME. And as mentioned in a comment, be sure to have a backup before trying to break doing such a serious modification to your Ubuntu installation.


text:
Q: Array_intersect returns NULL i'm trying to compare array1_ids with the cart of a customer if products of the array match those in the cart field x_name should be there if not it
should be gone.
I get the values from my cart and array1_ids but when I put them through the array_intersect it will result in NULL causing it to always return true.
Here is my code:
function wc_ninja_product_is_in_the_cart() {
/*array 1*/
$array1_ids = array( '1', '3', '5');//field that should
/*array 2*/
//$micro_ids = array( '2', '4');//fields that shouldnt come back

    // Products currently in the cart
    $cart_ids = array();
    $cart_categories = array();

    // Find each product in the cart and add it to the $cart_ids array
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $cart_product = $values['data'];
        $cart_ids[]   = $cart_product->id;
    }

    // If one of the special products are in the cart, return true.
    if ( ! array_intersect($array1_ids, $cart_ids) ) {
        echo "true: " , implode(';',$cart_ids);;//bug fixing
        return true;
    } else {
        return false;
        echo "false: " , implode(';',$cart_ids);;//bug fixing
    }
}
//Field Remover
function wc_ninja_remove_checkout_field( $fields ) {
    if ( ! wc_ninja_product_is_in_the_cart() )    {
        //removes Field x_name
        unset( $fields['billing']['x_name'] );
    }
    return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' );

A: This should work:
$hasSpecialProduct= false;
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
    $cart_product = $values['data'];
    if (in_array($cart_product->id, $array1_ids)) {
        $hasSpecialProduct = true;
    }
    $cart_ids[]   = $cart_product->id;
}

// If one of the special products are in the cart, return true.
if ( $hasSpecialProduct ) {
    echo "true: " , implode(';',$cart_ids);;//bug fixing
    return true;
} else {
    return false;
}

you can make the last part shorter:
return $hasSpecialProduct;


text:
Q: One-click compilers Do you know of any compilers that only requires one or two clicks on the source code to compile? Having to configure it to do it doesn't count, nor does having to go to a terminal and write a word or two.
Extra points are given if you can give your own view as to why so few compilers have a gui included, or just a send to compiler listing in explorer!
The reason is that I want to be able to send source to my non-programming friends. Some have sparc computers, some have x64 with multiple cores and so on.
Then they would be able to compile the code and then remove it, saving just the binary that is optimized for their computer.

A: We have CMake, Makefiles and other build systems (MSBuild). Why should compiler have a gui?
After generating a build with cmake or writing makefiles issuing 'make' is usually sufficient.

A: So few compilers have a GUI included since it is not a fundamental function of a compiler. A compiler should be usable from a command line, easily integrated into scripts/automation tools and similarly, it should be easy to make GUI tools communicate with it.
In other words, it can be used from a GUI but it is not a GUI type of tool.

A: Btw, may be it is not that you are looking for but qmake utility from qt-lib is a perfect example of "one click" tool :) It creates project and makefiles based on what files you have in current directory. It detect .ui (user interfacec), resources, headers etc... Then you have to just make, make, make...
Exept that, i mean configuration, all compilers and IDEs use one click or keypress to start compilation.
Another q is - how do u deal with the compilation errors. Error highlinght, source navigation - it`s all IDEs functions. And compiler can be a part of IDE, but not on the contraty.

A: I used to use "jikes", IBM's java compiler.  It had an incremental mode where you just had to hit return and it would compile everything that had changed.  So you'd do some coding in vi, save the file, and alt-tab over to the window with jikes in it, and hit return, and alt-tab back to the vi window.
Now I use Eclipse that compiles on the fly.  Sometimes that's good, sometimes it puts ugly red lines all over the code that you haven't finished writing so you know it's not supposed to compile.

A: I'm assuming the use of C++.
I feel like what you're really looking for is an IDE that makes compiling simpler.  I know Dev-C++ was pretty good about that.  Many production-level application probably need at least some configuration of the compiler.  That being said, I've often found that a call to "g++ *.cpp -o output.exe" works as a quick and dirty compile...though it won't work in many, many cases.  Still, when I was newer to programming most of my projects could compile using that command.

A: It's called make.
For alternatives, check this list out.

A:
Having to configure it to do it doesn't count,

Theres a logic flaw there. Either you configure it, or the installer configures it. It won't just automagically happen all on its own ;)


text:
Q: How to catch a CListCtrl column width change event? How can I catch CListCtrl column width change event in MFC? I believe there should be an OnNotify() event but I am note sure about various values and the parameters to use for message map and the event itself.
Please note that a CListCtrl column width can change by dragging the column divider or by double clicking on the header row.

A: I think the key is to understand that there is a difference in the listcontrol itself, and the header control. By using the GetHeaderCtrl() member function of the listcontrol you can get to the header control. For working with the header control, see this article: http://www.codeproject.com/KB/list/headerctrl.aspx?display=Mobile#Anchor-Handlin-41471
Hope this helps.


text:
Q: CCLabelBMFont crashing due to a missing image message I'm getting an exception saying that the image cannot be nil on this line:
   CCLabelBMFont *label =  [CCLabelBMFont labelWithString:@"5" fntFile:@"weaponnumbers.fnt"];

What am I doing wrong?  Am I supposed to specify the PNG somewhere different?  I have it at the root of the project.
-(CCTexture2D*) addImage: (NSString*) path
{
    NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill");

A: Is weaponnumbers.fnt included in your target?  E.g. is it compiled into the project?
Also, I think it's unlikely you're getting an exception here - you're probably getting an exception somewhere inside one of the calls made by this call.  Try breakpointing the line before, and using the "Step In" breakpoint tool to step through the call stack and find the true nature of the exception.
I find Cocos2D exceptions to be pretty self-explanatory, when you can eventually get down to the right level of where the exception is actually being thrown.

A: A delete add and clean fixed it.
NSString stringWithContentsOfFile failing with what seems to be the wrong error code


text:
Q: Cannot set property 'styles' of undefined in next js during add less support I am trying to add support for the less file to my next js project with the antd design but getting cannot set property 'styles' of undefined. I want to customize the antd theme but that error is a blocker for me anyone have any idea please help me to solve this problem
//error screenshot

// next.config.js file
const lessToJs = require('less-vars-to-js');
const fs = require('fs');
const path =  require('path');
const withPlugins = require('next-compose-plugins');
const withLess = require("@zeit/next-less");
const withCSS = require("@zeit/next-css");
const themeVariable =  lessToJs(fs.readFileSync(path.join(__dirname, './styles/antd-custom.less'), 'utf8'));

const nextConfig = {}

module.exports = withPlugins(
    [
        [
            withLess({
                lessLoaderOptions: {
                    javascriptEnabled: true,
                    modifyVars: themeVariable,
                },
                webpack: (config, {isServer}) => {
                    if (isServer) {
                        const antStyles = /antd\/.*?\/style.*?/;
                        const origExternals = [...config.externals];
                        config.externals = [
                            (context, request, callback) => {
                                if (request.match(antStyles)) return callback();
                                if (typeof origExternals[0] === "function") {
                                    origExternals[0](context, request, callback);
                                } else {
                                    callback();
                                }
                            },
                            ...(typeof origExternals[0] === "function" ? [] : origExternals),
                        ];

                        config.module.rules.unshift({
                            test: antStyles,
                            use: "null-loader",
                        });
                    }
                    // config.resolve.alias["relay"] = path.join(
                    //     __dirname,
                    //     "__generated__",
                    //     "relay"
                    // );
                    return config;
                }
            }),
        ],
        [withCSS],
    ],
    nextConfig
)

//antd-custom.less file
@import "./variables.less";

@primary-color: @green-6;
@processing-color: @green-6;
@font-family: Inter, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
@link-hover-decoration: underline;
@input-hover-border-color: @green-6;
@border-radius-base: 5px;
@label-color: @gray-6;
@table-header-bg: @gray-2;
@table-header-color: @gray-6;
@menu-item-active-bg: @gray-1;
@menu-item-color: @gray-6;
@tooltip-bg: @gray-10;
// Input
@input-border-color: @gray-4;
@input-placeholder-color: @gray-6;

A: I have a similar problem. I can solve with the following steps.

*

*Tell NextJs to downgrade to Webpack 4
// next.config.js
module.exports = withPlugins([...], {
   webpack5: false,
})

*Manually add the related dependencies with the proper version.
yarn add --dev webpack@webpack-4 less less-loader@5

A: You can use this zero dependency module to customize your antdesign theme in next.js project-
next-plugin-antd-less
 Features

*

*Zero Dependency on other Next.js Plugins

*Support Both Next.js & CRA Project

*Support Hot-Update After modifying Antd less vars

*Support Serverless Mode

*Support Antd Pro

 Compatibility

*

*next v12 & v11 (webpack 5, SWC or Babel)

*less v3.0+

To learn more on how to configure the webpack in next.config.js file check this article-
https://www.elvisduru.com/blog/how-to-customize-ant-design-theme-in-nextjs


text:
Q: How to prohibit access to my site directory? I have this website, example.com, and I just discovered that I can access my folders through the URL (for example, I can access the img folder using a web browser by going to http://example.com/img ). It's crazy! I'm sorry, I can't even search for the proper term in Google/StackOverflow because I don't know what it's called or what the proper term is. Also, I am using tags generously because I'm not sure what categories this would fall under.

A: put Options -Indexes in your .htaccess to prevent directory listing
... or deny from all if you want to restrict access to files

A: Add the following line to a file named .htaccess  in the root of your site with the following line
Options -Indexes

It will prevent Apache from listing the contents of the directories to your visitors and should still allow you to reference files within them (ie images) in your HTML.

A: You can do it in either two ways. First is to create an index.html file and store it in the directory, so that whenever anyone tries to navigate that directory through the URL he'll see the index.html page. And the second option would be to create a .htaccess file inside the directory and place this line of code inside it: Options -Indexes. I would recommend adding a 404 Not Found page with header informations, like what most of the websites are already doing.


text:
Q: Physics Body affects other nodes but node isn't moved I'm creating the effect of a spinning wheel with pins that hit a pointer causing the wheel to slow down eventually. In the below paragraph, Node A is a pin on the edge of the spinning wheel and Node B is the 'ticker' that hits the pins, deflects out the way and by doing so slows the wheel a little.
I have two nodes, I need these nodes to collide which each other so that one can resist the motion of the other. Node A will hit Node B which has a SKPhysicsJointSpring attached. Without the SKPhysicsJointSpring Node A hits Node B and it moves out of the way correctly so I know that the nodes themselves are set up correctly. However when I introduce the SKPhysicsJointSpring I have a strange behaviour; the nodes react correctly with their physics bodies however the node itself doesn't move and therefore it appears as if Node A overlaps Node B before being resisted by Node B's physics body.

(source: gifyu.com)
The triangle (Node B) is pinned at the dark grey circle and the two blue lines are the spring joints. When the spring joints are removed the triangle is free to move and is hit but the circles on the edge of the wheel.

A: Turns out the SKPhysicsJointSpring doesn't allow compression and therefore can never be smaller than the size it starts with! Replace with one spring joint in the middle of the ticker that extends when the ticker rotates works perfectly.


text:
Q: Can we refer to a bar of soap as a "bath accessory"? Is it correct and natural to refer to a bar of soap as a "bath accessory"?
If not, what would you call it?
I'm considering a sentence like:

The hotel offers free bath accessories/bathing products.

I'd appreciate your help.

A: "bath accessories" suggests towel holders, soap dishes and similar items.
In British English, "complimentary toiletries" would be used.

An invigorating hotel toiletries range that includes a selection of
  shampoo, soap, body lotion and shower gel.

https://www.hotel-complimentary-products.co.uk/hotel-toiletries
Things like sewing kit or shoe polish might be amenities.

Cole & Lewis Deluxe Toiletries & Amenities Welcome Pack

https://www.outofeden.co.uk/products/1234/cole-and-lewis-deluxe-toiletries-and-amenities-welcome-pack

Hotel Guest Amenities and Accessories

https://www.outofeden.co.uk/category/amenities-and-accessories

A: In the context you provide, it is helpful to look at Hotel websites:
Looking at some different hotel websites, bath products, bath amenities, or bath necessities are examples of options. To me any of these sound fine, but are ordered in decreasing preference


text:
Q: Could not load file or assembly 'netstandard, Version=2.0.0.0' only on remote server. Works on local As our development team have upgraded our project to support a special form of caching, our .NET project no longer works when put in an environment that isn't a local machine. I tried to figure out how to install .NET standard  on the server, but only came across this article, which is still on a local machine.
I have looking around and have consulted this answer on Stack Overflow, this discussion on GitHub and a bunch of other sites, but to no avail.

A: I installed .NET framework 4.7.1 on the server (it was running 4.6.1) and now it works just fine. I hope this will save someone some trouble


text:
Q: Application of homogeneous version of Nakayama Lemma I'm currently stuck in the proof of Proposition A.2.3. on page 267 of Monomial Ideals by Herzog and Hibi.
First we consider the following commutative diagram
$\require{AMScd}$
\begin{CD}
F @>{\varepsilon}>> U\\
@V \alpha VV @VV \varphi V\\
G @>{\eta}>> V
\end{CD}
Here $U,V,F,G$ are $S$-modules, $S=K[x_1,\dots,x_n]$ is the polynomial ring with coefficients over a field $K$. $F$ and $G$ are free f.g. modules, $\varepsilon$ and $\eta$ are homogeneous surjective homomorphism with $\ker(\varepsilon)\subseteq\mathfrak{m}F$ and $\ker(\eta)\subseteq\mathfrak{m}G$, and $\mathfrak{m}=(x_1,\dots,x_n)$ is the unique maximal omogeneous ideal of $S$.
On page 268, we consider the following commutative diagram
$\require{AMScd}$
\begin{CD}
F/\mathfrak{m}F @>{\overline{\varepsilon}}>> U/\mathfrak{m}U\\
@V \overline{\alpha} VV @VV \overline{\varphi} V\\
G/\mathfrak{m}G @>{\overline{\eta}}>> V/\mathfrak{m}V
\end{CD}
where the maps are the obvious one. By the costruction $\overline{\varepsilon},\overline{\varphi},\overline{\eta}$ are isomorphism, thus $\overline{\alpha}$ is an isomorphism. In order to complete the proof, one must show that $\alpha$ is also an isomorphism. The book only mentions that a homogeneous version of the Nakayama Lemma must be used. This is where I'm stuck.
This is the version I thought to use:
If $M$ is finitely generated graded $S$-module and $m_1,\dots, m_t\in M$ generate $M/\mathfrak{m}M$, then $m_1,\dots,m_t$ generate $M$.
I also know by basic tensor product isomorphism that $M/\mathfrak{m}M\cong K\otimes_S M$ for any $S$-module $M$. I don't understand how to use this to prove that $\ker(\alpha)=0$ for example.

A: $\newcommand{\m}{\mathfrak m}$
Here's a useful corollary of homogeneous Nakayama:

Suppose $M$ is a finitely generated graded $S$-module. Consider the
finite-dimensional $k$-vector space $M/\m M$ and let $n$ be its
dimension. Then $m_1,\ldots,m_n$ is a minimal set of generators of $M$
iff $\{m_1+\m M,\ldots, m_n+\m M\}$ is a basis for $M/\m M$.

As $\bar\alpha$ is an isomorphism, it takes a basis of $F/\m F$ to a basis of $G/\m G$. Since $F$ and $G$ are finite free, the above corollary implies that $\alpha$ maps a basis of $F$ to a basis of $G$.


text:
Q: AsyncStorage always returns {"_U": 0, "_V": 0, "_W": null, "_X": null} async function getTokenFromAsync() {
  const userToken = await AsyncStorage.getItem('@User_Token');
  return userToken;
}

export default {getTokenFromAsync};

Im trying to get userToken from asyncStorage but it return me this {"_U": 0, "_V": 0, "_W": null, "_X": null},
Im using react native

A: You are not resolving the Promise hence your "weird" output.
This is the way that I have my get Function defined:
  const getData = async (key) => {
    // get Data from Storage
    try {
      const data = await AsyncStorage.getItem(key);
      if (data !== null) {
        console.log(data);
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  };

You can then get the Data by calling the Function with your Key.
  await getData("yourKey")
  .then(data => data)
  .then(value => {
    a state or constant = value
    console.log("yourKey Value:  " + value)
  })
  .catch(err => console.log(err))

A: You should wait to resolve the promise where you are using it like
getTokenFromAsync().then((userToken)=>{
  console.log(userToken);
});


text:
Q: How to get all fields in VF page using custom controller? This is my Controller:
public class exportContactRecords
{
    public List <Contact> contactList { get; set; }
    String query;
    String allFields = '';
    public exportContactRecords()
    {
        String objectName = 'Contact';
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(objectName ).getDescribe().fields.getMap();
        set<string> mapset = fieldMap.keyset();
        contactList = NEW List <Contact> ();

        for ( String str:mapset )
        {

            allFields += str +', ';

        }
        allFields = allFields.removeEnd(', ');

        query = 'SELECT '+ allFields + ' FROM '  + objectName;

        System.debug('----------'+query);

        contactList = Database.query(query);
        System.debug('----------'+contactList);
    }
}

Here I am getting all the fields through this dynamic query
This is my VF page:
<apex:page Controller="exportContactRecords" ContentType="application/vnd.ms-excel#SalesForceExport.xls" >
  <apex:pageBlock >
      <apex:pageBlockTable value="{!contactList}" var="c">
               <apex:column value="{!c.LastName}"/>
     </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

Here I have taken only 1 field LastName but I want to have all the contact fields in that excel sheet.Please give me solution

A: To render the <apex:column> dynamically based on the number of fields queried, you should have a tap on number of fields queried in a list of string. Then use that list of fields to get the values from your list using <apex:repeat>
public class exportContactRecords
{
    public List <Contact> contactList { get; set; }
    String query;
    String allFields = '';
    public exportContactRecords()
    {
        String objectName = 'Contact';
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(objectName ).getDescribe().fields.getMap();
        set<string> mapset = fieldMap.keyset();
        contactList = NEW List <Contact> ();
        **List<String> lstFields = new List<String>();**
        for ( String str:mapset )
        {

            allFields += str +', ';
            **lstFields.add(str);**

        }
        allFields = allFields.removeEnd(', ');

        query = 'SELECT '+ allFields + ' FROM '  + objectName;

        System.debug('----------'+query);

        contactList = Database.query(query);
        System.debug('----------'+contactList);
    }
}

Here I am getting all the fields through this dynamic query
This is my VF page:
<apex:page Controller="exportContactRecords" ContentType="application/vnd.ms-excel#SalesForceExport.xls" >
  <apex:pageBlock >
      <apex:pageBlockTable value="{!contactList}" var="c">
        **<apex:repeat value="{!lstFields}" var="FieldLable">
            <apex:column value="{!c[FieldLable]}"/>
        </apex:repeat>**
     </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

Refer Page Block Table With Dynamic Columns In Salesforce
Hope it helps.

A: You can use Dynamic Visualforce components as explained here Dynamic Visualforce components documentation
Basically you define a Dynamic Visualforce component on your VF page. Like this:
<apex:dynamicComponent componentValue="{!thePanel}"/>

And then using apex you can add your fields to that panel.
Component.Apex.InputField inTxt = new Component.Apex.InputField(value=rec.name);
inTxt.expressions.value = "{!rec.name}";

I see you already use Describe to determine which fields to put. You can make use of that to dynamically add fields to your Panel.

A: You will use Dynamic Field Bindings Concept here
You are almost there with controller code but you may need one more list with all fields .
<apex:pageBlock title="Custom Object Fields and Data" id="fields">
<apex:pageBlockSection title="Dynamic Object">
  <apex:pageBlockTable value="{!contactList}" var="c">
  <apex:repeat value="{!listObjectFields}" var="fieldAPIName">
    <apex:outputField value="{!c[fieldAPIName]}"/>
  </apex:repeat>
  </apex:pageblocktable/>
</apex:pageBlockSection>

The controller code
 public list<Contact> contactList {get;set;}
 public List<String> listObjectFields {get;set;}


text:
Q: Twitter iOS image search by hashtag I need to search images from a certain hashtag in twitter to my iOS 6 app. I am trying to code a query that retrieves a minimal size possible response.
So, I tried to use Twitpic,  but the response is not good. it's outdated and incomplete. So, I went to the Twitter 1.0 API. The 1.1 is not good because it require user account in Twitter and a lot of my users don´t have it.
http://search.twitter.com/search.json?q=%23hashtag%20pic.twitter.com&rpp=100&include_entities=true&result_type=recent
Does have a better way to query images from twitter api? I only need the image urls, not the entire entities.

A: As Twitter and Instagram respond a big JSON, I decided to implement the logic in a server using PHP. My client send the hashtag and the server retrieve the image´s urls and send them this parameters and the next "page_id" from twitter and facebook.
It made the operation faster and more future friendly to my apps, besides avoid some "bad images".


text:
Q: Long tailed count probability distributions - with available likelihood calculation and random number generation in real world data, often (always to me) happen that for modelling count data

*

*Poisson

*Negative binomial

*multinomial

*dirichlet-multinomial

probability distribution, are not robust to outliers, as they don't have long tails. A lot have been proposed in this matter
https://arxiv.org/pdf/1504.01097.pdf

However often these problems arise, when implementing those functions in a Bayesian inference model

*

*The likelihood calculation doesn't have a closed form, and it's calculation in computationally prohibitive

*It is not clear how to generate random variables

*The implementation with mean parameter (for regression) does not exist or does not work (nominal mean is not read mean)
Thus the question is:
Does anybody have worked/implemented a functional implementation for any of these robust count functions? With likelihood calculation and random number generation process?


text:
Q: How to change script to save attachments by file name instead of by sender name? I'm using the script below.  It works well to save attachments by sender name in a specified folder.  However, if the sender names are constant, it only saves 1 of the attachments vs. all of the attachments.  I'm assuming it's a write error.  How do I update the script below to save all attachments meeting the filtered criteria by their actual attachment name instead of sender name.
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace("MAPI")
$f = $n.PickFolder()
$filepath = "c:\test"

$f.Items| foreach {$SendName = $_.Sendername
$_.attachments|foreach {
$_.filename
If ($_.filename.Contains("pdf")) {
$_.saveasfile((Join-Path $filepath "$SendName.pdf"))}}}`

Any ideas would be greatly appreciated.

A: So Lets Follow the rabbit hole here.
We can go to the Outlook Object Model, and look for Attachments Object because we see you are iterating over attachments:
$_.attachments|foreach

We see in the page:

Contains a set of Attachment objects

So we go look at the Attachment Object Page, look at Properties and we see there is a property for FileName
So to send by attachment name we can do this:
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace("MAPI")
$f = $n.PickFolder()
$filepath = "c:\test"

$f.Items| foreach {
    $FileName= $_.FileName
    $_.attachments|foreach {
        $_.filename
        If ($_.filename.Contains("pdf")) {
            $_.saveasfile((Join-Path $filepath "$FileName"))
        }
    }
}


text:
Q: Positioning of elements on page is messed up On my website, I have roughly about 4000px of height on my page. However, whenever I start to insert a new element, whether that be a
,
,  or whatever, it is getting cluttered with elements higher than I would expect. I wanted to know if there is a way to make it so that the new elements inserted will be after the previous elements, without having to mess with position. There is minimal jQuery and JavaScript as of right now, but there were several elements floated.
HTML
<!DOCTYPE html>

    <title>Final</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="../reset.css">
    <link rel="stylesheet" type="text/css" href="style.css">

    <link href="https://fonts.googleapis.com/css?family=Roboto:400,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,900" rel="stylesheet">

Colin Bruin

Home

Code

Webpages

Articles

Resume

Discover

About Me

            <svg height="5" width="100%">
                <line x1="500" y1="0" x2="1000" y2="0" style="stroke:rgb(0,0,0);stroke-width:8" />
                Sorry, your browser does not support inline SVG.
            </svg>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor eget ante in sodales. Integer lobortis eget massa in vehicula. Praesent nisl libero, viverra id tristique pretium, dictum id enim. Cras maximus, libero vitae lacinia commodo, nisl velit maximus augue, ac vestibulum ex ipsum sed ex. Donec tempor elit et nisi molestie bibendum. Etiam placerat ante ac lobortis commodo. Fusce ut massa tellus. Phasellus bibendum nisl at tellus sagittis dignissim. Ut non massa imperdiet, faucibus leo ut, pretium tortor. Nullam accumsan egestas rhoncus. Ut congue nisi rhoncus commodo molestie. Duis in sem id massa pellentesque facilisis. Aliquam ullamcorper pellentesque nulla, ac commodo arcu scelerisque id. Nulla at efficitur enim. Proin non augue nibh.

                Curabitur et ultrices sapien. Aenean fermentum massa et felis iaculis, nec aliquam est eleifend. Proin sagittis tincidunt iaculis. Fusce vel quam lectus. In et mi nec ex tempus ultricies. Etiam tortor leo, feugiat in elit vitae, fringilla rutrum nunc. Duis posuere accumsan pharetra.

                Donec ut tortor et sapien fringilla fermentum. Vestibulum tincidunt odio quis felis egestas eleifend sit amet a neque. Suspendisse a diam magna. Maecenas suscipit mauris eget ultricies imperdiet. Pellentesque lobortis faucibus viverra. Etiam porttitor mattis enim, et aliquam sem rhoncus rhoncus. Etiam tempor lobortis ultrices. Curabitur sit amet tincidunt elit, non fermentum ante. Praesent a blandit nisi. Fusce eu dui non arcu rutrum porttitor vitae sed mi. Cras vel mauris magna.

                Proin quis purus non justo bibendum dictum. Sed eu erat sit amet lectus tempor hendrerit in et tortor. Donec convallis augue quam, sit.

Resume

            <svg height="5" width="100%">
                <line x1="500" y1="0" x2="1000" y2="0" style="stroke:rgb(0,0,0);stroke-width:8" />
                Sorry, your browser does not support inline SVG.
            </svg>

Skills

HTML/CSS - Advanced

PHP - Beginner

Javascript - Proficient

jQuery - Proficient

Python - Proficient

MySQL - Advanced

1 / 3

Zionsville High School / 2008-2012 / High School Diplomal

2 / 3

Indiana University / 2012-2016 / Bachelors in Economics

3 / 3

Purdue University / 2016-2017 / Certificate of Web Development

                    ❮
                    ❯

sadglkadsgjdaskfhk

CSS
body {overflow-x: hidden;}
header {
    height: 100vh;
    width: 100%;
    background-color: rgba(255,255,255,.2);
}
header::after {
  content: "";
  background: url(http://hipnewjersey.com/wp-content/uploads/2016/12/mountains.jpg);
  background-size: cover;
  background-attachment: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;
}
header h3 {
    font-family: 'Roboto', sans-serif;
    font-size: 2.2em;
    position: relative;
    top: 20px;
    left: 3.5%;
}
nav {
    position: relative;
    left: 68%;
    top: -5px;
}
ul {list-style-type: none;}
li {
    display: inline;
    position: relative;
    margin-left: 20px;
}
ul li a {
    text-decoration: none;
    font-size: 1.2em;
    color: black;
    font-family: 'Lato', sans-serif;
    font-weight: bold;
}
ul li a:hover {opacity: .1;}
header h1 {
    position: relative;
    top: 40%;
    left: 36%;
    font-size: 7.5em;
    color: white;
    font-family: 'Roboto', sans-serif;
}
#headerNav {
    width: 100%;
    background-color: rgba(255,255,255, .9);
    height: 75px;
    position: fixed;
    z-index: 10;
}
#aboutMe {
    width: 1000px;
    height: 550px;
    position: relative;
    top: 150px;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: -50px;
    background-color: white;
    -webkit-box-shadow: 49px 43px 116px -17px rgba(196,196,196,1);
    -moz-box-shadow: 49px 43px 116px -17px rgba(196,196,196,1);
    box-shadow: 49px 43px 116px -17px rgba(196,196,196,1);
}
#pictureMe, #information {
    width: 498px;
    height: 550px;
    display: inline-block;
}
#information p {
    position: relative;
    top: -200px;
}
#section-header1 {
    margin-top: 125px;
}
.section-header  {
    font-family: 'Lato', sans-serif;
    font-size: 3.5em;
    color: black;
    position: relative;
    text-align: center;
}
svg {
    position: absolute;
    margin-top: -23px;
}
.spacing {
    margin-bottom: 120px;
    display: inline-block;
}

/*Skills*/
#resume {
    position: relative;
    top: 450px;
}
#skills {
    height: 1850px;
    width: 100%;
    margin-top: 30px;
    background-image: url("images/park-wallpapers-12.jpg");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    /*http://www.wallpaperawesome.com/wallpapers-awesome/wallpapers-landscapes-mountains-sea-lakes-awesome/wallpaper-amazing-landscape-patagonia.jpg*/
}
#skills-h3 {
    color: white;
    height: 80px;
    text-align: center;
    background-color: rgba(0,0,0,.7);
}
#skills-title {
    position: relative;
    top: 35px;
}
#php {background-image: url(https://turbo.paulstamatiou.com/uploads/2007/01/rsstotwittercode.gif);}
#html {
    background-image: url(http://jimbir.ch/sites/default/files/img/blog/Standing-Up-Presentation-Export.png);
    background-size: cover;
}
#js {background-image: url(http://magwebsitefiles2015.blob.core.windows.net/blogfiles/blog-image-iibrary/Script_C_to_Javascript_Meets_Dynamics_CRM_2011_2.jpg);}
#jquery {background-image: url(https://aspblogs.blob.core.windows.net/media/scottgu/Media/image_454269F0.png);}
#python {background-image: url(https://image.slidesharecdn.com/20160722europython2016-160723150413/95/3d-modeling-and-printing-by-python-31-638.jpg?cb=1469286265);}
#mysql {background-image: url(http://www.phpkode.com/media/shots/s/m_mysql-db-cleanup-script.jpg);}
.skillName {
    width: 100%;
    background-color: black;
    color: white;
}
.gridWrap {
    margin-bottom: 50px;
    background-color: blue;
}
.left-col, .right-col {
    width: 400px;
    height: 350px;
    margin-top: 25px;
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    color: #094C70;
    font-size: 1.1em;
    font-weight: bold;
    text-align: center;
    vertical-align: middle;
    line-height: 75px;
}
.left-col {
    float: left;
    margin-left: 20%;
}
.right-col {
    float: right;
    margin-right: 20%;
}

/*Education Slideshow*/
* {box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  width: 100%;
  position: relative;
  display: inline-block;
  margin-top: 100px;
}

.mySlides {
    display: none;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  background-color: rgba(0,0,0,.7);
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor:pointer;
  height: 13px;
  width: 13px;
  margin: 0 2px;
  background-color: white;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

JavaScript/jQuery
$(document).ready(function() {
    $(".mySlides:nth-of-type(1)").css("display", "block");
    $(".dot:nth-of-type(1)").addClass('active');
})
    var slideIndex = 1; //Shows which slide should show

    function plusSlides(n) {
      showSlides(slideIndex += n); //Adds one to the slide index then initiates the function
    }

    function currentSlide(n) {
      showSlides(slideIndex = n); //Sets slide to n then initiates the function
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides"); //array of mySlides
      var dots = document.getElementsByClassName("dot"); //array of dots
      if (n > slides.length) {slideIndex = 1} //If index of slides is too high return back to one
      if (n < 1) {slideIndex = slides.length} //If you backtrack from the first slide, it goes to the last one
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none"; //Resets them all to hidden
      }
      for (i = 0; i < dots.length; i++) {
          dots[i].className = dots[i].className.replace("active", ""); //Turns off active dots
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active"; //Adds the active class to the selected dot
    }


text:
Q: Control's parent is null when placed inside a ContentControl I've got a simple control derived from ContentControl with 3 properties.
My problem comes when I try to perform a control.TransformToVisual() with a control that is placed inside MainContent. It always brings up an ArgumentNullException.
My guess is this due to the control having a null Parent property. Is there a simple way to way around this?
C#
public static readonly DependencyProperty LabelTextProperty =
    DependencyProperty.Register("LabelText", typeof(string), typeof(LabelledControl), null);

public static readonly DependencyProperty ValidationContentProperty =
    DependencyProperty.Register("ValidationContent", typeof(object), typeof(LabelledControl), null);

public static readonly DependencyProperty MainContentProperty =
    DependencyProperty.Register("MainContent", typeof(object), typeof(LabelledControl), null);

XAML
<Style TargetType="local:LabelledControl">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="local:LabelledControl">

            <StackPanel Margin="0 10 0 0">
                <StackPanel Orientation="Vertical">
                    <dataInput:Label Content="{TemplateBinding LabelText}" FontWeight="Bold" FontSize="12" IsTabStop="False"/>
                    <ContentControl Content="{TemplateBinding ValidationContent}" IsTabStop="False"/>
                </StackPanel>
                <ContentControl x:Name="_contentControl" Content="{TemplateBinding MainContent}" IsTabStop="False"/>
            </StackPanel>

        </ControlTemplate>
    </Setter.Value>
</Setter>
</Style>

A: Have you tried using the ContentPresenter class instead of the ContentControl class within your ControlTemplate to present those properties within the template? I am not sure if it is related to your ArgumentNullException, but typically the content of a ContentControl is exposed on the template via a ContentPresenter.
Since your control derives from ContentControl the ContentPresenter will automatically bind the Content and ContentTemplate properties for you to whatever the Content property is set to. You could also manually bind the Content property of the ContentPresenter to your ValidationContent property.
I am not sure why you are defining a MainContent property when the base ContentControl already gives you a Content property to use, maybe that is a second piece of content you are trying to expose.


text:
Q: how can i display UIlabel in UItableview cell where UILabel containing the xml data? this is my parser section where i am getting the attribute and values from the xml file.now when it will parse the xml concurrently should show the attribute and its value in the table view cell one bye one.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(@"found this element: %@", elementName);
currentElement = [elementName copy];
if([elementName isEqualToString:@"ProductData"])
    {
    objectsArray = [[NSMutableArray alloc] init];
    productDict = [[NSMutableDictionary alloc] init];
   }

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@ %@", currentElement,string);
if(!currentString){
    currentString = [[NSMutableString alloc] init];
}
[currentString appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:   (NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(@"ended element: %@", elementName);
if([elementName isEqualToString:@"id"])
{
    [productDict setObject:currentString forKey:@"id"];
    [self labelsetting:0];
    [currentString release],currentString = nil;

    return;
}
if([elementName isEqualToString:@"productNumber"])
{
    [productDict setObject:currentString forKey:@"productNumber"];
    [self labelsetting:0];
    [currentString release],currentString = nil;
    return;
}
if([elementName isEqualToString:@"name"])
{
    [productDict setObject:currentString forKey:@"name"];
    [self labelsetting:0];
    [currentString release],currentString = nil;
    return;
}
if([elementName isEqualToString:@"dateCreated"])
{
    [productDict setObject:currentString forKey:@"dateCreated"];
    [self labelsetting:0];
    [currentString release],currentString = nil;
    return;
}
if([elementName isEqualToString:@"image"])
{
    [productDict setObject:currentString forKey:@"image"];
    [self labelsetting:0];
    [currentString release],currentString = nil;
    return;
}
if([elementName isEqualToString:@"ProductData"])
{
    [objectsArray addObject:productDict];

    [productDict release],productDict = nil;
}
[currentString release], currentString = nil;

}

below my tableview where i want to show the xml data.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
return [objectsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];

}

productDict = [objectsArray objectAtIndex:indexPath.row];

NSString *data = nil;
for (NSString *key in [productDict allKeys] ) {
   // [data stringByAppendingFormat:@"%@ %@",key,[productDict objectForKey:key]];
    data = [NSString stringWithFormat:@"%@%@", key,[productDict objectForKey:key]];

    NSLog(@"data: %@",data);

}
cell.textLabel.text = data;

return cell;
[data release];
}

This the console of this view controller
2011-10-16 15:19:01.627 cmsCommander[1795:207] namestring: emon
2011-10-16 15:19:01.630 cmsCommander[1795:207] username: emon@test.com
2011-10-16 15:19:01.874 cmsCommander[1795:207] found file and started parsing
2011-10-16 15:19:01.877 cmsCommander[1795:207] current Element id : 1
2011-10-16 15:19:01.879 cmsCommander[1795:207] current Element productNumber :    a91cc0f4c7
2011-10-16 15:19:01.880 cmsCommander[1795:207] current Element name : Product 1
2011-10-16 15:19:01.881 cmsCommander[1795:207] current Element image :  5e928bbae358c93caedf6115fa7d178b.jpg
2011-10-16 15:19:01.882 cmsCommander[1795:207] current Element dateCreated : 2011-10-06T16:08:45
2011-10-16 15:19:01.883 cmsCommander[1795:207] current Element id : 2
2011-10-16 15:19:01.888 cmsCommander[1795:207] current Element productNumber : d8287e2e51
2011-10-16 15:19:01.892 cmsCommander[1795:207] current Element name : Product 2
2011-10-16 15:19:01.893 cmsCommander[1795:207] current Element image : 8bbd8dfff3cdd28285d07810a4fe7c32.jpg
2011-10-16 15:19:01.895 cmsCommander[1795:207] current Element dateCreated : 2011-10-06T16:08:45
2011-10-16 15:19:01.896 cmsCommander[1795:207] current Element id : 3
2011-10-16 15:19:01.897 cmsCommander[1795:207] current Element productNumber : 7931c08c22
2011-10-16 15:19:01.897 cmsCommander[1795:207] current Element name : Product 3
2011-10-16 15:19:01.902 cmsCommander[1795:207] current Element image : e19becad20d6f4378e37313c5dbdf070.jpg
2011-10-16 15:19:01.904 cmsCommander[1795:207] current Element dateCreated : 2011-10-06T16:08:45
2011-10-16 15:19:01.904 cmsCommander[1795:207] all done!
2011-10-16 15:19:01.906 cmsCommander[1795:207] The number of row in the object array:  1
2011-10-16 15:19:01.909 cmsCommander[1795:207] data: name  Product 3
2011-10-16 15:19:01.910 cmsCommander[1795:207] data: id  3
2011-10-16 15:19:01.911 cmsCommander[1795:207] data: productNumber  7931c08c22
2011-10-16 15:19:01.912 cmsCommander[1795:207] data: image  e19becad20d6f4378e37313c5dbdf070.jpg
2011-10-16 15:19:01.913 cmsCommander[1795:207] data: **dateCreated  2011-10-06T16:08:45**

now i think you have got my question.

A:     - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
            return 1;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
            return [objectsArray count];
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

            static NSString *CellIdentifier = @"Cell";

            UITableViewCell *currentCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

            if (currentCell == nil) {
                currentCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
            }
            NSMutableDictionary *productDict = [objectsArray objectAtIndex:indexPath.row];
NSString *data = nil;
    for (NSString *key in [productDict allKeys] ) {
        [data stringByAppendingFormat:@"%@",key,[dic objectForKey:key]];
    }
            currentCell.textLabel.text = data;

            return currentCell;
    }


text:
Q: How can I user configService in super()? I have a question about setting environmental variables.
In official document, it says using ConfigModule in this case, but my case is a exception case.
Because I would like to use it in super() in constructor.
My code is the below.
Is there any solution in this case?
If you need more information, please let me know.
Thank you all your support!!
// jwt.strategy.ts

import { UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserRepository } from './user.repository';
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserRepository)
        private userRepository: UserRepository,
        private configService: ConfigService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: configService.get('JWT_TOKEN'),
        });
    }

    async validate(payload: JwtPayload) {
        const { username } = payload;
        const user = await this.userRepository.findOne({ username });

        if (!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}

A: For your Strategy you're missing the @Injectable() which tells Nest that it needs to inject the dependencies defined in the constructor.

A: You need to import the configModule into your module class for the configService to work. Also, add @Injectable() right above the class name to indicate it is a provider.
This is how you import the module.
//auth.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [ConfigModule],
  provider:[JwtStrategy]
})
export class AuthModule {}

NestJs resolves the dependencies between them.
see: https://docs.nestjs.com/techniques/configuration#using-the-configservice

A: I would also like to point out that since you are not using the configService anywhere but in the super() call the usage of private keyword in front of it is redundant
You can try using this.configService.get('JWT_TOKEN') but it will simply yell at you that you haven't called super
Removing the private keyword will simply avoid making the configService as a class variable and simply treat it as some option passed into it


text:
Q: Translate CHAR_INFO.Attributes to ConsoleColor In C# or VB.NET, I would like to translate the Attributes member of CHAR_INFO structure, to a ConsoleColor for obtaining both the foreground color and background color.
This is the enumeration that I have declared using VB.NET:
<Flags>
Enum CharInfoAttributes As Short
    None = &H0S
    ForeColorBlue = &H1S
    ForeColorGreen = &H2S
    ForeColorRed = &H4S
    ForeColorIntensity = &H8S
    BackColorBlue = &H10S
    BackColorGreen = &H20S
    BackColorRed = &H40S
    BackColorIntensity = &H80S
    LeadingByte = &H100S
    TrailingByte = &H200S
    GridHorizontal = &H400S
    GridVerticalLeft = &H800S
    GridVerticalRight = &H1000S
    ReverseVideo = &H4000S
    Underscore = &H8000S
End Enum

For getting the forecolor I'm not sure if my solution is correct (I yet didn't tested all console colors) but it seem to work as expected with the colors that I tried...
Public Shared Function GetForeColor(attributes As CharInfoAttributes) As ConsoleColor

    If (attributes = CharInfoAttributes.None) Then
        Throw New ArgumentException(
                           paramName:=NameOf(attributes),
                           message:="Value does not contain forecolor information.")
    End If

    Dim value As CharInfoAttributes = attributes And
        Not CharInfoAttributes.BackColorBlue And
        Not CharInfoAttributes.BackColorGreen And
        Not CharInfoAttributes.BackColorRed And
        Not CharInfoAttributes.BackColorIntensity And
        Not CharInfoAttributes.GridHorizontal And
        Not CharInfoAttributes.GridVerticalLeft And
        Not CharInfoAttributes.GridVerticalRight And
        Not CharInfoAttributes.LeadingByte And
        Not CharInfoAttributes.TrailingByte And
        Not CharInfoAttributes.ReverseVideo And
        Not CharInfoAttributes.Underscore

    Return CType(value, ConsoleColor)

End Function

But I don't get the idea about how to retrieve the backcolor.
Public Shared Function GetBackColor(attributes As CharInfoAttributes) As ConsoleColor

    If (attributes = CharInfoAttributes.None) Then
        Throw New ArgumentException(
                           paramName:=NameOf(attributes),
                           message:="Value does not contain backcolor information.")
    End If

    ' ToDo...
    Return CType(value, ConsoleColor)

End Function

A: I did this solution thanks to @TnTinMn comment.
Enum definition:
<Flags>
Public Enum CharInfoAttributes As Short
    None = &H0S
    ForeColorBlue = &H1S
    ForeColorGreen = &H2S
    ForeColorRed = &H4S
    ForeColorIntensity = &H8S
    BackColorBlue = &H10S
    BackColorGreen = &H20S
    BackColorRed = &H40S
    BackColorIntensity = &H80S
    LeadingByte = &H100S
    TrailingByte = &H200S
    GridHorizontal = &H400S
    GridVerticalLeft = &H800S
    GridVerticalRight = &H1000S
    ReverseVideo = &H4000S
    Underscore = &H8000S
    ForeColorMask = &HFS
    BackColorMask = &HF0S
    ColorMask = &HFFS
End Enum

Functions:
Public Shared Function GetCharInfoAttributesForeColor(ByVal attributes As CharInfoAttributes) As ConsoleColor
    If ((attributes And CharInfoAttributes.ForeColorMask) <> 0) Then
        attributes = CType((CInt(attributes)) And Not CharInfoAttributes.BackColorMask, CharInfoAttributes)
    End If
    Return CType(attributes, ConsoleColor)
End Function

Public Shared Function GetCharInfoAttributesBackColor(ByVal attributes As CharInfoAttributes) As ConsoleColor
    ' https://referencesource.microsoft.com/#mscorlib/system/console.cs,7a88edaade340cdb
    If ((attributes And CharInfoAttributes.BackColorMask) <> 0) Then
        ' Turn background colors into foreground colors.
        attributes = CType((CInt(attributes)) >> 4, CharInfoAttributes)
    End If
    Return CType(attributes, ConsoleColor)
End Function


text:
Q: Открываю файл разными редакторами — содержимое разное. Почему? Есть mkv файл. Если открываю через блокнот или в бинарном режиме в visual studio, то получаю набор символов вида "→EЯ??B┼?☺Bт?♦BуB'?matroskaB╪?☺". Но случайно открыл в sublime text, так там сразу получился идеальный (для дальнейшей обработки) результат - набор шестнадцатеричных чисел (на всякий случай часть из них - 1a45 dfa3 0100 0000).
Казалось бы, достаточно преобразовать эти символы в VS в двоичный код и результат будет таким же. Только при преобразовании символов в int (и uint32_t) происходят косяки. А именно - уже третий и четвёртый символы, описанной выше последовательности, преобразовываются в отрицательные числа (в случае uint в многозначное положительное), в результате чего и двоичный код выходит неправильный.
Почему так? Как мне получить в VS нормальную последовательность чисел?
![Тут результат преобразования этих символов сначала в int, а потом в двоичный код.
После слова Тест идёт два числа - это я перевёл шестнадцатеричные числа, полученные из sublime text, в двоичный код.
Если не считать первые 8 нулей (откуда они могут браться, если в другом редакторе их нет?) в последовательности, полученной в VS, а так же неверно переведённых символов, то числа совпадают. ]1
И вот код, которым открываю файл и провожу преобразование.
  setlocale(LC_ALL, "ru");
  string path = "video.mkv";

  ifstream mkv;

  mkv.open(path, fstream::binary);

  if (!mkv.is_open())
  {
    cout << "Not" << endl;
  }
  else
  {
    cout << "Success!" << endl;
    for (int i = 0; i < 5; i++)
    {
      char byte;
      mkv >> byte;
      cout << byte << "\t" << (int)byte << "\t" << bitset<16>((int)byte) << "\t" << i << endl;
    }
    cout << "Test: " << bitset<16>(0x1a45) << "\t" << bitset<16>(0xdfa3) << endl;


text:
Q: Give more score to documents that contains all query terms I have a problem with scoring in elasticsearch. When user enter a query that contains 3 terms, sometimes a document that has two words a lot, outscores a document that contains all three words. for example if user enters "elasticsearch query tutorial", I want documents that contains all these words score higher than a document with a lot of "tutorial" and "elasticsearch" terms in it.
PS: I am using minimum should match and shingls in my query. also they made ranking a lot better, they did not solve this problem completely. I need something like query coordination in lucene's practical scoring function. is there anything like that in elastic with BM-25?

A: One of the possible solutions could be using function score:
{
    "query": {
        "function_score": {
          "query": { "match_all": {} },
          "functions": [
              {
                  "filter": { "match": { "title": "elasticserch" } },
                  "weight": 1
              },
              {
                  "filter": { "match": { "title": "tutorial" } },
                  "weight": 1
              }
          ],
          "score_mode": "sum"
        }
    }
}

In this case, you would have clearly a better position for documents with more matches. However, this would completely ignore TF-IDF or any other parameters.


text:
Q: Ranking MongoDB search Ok, this might sound simple but am not sure what to do.
I am running PHP 5.3.x and this is what I want to do. I know the find() command. but I am not sure how to rank the returned JSON.
here is how we store our blog
{
"title":"this is a title";
"body":"this is the body";
"author":"ROB"
"keywords":[{'auto';'music';'fun'}]
"country":"USA"
"dateadded":"07-11-2011";
}

what I want to do is the following order
Keyword match 100% - 0%
Author if author has talked about this keyword a lot there posts go higher up
title search score 1 (Meaning matches what user is searching
order that by date newest to oldest
please let me know if this is possible.

A: Mongo is a document store not a search engine. I recommend you look at SOLR to index your documents for search/relevancy and store the documents themselves in mongo. For a blog you can probably forgo mongo and just store everything in SOLR but for large document sets this would be a bad idea.


text:
Q: tabbed page causing more time to load the application I am trying develop a xamarin app which has tabbed pages.
I have 3 main tabs.Each page viewmodel contructor has 3-5 Api calls.So its taking more time(20s) to load my app(for opening).
mainpage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage  xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Myapplication.Views.MenuPage"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             xmlns:b="clr-namespace:Prism.Behaviors;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
              xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
             xmlns:views="clr-namespace:Dyocense.Views"
             android:TabbedPage.ToolbarPlacement="Bottom"
             android:TabbedPage.IsSwipePagingEnabled="False"
             >

        <views:A Title="A" Icon="dsjsdsd_18dp.png" ></views:A>
        <views:B Title="B" Icon="askjasa.png"></views:B>
        <views:C Title="C" Icon="abc.png"></views:C>
        <views:D Title="D" Icon="abc.png"></views:D>

</TabbedPage>

How to load only first tab(A) detail page on app loading and rest of the pages on tab changing.

A: A solution is to make the heavy pages load their content in a lazy manner, only when their tab becomes selected. This way, since these pages are now empty when TabbedPage is created, navigating to the TabbedPage suddenly becomes very fast!
1.create a behavior for the TabbedPage page, called ActivePageTabbedPageBehavior.
class ActivePageTabbedPageBehavior : Behavior<TabbedPage>
{
 protected override void OnAttachedTo(TabbedPage tabbedPage)
  {
    base.OnAttachedTo(tabbedPage);
    tabbedPage.CurrentPageChanged += OnTabbedPageCurrentPageChanged;
  }

 protected override void OnDetachingFrom(TabbedPage tabbedPage)
  {
    base.OnDetachingFrom(tabbedPage);
    tabbedPage.CurrentPageChanged -= OnTabbedPageCurrentPageChanged;
  }

 private void OnTabbedPageCurrentPageChanged(object sender, EventArgs e)
  {
    var tabbedPage = (TabbedPage)sender;

    // Deactivate previously selected page
    IActiveAware prevActiveAwarePage = tabbedPage.Children.OfType<IActiveAware>()
        .FirstOrDefault(c => c.IsActive && tabbedPage.CurrentPage != c);
    if (prevActiveAwarePage != null)
    {
        prevActiveAwarePage.IsActive = false;
    }

    // Activate selected page
    if (tabbedPage.CurrentPage is IActiveAware activeAwarePage)
    {
        activeAwarePage.IsActive = true;
    }
  }
}

2.define IActiveAware interface
interface IActiveAware
  {
    bool IsActive { get; set; }
    event EventHandler IsActiveChanged;
  }

3.create a base generic abstract class called LoadContentOnActivateBehavior
abstract class LoadContentOnActivateBehavior<TActivateAwareElement> : Behavior<TActivateAwareElement>
   where TActivateAwareElement : VisualElement
 {
  public DataTemplate ContentTemplate { get; set; }

  protected override void OnAttachedTo(TActivateAwareElement element)
   {
     base.OnAttachedTo(element);
     (element as IActiveAware).IsActiveChanged += OnIsActiveChanged;
   }

  protected override void OnDetachingFrom(TActivateAwareElement element)
   {
     (element as IActiveAware).IsActiveChanged -= OnIsActiveChanged;
     base.OnDetachingFrom(element);
   }

  void OnIsActiveChanged(object sender, EventArgs e)
   {
     var element = (TActivateAwareElement)sender;
     element.Behaviors.Remove(this);
     SetContent(element, (View)ContentTemplate.CreateContent());
   }

  protected abstract void SetContent(TActivateAwareElement element, View contentView);
}

4.the specialized LazyContentPageBehavior
class LazyContentPageBehavior : LoadContentOnActivateBehavior<ContentView>
 {
   protected override void SetContent(ContentView element, View contentView)
    {
      element.Content = contentView;
    }
 }

then we can use in xaml like this:
<TabbedPage>
  <TabbedPage.Behaviors>
    <local:ActivePageTabbedPageBehavior />
  </TabbedPage.Behaviors>

<ContentPage Title="First tab">
    <Label Text="First tab layout" />
</ContentPage>

<local:LazyLoadedContentPage Title="Second tab">
    <ContentPage.Behaviors>
        <local:LazyContentPageBehavior ContentTemplate="{StaticResource ContentTemplate}" />
    </ContentPage.Behaviors>
    <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="ContentTemplate">
                <!-- Complex and slow to render layout -->
                <local:SlowContentView />
            </DataTemplate>
        </ResourceDictionary>
    </ContentPage.Resources>
</local:LazyLoadedContentPage>
</TabbedPage>

we moved the ContentPage complex layout to become a DataTemplate.
Here's the custom LazyLoadedContentPage page which is activation aware:
class LazyLoadedContentPage : ContentPage, IActiveAware
{
  public event EventHandler IsActiveChanged;

  bool _isActive;
  public bool IsActive
   {
     get => _isActive;
     set
      {
        if (_isActive != value)
        {
            _isActive = value;
            IsActiveChanged?.Invoke(this, EventArgs.Empty);
        }
      }
   }
 }

SlowContentView  do some complex things
 public partial class SlowContentView : ContentView
{
    public SlowContentView()
    {
        InitializeComponent();

        // Simulating a complex view
        ...
    }
}

you could refer to the link

A: As a workaround I created a new class extending the Xamarin.Forms.TabbedPage and I send a message every time one of the tabs is clicked (or in general is diplayed)
public enum TabbedPages
{
    MyPage1 = 0,
    MyPage2 = 1,
    MyPage3 = 2,

}

public class BottomBarPage : Xamarin.Forms.TabbedPage
{

    protected override void OnCurrentPageChanged()
    {
        base.OnCurrentPageChanged();

        var newCurrentPage = (TabbedPages)Children.IndexOf(CurrentPage);

        MessagingCenter.Send<Xamarin.Forms.TabbedPage>(this, newCurrentPage.ToString("g"));

    }
}

and then on the view models used for each page loaded when clicking on the tab I subscribe to the message and call my APIs
public class MyPage2ViewModel
{
    public MyPage2ViewModel()
    {
        MessagingCenter.Subscribe<TabbedPage>(this, TabbedPages.MyPage2 .ToString("g"), async (obj) =>
        {
            //API call
        });
    }
}


text:
Q: Why isn't the "rectangle" that I want to draw on my Qt widget showing up? I basically want to display a rectangle on a dialog window widget. Using another question as reference, I tried to adapt the framework of using a QLabel and painting to it (the process overall seems overly complicated).
I started by making a member in the dialog box's class:
QLabel* label;

In the constructor of the dialog box:
label = new QLabel(this);
label->setGeometry(20, 50, 50, 100);

Just to try and make it work, I gave the dialog box a button to make the "rectangle" created with the label appear on the widget. I connected the "pressed" signal of this button to a slot which does the following:
QPixmap pixmap(50, 100);
pixmap.fill(QColor("transparent"));
QPainter painter(&pixmap);
painter.setBrush(QBrush(Qt::black));
painter.drawRect(20, 50, 50, 100);
label->setPixmap(pixmap);
update();

Unfortunately, nothing appears in the widget when I press the button. What am I missing here?

A: I tried this with PyQt and it generally works, but I'm not 100% sure about the procedure. Maybe you should try calling painter.end() the painter before calling setPixmap(). Also, I'm not sure if one is supposed to draw onto a QPixmap outside of QWidget:paintEvent, it might be safer to draw a QImage and create a QPixmap from it.
from PyQt4 import QtGui

app = QtGui.QApplication([])

class Test(QtGui.QWidget):
    def __init__(self):
       QtGui.QWidget.__init__(self)
       self.bn = QtGui.QPushButton("Paint")
       self.lb = QtGui.QLabel()
       layout = QtGui.QVBoxLayout(self)
       layout.addWidget(self.bn)
       layout.addWidget(self.lb)
       self.bn.clicked.connect(self.handleClick)

    def handleClick(self):
       pixmap = QtGui.QPixmap(50, 100)
       pixmap.fill(QtGui.QColor("transparent"))
       p = QtGui.QPainter(pixmap)
       p.drawRect(0,0,50-1,100-1)
       p.end()
       self.lb.setPixmap(pixmap)

t = Test()
t.show()
app.exec_()

For simply drawing a rectangle this is certainly very complicated. I don't know what you are planning, be aware that there is QGraphicsView for drawing figures.


text:
Q: R: Rollapply, preserve Date column I have a dataset that includes a date column and the other columns are daily index returns. I would like to receive the rolling standard deviation for all indices but preserve the date in order to plot the results. Data looks as follows:
head(mydata)

        Date      GL1 GL2       US CN       JP       DE       UK
1 1990-01-03  0.02460  NA -0.25889 NA       NA  3.00128  1.20872
2 1990-01-04  0.33681  NA -0.86503 NA       NA -1.82327 -0.49234
3 1990-01-05 -0.81943  NA -0.98041 NA -1.13817 -0.86874 -0.29003
4 1990-01-06       NA  NA       NA NA       NA       NA       NA
5 1990-01-07       NA  NA       NA NA       NA       NA       NA

When using rollapply function the date however disappears and returns NAs
require(zoo)

Rolling = as.data.frame(rollapply(mydata,30,sd,na.rm=TRUE,align="right"))

head(Rolling)
 Date       GL1 GL2       US CN        JP       DE        UK
1   NA 0.5527451  NA 1.033204 NA 0.9021960 1.486567 0.8421562
2   NA 0.5675608  NA 1.057156 NA 0.9318496 1.467637 0.7954081
3   NA 0.5681388  NA 1.077253 NA 0.9318496 1.438117 0.8123918
4   NA 0.5663124  NA 1.095049 NA 0.9264034 1.454327 0.8331727
5   NA 0.5623544  NA 1.075118 NA 0.9017324 1.443547 0.8123613
6   NA 0.5523878  NA 1.052310 NA 0.8797660 1.411220 0.8197624

I kept the date in the as.Date format but can not figure out how to continue showing the corresponding dates in the Date column.

A: The real problem here is using data frames to represent time series.  If you use a time series representation then the entire problem goes away.
mydata_z <- read.zoo(mydata)
r <- rollapplyr(mydata_z, 30, sd, na.rm = TRUE, fill = NA)

Now you can use plot.zoo, xyplot.zoo or autoplot.zoo to graph r using classic graphics, lattice graphics or ggplot2 graphics respectively or if you need a data frame then fortify.zoo(r).