text:
Q: correct way to get selected option in jquery from an object I've seen on StackOverflow and googling around that the most used way to get the selected text from a <SELECT> element with jquery is like this
$("#cboId :selected").text()

what I have is not the id, but an object. I have an object, say
var myCombo= $("#cboId");

coming from an earlier piece of code.
I've done like this to get the selected text, but is ugly:
  $("#" + myCombo.attr('id') + " :selected").text() ;

Is there any cleaner way to do it?

A: var selectedText = $(":selected",myCombo).text();


text:
Q: AHK, how to capture Rbutton in loop Could someone help me understand how to capture Rbutton in Loop?
The idea is when I click GUI button its activate loop and waiting for some time for example 15 sec until RButton will be clicked, if loop detects that RBUtton been doubleclicked, should show me msg box

w::SetTimer Test, 5000

Test:
Loop {  ; waiting when RButton will be clicked
    Keywait,RButton
    A := GetKeyState("Rbutton","P")
if (!%A%) {
    MsgBox, this part should continue and wait for RButton  do nothing and continue to wait
    } else if (%A%) {
    MsgBox, you clicked double RButton
    Send, this is text
    break
    }

}
    Msgbox end of script
    SetTimer Test, Off
Return

A: My idea:

*

*Use While loop as timer, ie, while within duration (eg 15 secs), keep checking status of double right button. If criteria met within duration, break the loop and show message box.

*Use SetTimer and GetKeyState to constantly check and update number of right button clicked.

Note to below script. It is assumed that when GUI is clicked, DetectDoubleClick() will be fired.
Counter_RButton := 0
SecondsToWait   := 15

DetectDoubleClick()
{
  Global Counter_RButton
  Now   := A_TickCount
  End   := A_TickCount + (SecondsToWait * 1000)
  SetTimer, CaptureRButton, 150
  While (End >= Now)
  {
    if (Counter_RButton = 2)
    {
      Counter_RButton := 0
      MsgBox,,,Double RButton Detected!
      break
    }
    Now := A_TickCount
  }
SetTimer, CaptureRButton, Off
return
}

CaptureRButton:
ButtonIsDown := GetKeyState("RButton")
If ButtonIsDown
    Counter_RButton := Counter_RButton + 1
Exit

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I represent a keyboard touch event programmatically in IOS? I am working on an app that uses voice commands to maneuver through text fields. What I need to do is translate the voice command into a touch event on the keyboard. Specifically I need to access the tab key and the return key. The user will not be using the keyboard in this app. I am having a difficult time finding a way to get this done. I know how to convert the voice commands into something that I can use, but I still need to apply that to the keyboard commands. I have researched this extensively and I get what I think are bits and pieces of what I really need, but nothing is connecting the dots for me.

A: You don't need the keyboard to navigate text fields. You just need to modify the first responder. There unfortunately isn't an easy way to get the current first responder, but you can search for it.
Once you have the first responder, you can move to the next field like this:
[[field nextResponder] becomeFirstResponder];

If you are trying to do this in a very general way, you should first call canBecomeFirstResponder and handle situations where there there are no available first responders and other corner cases, but this generally isn't needed for very simple interfaces.
If you want to manage "enter" in order to end editing and dismiss the keyboard, you can call endEditing: on the superview.
You can modify text without the keyboard by replacing the text property.


text:
Q: Efficient inverse (1/x) for AVR I'm trying to find an efficient way of calculating an inverse on an AVR (or approximating it).
I'm trying to calculate the pulse period for a stepper motor so that I can vary the speed linearly. The period is proportional to the inverse of the speed (p = K/v), but I can't think of a good way of calculating this on the fly.
My formula is
p = 202/v + 298; // p in us; v varies from 1->100

Testing on the Arduino, the division seems to be ignored completely leaving p fixed at 298 (though perhaps this would be different in avr-gcc). I've also tried summing v in a loop until it exceeds 202, and counting the loops, but this is quite slow.
I could generate a lookup table and store it in flash, but I was wondering if there was another way.
Edit: Maybe the title should be "efficient divide"...
Update: As pingswept points out, my formula for mapping period to velocity is incorrect. But the main problem is the divide operation.
Edit 2: On further investigation, divide is working on the arduino, the problem was due to both the incorrect formula above and an int overflow elsewhere.

A: One nice thing about division is that more or less everyone is doing it.  It is a pretty core feature of the C language, and compilers like AVR-GCC (called by the Arduino IDE) will choose the best division algorithm available, even when the microcontroller does not have a hardware division instruction.
In other words, you don't need to worry about how division is implemented unless you have a very strange special case.

If you do worry, then you might enjoy reading Atmel's official suggested division algorithms (one optimized for code size, and one optimized for execution speed; neither take any data memory).  They are in:
http://www.atmel.com/dyn/resources/prod_documents/doc0936.pdf
which is the Application Note "AVR200: Multiply and Divide Routines" listed on the Atmel page for its (reasonably big) Atmega processors like the Atmega 168 and Atmega 328 used in the standard Arduinos.  The list of data-sheets and application notes is at:
http://www.atmel.com/dyn/products/product_card.asp?part_id=4720

A: looks to me like all you need is a 100-entry lookup table. Doesn't get much faster than that.
#define VALUE_FOR_V_EQUALS_ZERO 0
uint16_t formula_lookup[100] = {VALUE_FOR_V_EQUALS_ZERO, 500, 399, 365, 348, ..., 300};

...

//"calculate" formula
p = formula_lookup[v > 67 ? 67 : v];

EDIT you actually only a 68 value lookup table since values of v greater than 67 always evaluate to 300.

A: There are some very good techniques mentioned in the book "Hackers Delight by Henry Warren and on his website hackersdelight.org.  For a technique that works well with smaller microcontrollers when dividing by constants have a look at this file.

A: Your function doesn't seem like it would give the result you want. For example, the value 50 returns roughly 302, while 100 returns roughly 300. Those two results will cause almost no change in the speed of the motor.
If I understand you correctly, you're really looking for a fast way to map the numbers 1-100 to the range 300-500 (approximately), such that 1 maps to 500 and 100 maps to 300.
Perhaps try:
p = 500 - (2 * v)
But I might be misunderstanding-- are you trying to calculate the on-time of a constant frequency square wave? What's the 298?

A: An efficient way to approximate divides is by shifts.  e.g. if x = y / 103;
dividing by 103 is the same as multiplying by 0.0097087, so to approximate this first select a 'good' shift number (i.e. a base-2 number, 2,4,8,16,32 and so on)
For this example 1024 is a good fit as we can say that 10 / 1024 = 0.009765
Its then possible to code:
x = (y * 10) >> 10;
Remembering of course to ensure the variable y does not overflow its type when multiplied.  Its not exact, but its quick.

A: On another note if you are trying to do a divide on a CPU that doesn't support divide there's a really cool way to do it in this Wiki article.
http://en.wikipedia.org/wiki/Multiplicative_inverse

To approximate the reciprocal of x,
  using only multiplication and
  subtraction, one can guess a number y,
  and then repeatedly replace y with 2y
  − xy2. Once the change in y becomes
  (and stays) sufficiently small, y is
  an approximation of the reciprocal of
  x.

A: This process here looks mcu-friendly, though it might need a bit of porting.
Though it seems as if the LUT would be easier.  You would only need 100 bytes, less if you used some interpolation, and since the LUT is filled with constants then the compiler might even locate it in the code area instead of the data area.

A: Check to make sure that the division is being performed as floating point. I use Microchip not AVR, but when using C18 you need to force your literals to be treated as floating point. Eg. Try changing your formula to:p = 202.0/v + 298.0;

A: You want fast so here goes.....
Since the AVR cant do normalisation efficiently (shifting left until you cant shift anymore), ignore any pseudo floating point algorithms. The simplest way for very accurate and fastest integer division in an AVR is via a reciprocal look-up table. The table will store reciprocals scaled by a large number (say 2^32).  You then implement a unsigned32 x unsigned32 = unsigned 64 multiplication in assembler,
so answer =   (numerator * inverseQ32[denominator]) >> 32.
I implemented the multiplication function using inline assembler, (wrapped in a c function).  GCC does support 64-bit "long longs", however, to get the result you have to multiply 64bits by 64bits, not 32x32=64 due to C language limitations on 8-bit architecture......
Downside of this method is you will use 4K x 4 = 16K of flash if you want to divide by integers from 1 to 4096......
Very accurate unsigned division is now achieved in about 300 cycles in C.
You could consider using 24 bit or 16 bit scaled integers for more speed, less accuracy.

A: p = 202/v + 298; // p in us; v varies from 1->100

The return value of your equation already is p=298 since the compiler divides first then add, use integer muldiv resolution that is:
p = ((202*100)/v + (298*100))/100

Using this is same multiply a*f, with a=integer f=fraction.
That yield r=a*f but f=b/c then r=a*b/c but it doesn't work yet because position of operators, yield the final r=(a*b)/c or muldiv function, a manner to compute fraction numbers using only integer.


text:
Q: A cheap error estimate and a costly doubt Carl de Boor poses the following problem in his A Practical Guide to Splines (1978 - Chapter II, p. 38, problem 4):

The calculation of $||g|| = \max\{|g(x)| : a \le x \le b\}$ is a nontrivial task. Prove that, for $p \in \mathbb{P}_n$, though, a good and cheap approximation to $||p||$ is provided by $||p||_C := \max\{ |p(\tau_i^C)| : i = 1, ..., n \}$, with $(\tau_i^C)$ given by (6) [Chebyshev points]. [...]

My first question is, if $p$ is really taken to be as general as a random polynomial of order $n$ or if we have to limit ourselves to polynomial interpolations of a function $g:\mathbb{R}\rightarrow\mathbb{R}$ at the Chebyshev points $\tau = [\tau_1^C, ..., \tau_n^C]$?
My second question is, how an approximation $||p||_C$, as defined above, could possibly cover all the arbitrary behaviour between two successive interpolation points $\tau_i^C$ and $\tau_{i+1}^C$.
I have a whole stack of properties which could come at hand for a proof but I am just not able to combine them in a suitable manner. Here they are:
A polynomial $p$ (interpolated at Chebyshev points) is bounded by the approximated function's norm scaled by an order-dependent norm of the Lesbesgue function $||\lambda_n^C||$:
$$ ||p|| \le ||g|| \cdot ||\lambda_n^C|| $$
The error $||g - p||$ of a Chebyshev-based approximation is bounded as follows:
$$ ||g-p|| \le \max_{a\le x\le b} \left| \frac{g^{(n)}(x)}{n!} \right| \frac{2(b-a)^2}{4^n}$$
A Chebyshev-based polynomial interpolation can be represented like this:
$$p(x) = \sum_{i=1}^n \alpha_i T_{i-1}(y(x)),$$
where
$$\alpha_{i+1} := \sum_{j=1}^n \frac{g(\tau_j^C)T_i(\tau_j^*)}{< T_i, T_i >}, \qquad y(x) := \frac{2x - (a+b)}{(b-a)}, \qquad \tau_j^* = \cos\left(\frac{(2j - 1)\pi}{2n}\right).$$
and the polynomial interpolation agrees with the approximated function at the $\tau_i^C$:
$$ p(\tau^C_i) = g(\tau^C_i) \qquad \forall i = 1, ..., n$$
Can anybody help me putting the pieces together?

A: How about this one:
Define a piecewise linear function
$$ g(x) =
\begin{cases}
p(\tau_1^C) & \text{if } x < \tau_1^C \\
p(\tau_i^C) & \text{if } x = \tau_i^C \\
p(\tau_i^C) + \frac{x - \tau_i^C}{\tau_{i+1}^C - \tau_i^C} \left( p(\tau_{i+1}^C) - p(\tau_i^C) \right) & \text{if } x \in (\tau_i^C, \tau_{i+1}^C) \\
p(\tau_n^C) & \text{if } x > \tau_n^C \\
\end{cases},
$$
where $\tau_i^C$ are Chebyshev points such that
$$ \max_{a \le x \le b} |g(x)| = \max_{1\le i \le n} |p(\tau_i^C)|$$
and
$$ p(x) = \sum_{i=1}^n \alpha_i T_{i-1}(y(x))  $$
as given in the question above. From the upper bound of $p$ we then have
$$ ||p|| \le ||g|| \cdot ||\lambda_n^C|| = \max_{1\le i \le n} |p(\tau_i^C)| \cdot ||\lambda_n^C||, $$
with
$$ ||\lambda_n^C|| := \max_{a\le x \le b} \sum_{i=1}^n |l_i^C(x)|, $$
where $l_i^C(x)$ is the Lagrange polynomial based on Chebyshev points.
This qualifies $||p||_C = \max\limits_{1\le i\le n} p(\tau_i^C)$ as a good approximation of $||p||$.
Does that make sense?


text:
Q: How to plot a variable with geographic distance in R? I would like to plot a simple xy graphic being y=variable and x=geographic distance.
I have data.frame with my data of interest in separate columns (ex: Species$Latitude, Species&Longitude, Species$Variable). All coordinates are in decimal degrees and all variable values are numeric.
Something like the attached image.

Can someone help me? I think it it's easy, but I'm having a hard time figuring it out (so not so easy actually).

A: When you have a point of origin, you can use the haversine formule to calculate the distance: Haversine function in R
Update, added sample code:
library(pracma)
names <- c("lion","tiger","flamengo")
latitude <- c(0,3,-5)
longitude <- c(0,-0.5,2)
species <- data.frame(names, latitude, longitude)
for(i in 1:length(species$latitude)){
  loc1 <- c(0,0)
  loc2 <- c(species$latitude[i],species$longitude[i])
  species$distance[i] <- haversine(loc1, loc2)
}
species


text:
Q: Merge between siblings branch of svn My project has big volatile code base and different team are working on same code, so total number of files getting affected daily is huge in number. I recently faced a problem as two of the team has to merge their codes. I will explain the scenario.
My team has branched out from trunk and daily do a down merge from trunk to keep the code base in sync with trunk. There will at least 500 files getting affected daily. Once we finish our code we used to reintegrate to trunk and then do a records only merge back to branch so we can use continue working in branch. Now recently due to early release we are not able to upmerge to trunk, so for getting different team changes we branched out another branch from trunk and then decided to merge all our changes to the new branch, but as we do not have any merge history between my branch and new branch, what I could see, when I try full merge to new branch from my team branch, svn is trying to apply the changes we received from trunk as part of down merge to new branch. The new branch has all the changes as we branched from trunk recently and it is resulting in lots of tree conflicts. I am also not able to reintegrate because it is not trunk.
Could you please suggest any work around on this or any way out of this problem?


text:
Q: Windows 10: Legacy app having trouble opening its own files I'm running an older application -- just for the record, it's QuarkXPress 6 -- on Windows 10 (64-bit pro). Everything works fine, except that I can only open Quark project files from within the application, using File > Open.
If I try to double-click a Quark file in a File Explorer window, I get an "operation requires elevation" error. If I try to drag and drop a file from File Explorer to Quark, it doesn't work (there's no error message, though the cursor turns into a "no-entry" sign as soon as it's over the Quark window).
I've tried running Quark with and without compatibility mode, as an administrator and also started the program with elevated privileges via Task Scheduler. Nothing fixes the problem.
I don't think it's a matter of file rights or ownership, either.
Can anyone enlighten me?


text:
Q: Can ping the website with domain name but can't browse them , why? Some websites like twitter and facebook and youtube are blocked in my country so I need to use VPN so I can access to them , and I didn't have any problem with them until today
The problem is I can ping all these websites that I mentioned (with vpn on) but I can't browse them with chrome or firefox
I set my DNS with the resolveconf/head file and also I can connect with telnet to any of them telnet twitter.com 80 so I can make a TCP connection to them
The only change I made today was about wifi driver and as far as I know it doesn't have any effect on this (if it has tell me )
Is there any settings that I haven't looked at yet ?!
PS: All websites that aren't blocked work well, only have problem with blocked websites that shouldn't be blocked anymore when I'm using VPN ( I can ping them by their domain name but can't brows them with Browsers , that't really interesting !! )
default dev ppp0 proto static scope link metric 50
default via 192.168.1.1 dev wlp2s0 proto dhcp metric 600
10.10.0.0 dev ppp0 proto kernel scope link src 10.10.16.225 metric 50
169.254.0.0/16 dev wlp2s0 scope link metric 1000
185.180.15.243 via 192.168.1.1 dev wlp2s0 src 192.168.1.120
185.180.15.243 via 192.168.1.1 dev wlp2s0 proto static metric 600
192.168.1.0/24 dev wlp2s0 proto kernel scope link src 192.168.1.120 metric 600
192.168.1.1 dev wlp2s0 proto static scope link metric 600
192.168.61.0/24 dev vmnet1 proto kernel scope link src 192.168.61.1
192.168.223.0/24 dev vmnet8 proto kernel scope link src 192.168.223.1

A: I've searched many topics for this problem and I finally resolve the problem , the problem was the size of MTU packets of my Wlan card
I reduce it to 1200 ( previous size was 1500 ) with sudo ifconfig wlp2s0 mtu 1200
 command ( wlp2s0 is my wireless card) and the problem was solved


text:
Q: Backend gets a pdf from a third-party. How can I send it via REST api to my client? I get a pdf from a third party.
I save the file on S3. I can see the file on S3 and when I open it I can see my PDF.
However, when I passed the pdf to the client and check it on Postman I get an empty PDF.
Here is my code:
public async getReportFromThirdParty(token) {
    const params = {
        headers: { Authorization: `Bearer ${token}`},
        responseType: "arraybuffer",
    }

    let report = {};
    report = await axios.get(`https://api.thirdparty.com/api/get-pdf`, params);
    return report.data;
}

app.post("/download", async (req, res) => {
   const token = 'abcde-secret-token';
   const pdf = await getReportFromThirdParty(token);
   await saveToS3(pdf) // <---- I checked and it saves the file properly on S3 as PDF

   res.contentType("application/pdf");
   return res.status(200).send(pdf); // <--- this returns an empty pdf file
});

Any ideas?

A: im going to guess your app is an node express app so therefore you likely need to
res.sendFile();

More info found on the express site


text:
Q: ExpressJS folder structure for helper functions, error class, db operations and general functions without a direct return to the client I'm working on a new export functionality in a ExpressJS project. While working on this it feels like my current folder structure needs to be extended. I'm looking for some advice in this.
Let me quickly describe what I'm building right now.
When a user wants to generate an export (for example a contract export) I want to create a new export record in the database with an 'in_progress' status and return this information to the client so the UI can be updated. At the same time I want to trigger the generation of this export which is a 5-step process:

*

*Get the necessary data from the database

*Format the data to the needed .csv structure

*Parse the array to a .csv

*Upload the .csv to Azure Storage

*Update the export record with the storage data and change the status to 'completed'

In the past I have done all the database operations directly in the controller function. Is it common for the controller file to have more functions than these who are called by the routes? Since this process of generating the export does not have a return to the client I'm not sure if this function should live in the controller file or somewhere else. Also all the sub functions that this function will trigger (get data, format data, parse data to csv, ...). Where should these be stored?
Since we are talking about folder structure. I'm also unsure about the helpers folder. This folder contains functions to format data, parse arrays to csv, generate tokens but also an ErrorResponse class. Should this be split up?
My current folder structure
/deploy
/src
├── config/
│   ├── db.config.js
│   ├── general.config.js
├── controllers/
│   ├── auth.controller.js
│   ├── user.controller.js
│   ├── export.controller.js
│   ├── contract.controller.js
├── database/
│   ├── mongodb.database.js
├── helpers/
│   ├── parsers.js
│   ├── arrayToCsv.js
│   ├── ErrorResponse.js
├── integrations/
│   ├── azure.integration.js
│   ├── auth0.integration.js
│   ├── algolia.integration.js
├── middleware/
│   ├── asyncHandler.middleware.js
│   ├── errorHandler.middleware.js
│   ├── inputHandler.middleware.js
│   ├── notFound.middleware.js
├── models/
│   ├── contract.model.js
│   ├── export.model.js
│   ├── user.model.js
├── routes/
│   ├── auth.routes.js
│   ├── contract.routes.js
│   ├── export.routes.js
├── validators/
│   ├── auth.validator.js
│   ├── user.validator.js
│   ├── export.validator.js
/node_modules
/server.js
/package.json
/.env


text:
Q: getting the org.eclipse.equinox.p2.core.ProvisionException while installing UX studio software in eclipse I am trying to install UX_ Studio software in eclipse from the following URl.
http://developer.salesforce.com/media/commercecloud/uxstudio/4.5
This is my home pc
But I am getting the org.eclipse.equinox.p2.core.ProvisionException
The error is as follows:

Unable to read repository at http://developer.salesforce.com/media/commercecloud/uxstudio/4.5/content.xml.
  Unable to read repository at http://developer.salesforce.com/media/commercecloud/uxstudio/4.5/content.xml.
  Received fatal alert: protocol_version

I checked the error online and added the following line
 open the eclipse.ini file and add the following on a separate line under the -vmargs option.
-Djava.net.preferIPv4Stack=true
But exception is still there

A: Java 8 needs to install with the software. Other versions of java will not work


text:
Q: Как достать данные из списка словаря у меня есть список
 res = [{1:{
                1: [ReservationData.Seat(id_coach=1, id_spot=1, text_from="0", text_to="5", text_special = 1)],
                2: [ReservationData.Seat(id_coach=1, id_spot=2, text_from="0", text_to="6", text_special = 2)],
                3: [ReservationData.Seat(id_coach=1, id_spot=3, text_from="0", text_to="11", text_special = 3)],
                4: [ReservationData.Seat(id_coach=1, id_spot=4, text_from="0", text_to="11", text_special = 4)],
                }}]

Мне надо достать данные второго словаря с ключом 1 и значением ReservationData то есть значение ключа 1 которые в квадратных скобках

A: res = [
      ^ список, первый элемент списка берём как [0]
       {1:
       ^ словарь, берём значение по ключу, т.е. [1]
          {1:
          ^ опять словарь, опять по ключу [1]
             [ReservationData...
             ^ список, первый элемент списка берём как [0]

Итого:
res[0][1][1][0]


text:
Q: Не отображает метод доставки Shiptor и выдает ошибку Всем привет!
После установки плагина доставки Шиптор, постоянно выдает ошибку:

Методов доставки не видно ни в админке, ни на сайте. Как их сделать видимыми? Спасибо!


text:
Q: How to detect when a UIWebView has completely finished loading? I am trying to build a filter for a UIWebView and I am struggiling to detect when the UIWebView has completely finished loading. I have used the following two methods
– webView:shouldStartLoadWithRequest:navigationType:
– webViewDidFinishLoad:

but the issue is that these will be called multiple times when a page has frames and additional content to load.
What I need is to know when the view has completely loaded and there is no more content to fetch. Then when the content has loaded I can check to URL of the page against a list of approved URLS.
ANy ideas?

A: Use the UIWebViewDelegate protocol method webViewDidFinishLoad and webView's isLoading property
 - (void)webViewDidFinishLoad:(UIWebView *)webView
 {
    //Check here if still webview is loding the content
    if (webView.isLoading)
       return;

    //after code when webview finishes
    NSLog(@"Webview loding finished");
 }

A: Swift 3 version:
func webViewDidFinishLoad(_ webView: UIWebView) {
    if webView.isLoading{
        return
    }
    print("Done loading")
}

A: Try use:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)requestURL navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [requestURL URL];
NSLog(@"##### url = %@",[url absoluteString]);
return YES;
}

don't forget to set your UIWebView Delegate
or add statement,
NSRange range = [[url absoluteString] rangeOfString:@"https://www.google.com"];
if (range.location != NSNotFound)
{}

hope to help you.

A: It is true that the original question was posted many years ago. Recently I had to find a reliable solution to this issue.
Here is the solution that worked for me:

*

*Replaced UIWebView with WKWebWiew.

*Added 'evaluateJavaScript' code while handling the 'didFinishNavigation' delegate method.

The complete code is:
   - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id result, NSError *error) {
        if (result != nil) {
            // Call your method here
        }
        if(error) {
            NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
        }
    }];
}

A: If you aren't an owner of UIWebView and as a result you don't have an access to webViewDidFinishLoad but you have a reference to UIWebView you can use the next code
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in

    guard uiWebView.isLoading else {
        return
    }

    timer.invalidate()
    //Add your logic here

}


text:
Q: Text running off page for cventry in moderncv I'm redoing my CV with the moderncv template and it's mostly working quite well (though I admit I'm playing fast and loose with the intended purpose of certain fields to fit an academic profile). However, there's a formatting issue with my teaching section because the name of some classes are quite long:

As you can see, the field with the date can only start after the field with the course title on the line above, which pushes it into the margin. How can this be fixed so that the date aligns properly with the right margin?
Here (I hope) is an MWE:
\documentclass[11pt,a4paper]{moderncv}
\moderncvstyle{banking}
\moderncvcolor{black}
\usepackage[utf8]{inputenc}
\usepackage[scale=0.75,top=2.5cm,bottom=2.5cm]{geometry}

\name{Firstname}{Lastname}

\usepackage{fontspec}
\setmainfont{Baskerville}

\begin{document}
\makecvtitle

\cventry{Autumn 2015}{Postgraduate Tutor (History Department, University of York)}{The Hundred Years War}{}{}{}

\cventry{Spring--Summer 2015}{Postgraduate Tutor (History Department, University of York)}{From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}{}{}{}

\end{document}

A:
I put the too-long text in a left-aligned ([l]) and borderless box with a width of 0 mm:
  \makebox[0mm][l]{From Rome...} that occupies no horizontal space.

\documentclass[11pt,a4paper]{moderncv}
\moderncvstyle{banking}
\moderncvcolor{black}
\usepackage[utf8]{inputenc}
\usepackage[scale=0.75,top=2.5cm,bottom=2.5cm]{geometry}

% Added
\usepackage{showframe}

\name{Firstname}{Lastname}

% Removed
%\usepackage{fontspec}
%\setmainfont{Baskerville}

\begin{document}
\makecvtitle

\cventry{Autumn 2015}{Postgraduate Tutor (History Department, University of York)}{The Hundred Years War}{}{}{}

\cventry{Spring--Summer 2015}{Postgraduate Tutor (History Department, University of York)}{From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}{}{}{}

\cventry{Spring--Summer 2015}{Postgraduate Tutor (History Department, University of York)}{\makebox[0mm][l]{From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}}{}{}{}

\end{document}

A: Class moderncv has a fixed definition of command \cventry, for example for style banking
\renewcommand*{\cventry}[7][.25em]{
  \begin{tabular*}{\maincolumnwidth}{l@{\extracolsep{\fill}}r}% <============
    {\bfseries #4} & {\bfseries #5}\\%
    {\itshape #3\ifthenelse{\equal{#6}{}}{}{, #6}} & {\itshape #2}\\%
  \end{tabular*}%
  \ifx&#7&%
  \else{\\%
    \begin{minipage}{\maincolumnwidth}%
      \small#7%
    \end{minipage}}\fi%
  \par\addvspace{#1}}

with the resulting command in the cv:
\cventry[length--1]{year--year--2}{Degree--3}{Institution--4}{City--5}{\textit{Grade}--6}{Description--7}  % arguments 4 to 7 can be left empty

The main part of the command is set in a tabular, only the last part is a minipage, which can contain more than one line without problems.
So you can change your command to:
\cventry{Spring--Summer 2015}%
  {Postgraduate Tutor (History Department, University of York)}%
  {}%
  {}{}%
  {From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}

With the following MWE:
\documentclass[11pt,a4paper]{moderncv}
\moderncvstyle{banking}
\moderncvcolor{black}
\usepackage[utf8]{inputenc}
\usepackage[scale=0.75,top=2.5cm,bottom=2.5cm]{geometry}

\name{Firstname}{Lastname}

%\usepackage{fontspec}
%\setmainfont{Baskerville}

\begin{document}
\makecvtitle

\cventry{Autumn 2015}%
  {Postgraduate Tutor (History Department, University of York)}%
  {The Hundred Years War}%
  {}{}{}

\cventry{Spring--Summer 2015}%
  {Postgraduate Tutor (History Department, University of York)}%
  {From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}%
  {}{}{}

\cventry{2}%
  {3}%
  {4}%
  {5}{6}{7}

\cventry{Spring--Summer 2015}%
  {Postgraduate Tutor (History Department, University of York)}%
  {}%
  {}{}%
  {From Rome to the Renaissance: The Transformation of Traditional Societies, c. 400--1650}

\end{document}

you get the result:

Just adding \makebox[0mm][l] is not working, because there should be a line break that can not be added.  See this with a litte bit longer text:
\cventry{Spring--Summer 2015}%
  {Postgraduate Tutor (History Department, University of York)}%
  {\makebox[0mm][l]{From Rome to the Renaissance: The Transformation of
    Traditional Societies, c. 400--1650, some text, to make this sentence
    a little bit longer}}%
  {}{}{}

Then you get the result:

As you can see the bold shorter text is already too long, no more space for argument 5 ...


text:
Q: Applying containment to jQuery UI Sortable table prevents moving tall rows to the last position I have a HTML table, for which I am trying to use the jQuery UI Sortable Widget to enable re-ordering of the rows. I have set the sortable axis: 'y', am using a helper function to preserve the widths of the rows when they are being dragged, and have set the containment to be the parent table:
jQuery(function($) {
    $("#rows").sortable({
        handle: ".handle",
        axis: "y",
        containment: "#main-table",
        helper: function(e, row) {
            // From http://www.paulund.co.uk/fixed-width-sortable-tables.
            // Sets the width of each cell to be its original width.
            // This prevents the row collapsing into a narrower stub when being dragged.
            row.children().each(function() {
                $(this).width($(this).width());
            });
            return row;
        }
    });
});

However, when there are rows which have multiple line height, the containment does not behave as expected: when dragging the larger row, the height of the table reduces, and the containment shrinks even more such that the large row cannot be moved to the bottom of the table. The other rows work fine.
A JSFiddle showing this behaviour can be found here: https://jsfiddle.net/AndrewBennet/rc5pnazc/3/
Is this known/expected behaviour? Is there any workaround?

A: The way containment is set is that when the drag starts, coordinates of the element are calculated and pushed to an array which is then used to see if a drag should occur on mouse move. What happens in your case is that this calculation is made after the row is removed from the table, so the containment values are not correct.
One thing you can do is adjust these values on start event so that they match the state of the table before removing the rows from the calculations. You can access them through instance method of sortable.
If you want to be even more precise, you can adjust top coordinate of this containment property as well so that it takes in consideration the click offset.
Like this for example:
jQuery(function($) {
  $("#rows").sortable({
    handle: ".handle",
    axis: "y",
    containment: '#main-table',
    start: function(e, ui) {
      // get the instance of the sortable.
      // instance method is new to jquery ui 1.11, for previous versions
      // you can use $(this).data()['ui-sortable'];
      var sort = $(this).sortable('instance');

      // this makes the placeholder fit with the row that's being dragged
      ui.placeholder.height(ui.helper.height());

      // containment property of the sortable instance is not the same
      // as the containment option. The property is calculated
      // from the option. You need to adjust bottom coordinates
      // to take into account the row you just removed from it and the click offset.
      sort.containment[3] += ui.helper.height() * 1.5 - sort.offset.click.top;

      // Since your handle is centered, and pointer coordinates are used
      // for sortable, but top coordinates are used for containment
      // you can have issues with top row. Adjusting with the click offset
      // will resolve the issue.
      sort.containment[1] -= sort.offset.click.top;
    },

    helper: function(e, row) {
      // From http://www.paulund.co.uk/fixed-width-sortable-tables.
      // Sets the width of each cell to be its original width.
      // This reverts the default behaviour of the row collapsing into a narrower stub when being dragged.
      row.children().each(function() {
        $(this).width($(this).width());

      });
      return row;
    }
  });
});

https://jsfiddle.net/f1nexjmz/4/

A: jQuery(function($) {
  $("#rows").sortable({
    handle: ".handle",
    axis: "y",
    containment: "#main-table",
    helper: function(e, row) {
        row.children().each(function() {
            $(this).width($(this).width());
        });
        return row;
    },
    start: function (e, ui) {
        var sort = $(this).sortable('instance');
        sort.containment[3] += ui.helper.height();
    }
  });
});


text:
Q: Specify shared/'common' values for configurations in CppProperties.json or CMakeSettings.json When using the "Open Folder" functionality of Visual Studio, the IDE searches for project settings and configurations in a special json file.  For CPP projects, this could be CppProperties.json.  For CMake projects, this could be CMakeSettings.json.
This json file contains a collection of one or more "configurations," such as "Debug" or "Release".  I will use a recent CMake project as an example:
"configurations": [
    {
      "name": "ARM-Debug",
      "generator": "Ninja",
      "configurationType": "Debug",
      "inheritEnvironments": [
        "gcc-arm"
      ],
      "buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
      "installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
      "cmakeCommandArgs": "",
      "buildCommandArgs": "-v",
      "ctestCommandArgs": "",
      "intelliSenseMode": "linux-gcc-arm",
      "variables": [
        {
          "name": "CMAKE_TOOLCHAIN_FILE",
          "value": "${workspaceRoot}/cmake/arm-none-eabi-toolchain.cmake"
        }
      ]
    },
    {
      "name": "ARM-Release",
      "generator": "Ninja",
      "configurationType": "Release",
      "inheritEnvironments": [
        "gcc-arm"
      ],
      "buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}",
      "installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}",
      "cmakeCommandArgs": "",
      "buildCommandArgs": "-v",
      "ctestCommandArgs": "",
      "intelliSenseMode": "linux-gcc-arm",
      "variables": [
        {
          "name": "CMAKE_TOOLCHAIN_FILE",
          "value": "${workspaceRoot}/cmake/arm-none-eabi-toolchain.cmake"
        }
      ]
    }

As you can see, I have two configurations with nearly identical properties.
My question: is it possible to define these common/shared properties once, in such a way as to allow the configurations to inherit them and avoid repeating myself?

A: The easier way is to define an environment at global level (outside of any configuration), such as:
{
  "environments": [
    {
      "namespace" : "env",
      "varName": "varValue"
    }
  ],

Then you can reuse that wherever you need to, e.g.:
  "cmakeCommandArgs": "${env.varName}",

You can also have multiple environments, and reuse them, like this:
{
  "environments": [
    {
      "environment": "env1",
      "namespace": "env",
      "varName": "varValueEnv1"
    },
    {
      "environment": "env2",
      "namespace": "env",
      "varName": "varValueEnv2"
    }

  ],
  "configurations": [
    {
      "name": "x64-Release",
      "inheritEnvironments": [
        "msvc_x64_x64", "env2"
      ],
      "cmakeCommandArgs": "${env.varName}",
.....
    }
  ]

the 'x64-Release' will inherit the variables's value in the environment called "env2" (namespace 'env')


text:
Q: Stored properties cannot be marked potentially unavailable with '@available' XCODE 14 ERROR Stored properties cannot be marked potentially unavailable with '@available' XCODE 14 ERROR
I have this error in Flutter project in XCode 14. One of the external packages were using:
@available(iOS 14.0, *)

A: Solution:
My current fix is:

flutter_inappwebview: ^5.4.4+3

A: Solution would be updating version in Podfile platform :ios, '14.0', pod update && Pod install


text:
Q: Keyframes Parameters with SASS I have created a rotating carousel in CSS, which I'm pretty happy with. It's included in the snippet. The original is on this CodePen.
It basically rotates the positions of four boxes. The total animation time is 8 seconds and I've set it up so it remains static for 20% of that, then moves the boxes for 5% and then waits again (run the snippet; I don't think I've explained it very well).
Now I want to parameterise it. Sass is my weapon of choice, and I can easily set up a few variables that would help. So right at the top of my styles, I have this:
$delays: 0s, -6s, -4s, -2s;
$fullanimtime: 8s;
$animationstops: 0%, 20%, 25%, 45%, 50%, 70%, 75%, 95%, 100%;

I use $fullanimtime as my animation-duration, and use the $delays list to configure the delays on my pos-XXXX styles:
.pos-1 {
  animation-delay: nth($delays, 1);
}
.pos-2 {
  animation-delay: nth($delays, 2);
}
.pos-3 {
  animation-delay: nth($delays, 3);
}
.pos-4 {
  animation-delay: nth($delays, 4);
}

This works like a charm, and by setting up $fullanimtime and $delays correctly, I can change the animation to run correctly for any time, be it 8 seconds, or 120 seconds.
The problem is that @keyframes use percentages. So if I set the other variables for a long animation time, the actual transitions that move the boxes get real slow: For 8 seconds, the transition runs for 400 ms, but for 120 seconds, they take 6 seconds, which is more annoying than cool.
So the $animationstops variable is supposed to let me configure reasonable timing. But that doesn't work.
For reasons I don't understand, I can't use the Sass nth function in a keyframe declaration, neither can I use a Sass variable.
@keyframes rotate-board {
  nth($animationstops, 1) {
    // This gives an error:
    // Invalid CSS after "nth": expected keyframes selector, was "($animationstop..."
  }
  $somevariable {
    // This gives an error:
    // Invalid CSS after " $somevalue ": expected ":", was "{"
  }
}

Is there a way around this, or have I found a limitation of Sass? And is there another pre-processor that I should use instead if I want to do this?

body {
  margin: 0;
  padding: 0;
}
.frame {
  height: 580px;
  width: 100vw;
  background: lightgrey;
  position: relative;
  box-sizing: border-box;
}

.box {
  width: calc(50% - 30px);
  height: calc(50% - 30px);
  top: 20px;
  left: 20px;
  position: absolute;
  animation-name: rotate-board;
  animation-duration: 8s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
}

.redbox {
  background: red;
}
.greenbox {
  background: green;
}
.bluebox {
  background: blue;
}
.orangebox {
  background: orange;
}

@keyframes rotate-board {
  0% {
    top: 20px;
    left: 20px;
    bottom: calc(50% + 10px);
    right: calc(50% + 10px);
  }
  20% {
    top: 20px;
    left: 20px;
    bottom: calc(50% + 10px);
    right: calc(50% + 10px);
  }
  25% {
    top: 20px;
    left: calc(50% + 10px);
    bottom: calc(50% + 10px);
    right: 20px;
  }
  45% {
    top: 20px;
    left: calc(50% + 10px);
    bottom: calc(50% + 10px);
    right: 20px;
  }
  50% {
    top: calc(50% + 10px);
    left: calc(50% + 10px);
    bottom: 20px;
    right: 20px;
  }
  70% {
    top: calc(50% + 10px);
    left: calc(50% + 10px);
    bottom: 20px;
    right: 20px;
  }
  75% {
    top: calc(50% + 10px);
    left: 20px;
    bottom: 20px;
    right: calc(50% + 10px);
  }
  95% {
    top: calc(50% + 10px);
    left: 20px;
    bottom: 20px;
    right: calc(50% + 10px);
  }
  100% {
    top: 20px;
    left: 20px;
    bottom: calc(50% + 10px);
    right: calc(50% + 10px);
  }
}

.pos-1 {
  animation-delay: 0s;
}
.pos-2 {
  animation-delay: -6s;
}
.pos-3 {
  animation-delay: -4s;
}
.pos-4 {
  animation-delay: -2s;
}

A: You could write your variables like this:
#{nth($animationstops, 1)}

I created a Sassmeister for you:
https://www.sassmeister.com/gist/7c9b06c6b5a7cc580b14cbd1b312c566
Here it is at work: https://codepen.io/anon/pen/PBeNLV
PS: Your animation is very beautiful! Congrats! :)

A: As ReSedano said, you can use the syntax #{$var} in order to resolve your problem.
You can also use the loops provided from Sass in order to create a more readable code with less lines.
You can improve the final section of your code related to pos-* with the for loop, like the following code.
$delays: 0s, -6s, -4s, -2s;
@for $i from 1 through 4 {
  .pos-#{$i} {
    animation-delay: nth($delays, $i);
  }
}

You can also try to create a loop for the problem you are asking for. For example i found that there is a pattern like aaaabbbb that, with an offset for each side, can map your case in order to reproduce what you want. With this logic i have created the following code.
$animationPerc: 0%, 20%, 25%, 45%, 50%, 70%, 75%, 95%, 100%;
$animationPos: 20px, calc(50% + 10px);
$animationOffset: 0, 2, 4, 6; // top, left, bottom, right
@keyframes rotate-board {
  @for $i from 0 to 9 {
    #{nth($animationPerc, $i + 1)} {
      top: nth($animationPos, 1 + (floor((nth($animationOffset, 1) + $i)/4) % 2));
      left: nth($animationPos, 1 + (floor((nth($animationOffset, 2) + $i)/4) % 2));
      bottom: nth($animationPos, 1 + (floor((nth($animationOffset, 3) + $i)/4) % 2));
      right: nth($animationPos, 1 + (floor((nth($animationOffset, 4) + $i)/4) % 2));
    }
  }
}


text:
Q: Using while True miltiple times I'm new here and this is my first question. Apologies for any shortcomings.
I'm trying practise using a simply code. This example has the below output:
*who are you?
Joe
Hello Joe. What is the password? (It is a fish)
hoki
Access granted
Hello Joe. What is the password? (It is a fish)*

The code I am using is:
while True:
    print('who are you?')
    name = input()
    if name != 'Joe':
        continue
    while True:
        print('Hello Joe. What is the password? (It is a fish)')
        password = input()
        if password !='hoki':
            continue
        print('Access granted')*

As im trying to get out of the second while True loop using the continue statement (if the answer to the password question is hoki) it asks again "Hello Joe. What is the password? (It is a fish)*
It should be ending and not asking me for the password again as I've entered the correct one.
Any advice is appreciated.
Thanks

A: Here's the solution
user_check = True
while user_check:
    print('who are you?')
    name = input()
    if name != 'Joe':
        continue
    while True:
        print('Hello Joe. What is the password? (It is a fish)')
        password = input()
        if password !='hoki':
            continue
        else:
            print('Access granted')
            user_check = False
            break

A: You can use a break statement in your code to end the loop.
while True:
    print('This loop will stop because of my break statement!')
    break

print('This will print out because we used the break statement!')

A: Problem with your code is that it is just using continue. There is no statement for program to break out of the while-loop.
You just need two break statements, like this:
while True:
    print('who are you?')
    name = input()
    if name != 'Joe':
        continue
    while True:
        print('Hello Joe. What is the password? (It is a fish)')
        password = input()
        if password !='hoki':
            continue
        print('Access granted')
        break # break inner loop
    break # break outer loop

A: Like some others said you should use break instead of continue but you'll also need to change your password check to be `password == 'hoki'

A: *

*remove the * before the first while statement, and after the print('Access granted)

*indent all code that follows so that it is executed within the while loop.

*finally, add break statements as per below:

while True:
    print('who are you?')
    name = input()
    if name != 'Joe':
        continue
    while True:
        print('Hello Joe. What is the password? (It is a fish)')
        password = input()
        if password !='hoki':
            continue
        print('Access granted')
        break
    break

This should give the desired outcome. A more "semantic" way of solving the problem might be this:
logged_in = False

while not logged_in:
    print('who are you?')
    name = input()
    if name == 'Joe':
        while not logged_in:
            print('Hello Joe. What is the password? (It is a fish)')
            password = input()
            if password =='hoki':
                print('Access granted')
                logged_in = True

# Code only accessible to logged-in user
print("Now let's do some things that only Joe can do...")

Hope this helps!

A: Instead of using a While True directly; make it While (variable). Then proceed with your logic. See example below:
a = True

while a:

     # apply logic
     # if you want to break this loop; assign False to a.

     b = True

     while b:

         # apply logic
         # if you want to break this loop; assign False to b

         # .... and so on

Hope this is helpful.


text:
Q: Появились ли в Стандарте С++ отражения? Есть у меня проект интерпретатора Basic, написанный на С++. Проект довольно давний, ему уже лет 20. Соответственно, начинался этот проект на заре использования С++.
В процессе написания интерпретатора выяснилось, что для задачи интерпретатора полезно было бы иметь возможность передавать информацию с этапа трансляции на этап выполнения. В частности, чтобы подключить пользовательские функции к исполняющей системе интерпретатора, хорошо бы иметь возможность передавать информацию об аргументах С++ функций с этапа трансляции на этап выполнения. Эти возможности называли тогда отражениями и тогда эти возможности отсутствовали в С++. Тем не менее, ходили разговоры, что эти возможности будут добавлены в С++.
В связи с этим вопросы:

*

*Появились ли в Стандарте С++ отражения?

*Если нет, то ожидаются ли или от отражений отказались?

A: *

*Нет, в C++ всё ещё нет отражений (reflections).

*Да, работа над ними ведётся. Вот одно из предложений.

Когда мы сможем их увидеть в стандарте? Неизвестно, но это одна из тех функциональностей, которую многие ждут. Тем более, что тепло принятые метаклассы завязаны на отражения.


text:
Q: Get dynamic Form Value from Django Forms I'm trying to get the totalPrice value from the changing value of the form field through JavaScript.
My view part:
if request.method == "POST":
        if (not closed):
            form = BookingForm(request.POST)
            if form.is_valid():
                booking = form.save(commit=False)
                booking.author = user
                booking.hotelName = hotel.name
                booking.save()
                success = "Success!"
            else:
                return render(request, "hotels/hotel.html", {
                    "form": form
                })
        messages.info(request, success)
        return HttpResponseRedirect(reverse("hotel", args=(hotel.id,)))
    else:
        return render(request, "hotels/hotel.html", {
            "hotel": hotel,
            "closed": closed,
            "message": message,
            "form": BookingForm()
        })

My HTML + JS Code:
{% if not closed %}

Book Now!

    <form method="POST">
        {% csrf_token %}

            {{ form.as_p }}

            <input type="submit" name="button" id="submit" value="Book">

    </form>

{% endif %}

And, my form (through ModelForm):
class BookingForm(ModelForm):
    class Meta:
        model = Booking
        fields = ['includeBreakfast', 'includeDinner', 'totalPrice']
        labels = {
            'includeBreakfast': 'Include Breakfast',
            'includeDinner': 'Include Dinner',
            'totalPrice': 'Total Price (in USD)'
        }

    #Visual stuff

the totalPrice is a FloatField in the Model, but When I try to retrieve this value from the POST, it results None, but I want it to take the dynamically changing value.

A: My previous answer regarding ${price} was incorrect.
If your javascript is correctly updating the totalPrice field, you might need to use the "Network" tab in your browser developer tools to confirm that this value is being POSTed.

A: The problem was in the widget of totalPrice field. Before it was this:
self.fields['totalPrice'].widget = TextInput(attrs={
            'id': 'totalPrice',
            'disabled': True, #<-- The issue
            'class': 'form-control',
        })

I was supposed to set a readonly, not a disabled. Now it works.
After:
self.fields['totalPrice'].widget = TextInput(attrs={
            'id': 'totalPrice',
            'readonly': 'readonly',
            'class': 'form-control',
        })


text:
Q: CSS doubts about resizing equally two boxes inline I'm trying to make two boxes where to put a chart and I'd like them to have same width for the entire width of page and autoresizing when I resize the page:

Meeting hours per room
<select id="years_rooms_used"></select>

<canvas id="chart_rooms_used"></canvas>

Meeting hours per customer
<select id="years_rooms_customer"></select>

<canvas id="chart_per_customer"></canvas>

I tried to put width: 50%; on both
* and assing width: 100% on middle_row_box's div but it didn't worked...how I could do that? And if I put two elements like  and a  inside a , shouldn't they appear side by side since in my case  looks like in a new row?
Cheers,
Luigi

A: You need to set width to LIs too. How they should know you want to resize them?
#middle_row_contents {margin: 0; padding: 0;}

#middle_row_contents li {
    display: inline-block;
    list-style-type: none;
    padding-right: 2%; /* ems and % aren't compatible, use the same units */
    *display: inline;
    width: 47%; /* lower than 48% because of a white-space gap between inline-block elements. Use float to avoid this gap. */
    background: red;
}

http://jsfiddle.net/x98g7c3k/

A: Try this javascript snippet
document.getElementById("hoursd_per_customers").style.width = (document.getElementById("hours_rooms_used").clientWidth - 10) + "px";

Hope it will work.
For more details, Click here...


text:
Q: ROWLOCK in Stored Procedure with Composite Key in SQL Server EDITED: I have a table with composite key which is being used by multiple windows services deployed on multiple servers.
Columns:
UserId (int) [CompositeKey],
CheckinTimestamp (bigint) [CompositeKey],
Status (tinyint)

There will be continuous insertion in this table. I want my windows service to select top 10000 rows and do some processing while locking those 10000 rows only. I am using ROWLOCK for this using below stored procedure:
ALTER PROCEDURE LockMonitoringSession
AS
BEGIN
    BEGIN TRANSACTION

    SELECT TOP 10000 * INTO #TempMonitoringSession FROM dbo.MonitoringSession WITH (ROWLOCK) WHERE [Status] = 0 ORDER BY UserId

    DECLARE @UserId INT
    DECLARE @CheckinTimestamp BIGINT

    DECLARE SessionCursor CURSOR FOR SELECT UserId, CheckinTimestamp FROM #TempMonitoringSession

    OPEN SessionCursor

    FETCH NEXT FROM SessionCursor INTO @UserId, @CheckinTimestamp

    WHILE @@FETCH_STATUS = 0
    BEGIN
        UPDATE dbo.MonitoringSession SET [Status] = 1 WHERE UserId = @UserId AND CheckinTimestamp = @CheckinTimestamp
        FETCH NEXT FROM SessionCursor INTO @UserId, @CheckinTimestamp
    END

    CLOSE SessionCursor
    DEALLOCATE SessionCursor

    SELECT * FROM #TempMonitoringSession
    DROP TABLE #TempMonitoringSession

    COMMIT TRANSACTION
END

But by doing so, dbo.MonitoringSession is being locked permanently until the stored procedure ends. I am not sure what I am doing wrong here.
The only purpose of this stored procedure is to select and update 10000 recent rows without any primary key and ensuring that whole table is not locked because multiple windows services are accessing this table.
Thanks in advance for any help.

A: (not an answer but too long for comment)
The purpose description should be about why/what for are you updating whole table. Your SP is for updating all rows with Status=0 to set Status=1. So when one of your services decides to run this SP - all rows become non-relevant. I mean, logically event which causes status change already occurred, you just need some time to physically change it in the database. So why do you want other services to read non-relevant rows? Ok, probably you need to read rows available to read (not changed) - but it's not clear again because you are updating whole table.
You may use READPAST hint to skip locked rows and you need rowlocks for that.
Ok, but even with processing of top N rows update of those N rows with one statement would be much faster then looping through this number of rows. You are doing same job but manually.
Check out example of combining UPDLOCK + READPAST to process same queue with parallel processes: https://www.mssqltips.com/sqlservertip/1257/processing-data-queues-in-sql-server-with-readpast-and-updlock/
Small hint - CURSOR STATIC, READONLY, FORWARD_ONLY would do same thing as storing to temp table. Review STATIC option:
https://msdn.microsoft.com/en-us/library/ms180169.aspx
Another thing is a suggestion to think of RCSI. This will avoid other services locking for sure but this is a db-level option so you'll have to test all your functionality. Most of it will work same as before but some scenarios need testing (concurrent transactions won't be locked in situations where they were locked before).
Not clear to me:

*

*what is the percentage of 10000 out of the total number of rows?

*is there a clustered index or this is a heap?

*what is actual execution plan for select and update?

*what are concurrent transactions: inserts or selects?

by the way discovered similar question:
why the entire table is locked while "with (rowlock)" is used in an update statement


text:
Q: how to write the identity function in haskell I have a function with type like this:
functionX :: [String] -> ([Integer] -> [Integer])

It is kind of like a mapping function that maps a specific String to a function with type as so.
Because I need to handle the call functionX [], which I think this call should return something called identity function, or whatever, how can I write it?

A: id is predefined as the identity function in haskell.  It has type id :: a -> a.
If you wanted, you could define your own easily:
myIdentityFunction :: a -> a
myIdentityFunction a = a


text:
Q: Making iframe work with variable in wordpress I have created a custom meta field and I would like to save an iframe link on my posts.
When I retrieve the link from my meta field with the code below:
echo soundcloud_get_meta( 'soundcloud_soundcloud_shortcode' );

I get the whole iframe as a text!
But when I give the link as in the code below it works
echo '';

I think it puts extra quotes on the first example and  get as a text.
How can I make this work with the first example?
UPDATE
this is in my functions.php file
function soundcloud_add_meta_box() {
    add_meta_box(
        'soundcloud-soundcloud',
        __( 'SoundCloud', 'soundcloud' ),
        'soundcloud_html',
        'post',
        'normal',
        'default'
    );
}
add_action( 'add_meta_boxes', 'soundcloud_add_meta_box' );

function soundcloud_html( $post) {
    wp_nonce_field( '_soundcloud_nonce', 'soundcloud_nonce' ); ?>

SoundCloud

        <?php _e( 'SoundCloud Shortcode', 'soundcloud' ); ?>

        <input type="text" name="soundcloud_soundcloud_shortcode" id="soundcloud_soundcloud_shortcode" value="<?php echo soundcloud_get_meta( 'soundcloud_soundcloud_shortcode' ); ?>">

<?php
}

function soundcloud_save( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! isset( $_POST['soundcloud_nonce'] ) || ! wp_verify_nonce( $_POST['soundcloud_nonce'], '_soundcloud_nonce' ) ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    if ( isset( $_POST['soundcloud_soundcloud_shortcode'] ) )
        update_post_meta( $post_id, 'soundcloud_soundcloud_shortcode', esc_attr( $_POST['soundcloud_soundcloud_shortcode'] ) );
}
add_action( 'save_post', 'soundcloud_save' );

A: I had to use html_entity_decode on my function to output as html


text:
Q: Is $\mathbb{Q} \times \mathbb{R}$ countable or uncountable? Problem:

Is $\mathbb{Q} \times \mathbb{R}$ countable or uncountable?

Attempt:
It's known that $\mathbb{Q}$ is countable, and $ \# \mathbb{R} = \#(0,1)$ is uncountable. I then use the fact that:
$$\mathbb{Q} \times \mathbb{R}=\bigcup_{x \in (0,1)}(\mathbb{Q} \times \{x\})>\mathbb{N\times N}$$
which shows that $\mathbb{Q} \times \mathbb{R}$ is uncountable.
Am i on the right track?

A: Note that
$$\mathbb{Q}\times\mathbb{R} \supseteq \{0\}\times\mathbb{R} \cong \mathbb{R}$$
Since $\mathbb{R}$ is uncountable, so must $\mathbb{Q}\times\mathbb{R}$

A: You were almost on the right track to prove the statement easily (you can proceed by your method, but it requires some more work to complete it).
Observe that $$\mathbb Q\times \mathbb R=\bigcup_{q\in\mathbb Q}(\{q\}\times\mathbb R)$$ Now suppose there exists a bijection $\phi$ between $\mathbb Q\times\mathbb R$ and $\mathbb N$.
Pick up one of the sets in the union, say $\{0\}\times\mathbb R=:A$. Then $A\subset \mathbb Q\times\mathbb R$ and is clearly in bijection with $\mathbb R$ say by $\psi$). Then $A$ is in bijection with $\phi(A)\subseteq \mathbb N$. Compose this with $\psi$ (or $\psi^{-1}$ as per your definition), and you get a bijection between a subset (proper or improper doesn't matter) of $\mathbb N$ with $\mathbb R$, which is impossible.
Thus there exists no bijection between $\mathbb Q\times\mathbb R$ and $\mathbb N$ and hence the former set is uncountable.

A: Depending on your definition of (un)countable, this could be simplified.
Definition: A set $S$ is said to be uncountable if there exists a surjective map $f:S\longrightarrow\Bbb{R}$ (or any other uncountable set you desire).

To show that $\Bbb{Q}\times\Bbb{R}$ is uncountable, consider $f:\Bbb{Q}\times\Bbb{R} \longrightarrow \Bbb{R}$ where $(a,\alpha)\mapsto \alpha.$ It is clear that $f$ is well defined. To show it is surjective, let $\beta \in \Bbb{R}.$ Then any element $(b,\beta)\in \Bbb{Q}\times\Bbb{R}$ has the property that $f(b,\beta)=\beta.$ Thus, $f$ is surjective. Since $f: \Bbb{Q}\times\Bbb{R} \longrightarrow \Bbb{R}$ is surjective, then $\Bbb{Q}\times\Bbb{R}$ must bet uncountable.

A: Cartesian product of countable and uncountable is uncountable.
Proof: If $A$ is countable and $B$ isn't, then
$$A \times B \supseteq \{a\} \times B$$ QED

Btw, Cartesian Product of Countable Sets is Countable.


text:
Q: How to get Message objects from Mail Raw headers in C# We are using sendgrid services to sending and receive emails from customer and need to parse the mail raw headers objects (Message-ID,Date etc.) from customer mail response in Asp.Net Core WeB API C# application.
Please find the example of Email Raw headers.
    Received: by mx0047p1mdw1.sendgrid.net with SMTP id 6WCVv7KAWn Wed, 27 Jul 2016 20:53:06 +0000 (UTC)
    Received: from mail-io0-f169.google.com (mail-io0-f169.google.com [209.85.223.169]) by mx0047p1mdw1.sendgrid.net (Postfix) with ESMTPS id AA9FFA817F2 for <example@example.comom>; Wed, 27 Jul 2016 20:53:06 +0000 (UTC)
    Received: by mail-io0-f169.google.com with SMTP id b62so81593819iod.3 for <example@example.comom>; Wed, 27 Jul 2016 13:53:06 -0700 (PDT)
    DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sendgrid.com; s=ga1; h=mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=GH5YTxjt6r4HoTa+94w6ZGQszFQSgegF+Jlv69YV76OLycJI4Gxdwfh6Wlqfez5yID 5dsWuqaVJZQyMq/Dy/c2gHSqVo60BKG56YrynYeSrMPy8abE/6/muPilYxDoPoEyIr/c UXH5rhOKjmJ7nICKu1o99Tfl0cXyCskE7ERW0=
    X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=Sq6LVHbmywBdt3sTBn19U8VOmelfoJltz8IcnvcETZsYwk96RBxN+RKMN5fOZSKw4j 15HrgdIFfyDmp67YK0ygvOITlTvZ6XY5I0PtnvDtAQt79kS3tKjI3QKJoEp/ZjIjSzlL KG7agl6cxFgBbIN0yHWBOvy3O+ZXY8tZdom1yOvULjmjW1U9JkdOs+aJ6zq4qhZX/RM/ tIgLB461eJ5V95iQDDc5Ibj9Cvy4vJfXLQRO0nLVQAT2Yz58tkEO1bDZpWOPAyUNneIL yhIWp+SpbuqhMA68mq0krG1PjmWalUbpVcGJIGuOKB9mQFFo/MqdrUCjvYnyo1jPLPeX psdQ==
    X-Gm-Message-State: AEkoousvdxmDoxLlTUYJ1AOmCGJv77xRBBlfKv6YrthH0M2NueMwlOxUD6t8nidE9uonXbdJ/DQy/chmHUnN//a4
    X-Received: by 10.107.6.101 with SMTP id 98mr38024553iog.41.1469652785829; Wed, 27 Jul 2016 13:53:05 -0700 (PDT)
    MIME-Version: 1.0
    Received: by 10.107.48.17 with HTTP; Wed, 27 Jul 2016 13:53:05 -0700 (PDT)
    From: Sender Name <example@example.com>
    Date: Wed, 27 Jul 2016 14:53:05 -0600
    Message-ID: <CAN_P_JMvV7ZpAQhOnDienypLrJmuhN=LQWweu4yScw4jQyXY2w@mail.gmail.com>
    Reference:
<CAN_P_JMvV7ZpAAhOnDienypLrJmuhN=LQWweu4yScw4jQyXY2w@mail.gmail.com>
<CAN_P_JMvV7Z6AGhOnDienypLrJmuhN=LQWweu4yScw4jQyXY2w@mail.gmail.com>
    Subject: Different File Types
    To: example@example.comom
    Content-Type: multipart/mixed; boundary=001a113f8ad03e85160538a4343c

I tried to get the above required objects by using mimekit nuget but facing below exception.
Code:
MimeMessage msg = new MimeMessage(/* Above strings */);

Exception:

A: You're using MimeKit incorrectly.
Here's how you would parse those headers with MimeKit:
using (var stream = File.Open (fileName)) {
    var headers = HeaderList.Load (stream);

    Console.WriteLine ("Message-Id: {0}", headers[HeaderId.MessageId]);
    Console.WriteLine ("Subject: {0}", headers[HeaderId.Subject]);
    Console.WriteLine ("Date: {0}", headers[HeaderId.Date]);
}

Or, if the headers are already in a string, you could do something like this:
using (var memory = new MemoryStream (Encoding.UTF8.GetBytes (stringValue), false)) {
    var headers = HeaderList.Load (stream);
}

If you would like to use the convenient MimeMessage API's for reading pre-parsed email addresses, references, etc. then all you need to do is make sure that the header input ends with a double set of newlines (\r\n\r\n or \n\n).
/* the last header should already end with "\r\n", so just add one more: */
using (var memory = new MemoryStream (Encoding.UTF8.GetBytes (stringValue + "\r\n"), false)) {
    var message = MimeMessage.Load (stream);

    Console.WriteLine ("Message-Id: {0}", message.MessageId);
    Console.WriteLine ("Subject: {0}", message.Subject);
    Console.WriteLine ("Date: {0}", message.Date);
}

A: Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication123
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "Received: by mx0047p1mdw1.sendgrid.net with SMTP id 6WCVv7KAWn Wed, 27 Jul 2016 20:53:06 +0000 (UTC)\n" +
                "Received: from mail-io0-f169.google.com (mail-io0-f169.google.com [209.85.223.169]) by mx0047p1mdw1.sendgrid.net (Postfix) with ESMTPS id AA9FFA817F2 for <example@example.comom>; Wed, 27 Jul 2016 20:53:06 +0000 (UTC)\n" +
                "Received: by mail-io0-f169.google.com with SMTP id b62so81593819iod.3 for <example@example.comom>; Wed, 27 Jul 2016 13:53:06 -0700 (PDT)\n" +
                "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sendgrid.com; s=ga1; h=mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=GH5YTxjt6r4HoTa+94w6ZGQszFQSgegF+Jlv69YV76OLycJI4Gxdwfh6Wlqfez5yID 5dsWuqaVJZQyMq/Dy/c2gHSqVo60BKG56YrynYeSrMPy8abE/6/muPilYxDoPoEyIr/c UXH5rhOKjmJ7nICKu1o99Tfl0cXyCskE7ERW0=\n" +
                "X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=DpB1CYYeumytcPF3q0Upvx3Sq/oF4ZblEwnuVzFwqGI=; b=Sq6LVHbmywBdt3sTBn19U8VOmelfoJltz8IcnvcETZsYwk96RBxN+RKMN5fOZSKw4j 15HrgdIFfyDmp67YK0ygvOITlTvZ6XY5I0PtnvDtAQt79kS3tKjI3QKJoEp/ZjIjSzlL KG7agl6cxFgBbIN0yHWBOvy3O+ZXY8tZdom1yOvULjmjW1U9JkdOs+aJ6zq4qhZX/RM/ tIgLB461eJ5V95iQDDc5Ibj9Cvy4vJfXLQRO0nLVQAT2Yz58tkEO1bDZpWOPAyUNneIL yhIWp+SpbuqhMA68mq0krG1PjmWalUbpVcGJIGuOKB9mQFFo/MqdrUCjvYnyo1jPLPeX psdQ==\n" +
                "X-Gm-Message-State: AEkoousvdxmDoxLlTUYJ1AOmCGJv77xRBBlfKv6YrthH0M2NueMwlOxUD6t8nidE9uonXbdJ/DQy/chmHUnN//a4\n" +
                "X-Received: by 10.107.6.101 with SMTP id 98mr38024553iog.41.1469652785829; Wed, 27 Jul 2016 13:53:05 -0700 (PDT)\n" +
                "MIME-Version: 1.0\n" +
                "Received: by 10.107.48.17 with HTTP; Wed, 27 Jul 2016 13:53:05 -0700 (PDT)\n" +
                "From: Sender Name <example@example.com>\n" +
                "Date: Wed, 27 Jul 2016 14:53:05 -0600\n" +
                "Message-ID: <CAN_P_JMvV7ZpAQhOnDienypLrJmuhN=LQWweu4yScw4jQyXY2w@mail.gmail.com>\n" +
                "Subject: Different File Types\n" +
                "To: example@example.comom\n" +
                "Content-Type: multipart/mixed; boundary=001a113f8ad03e85160538a4343c\n";

            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
            string pattern = "^(?'key'[^:]+):(?'value'.*)";

            StringReader reader = new StringReader(input);
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if ((line.Length > 0) && line.Contains(":"))
                {
                    Match match = Regex.Match(line, pattern);
                    string key = match.Groups["key"].Value.Trim();
                    string value = match.Groups["value"].Value.Trim();
                    if (!dict.ContainsKey(key))
                    {
                        dict.Add(key, new List<string>() { value });
                    }
                    else
                    {
                        dict[key].Add(value);
                    }

                }
            }
        }
    }

}


text:
Q: How to learn joomla 1.5? I'm a web designer and so I learnt everything essential needed for designers and now I can design the websites using joomla.
But I want to move myself to programmer. I have very basic knowledge of php and mysql. I wanted to know how can I enter into development with joomla.
Joomla has been very popular in the world but also it has not implemented so much effort for the users. It is providing a tutorial but randomly, so I'm confused how to start. There is no any sites step by step tutorials for joomla.
So, anyone please help me how to start on the topics. Could anyone provide a lists what to learn as to become a developer of joomla?

A: Well first of all, you need to know about the versions.
There are 2 types of Joomla releases. Long Term (Joomla 1.5 and 2.5) and Short Term (Joomla 3.x)
Joomla 1.5 is old and unsupported now so there is no need to look into it.
If you want to start developing for Joomla, then you simply need to read up on the documentation and start messing around with pre-made extensions. You will also need to do research on how MVC works if you are not already familiar with it.
Hope this helps

A: you can get help from a nice book such as Joomla! Programming


text:
Q: How do you handle validation in composite microservice request? Consider an application with two entities:

*

*User (contains basic user data, such as name)

*Passport (contains authentication credentials, i.e. password)

And two internal microservices:

*

*UserService (responsible for creating and managing users and their basic data)

*AuthService (responsible for user authentication and password handling)

The User entity belongs to the UserService and Passport entity belongs to the AuthService.
Those two services should be separated, because they solve very different tasks: profile data and authentication.
Also, consider we have a registration form with three fields:

*

*E-Mail

*Name

*Password

This form will trigger HTTP-request to the GatewayService, which intercepts all requests to the application and routes them to internal microservices (or composes/aggregates them).
Now, when gateway service receives the request with all the form data it needs to do the following:

*

*Call UserService to create new user (it will respond with generated userId).

*Call AuthService to create a passport for newly created user. It will need the userId received in step #1 and a password field from the original request.

This looks pretty straightforward, but what will happen if AuthService is unavailable on step #2? We will need to somehow separate those requests!
The classic approach is to use the eventual consistency and to create Passport entity via asynchronous call (we can place this request to the queue and process it in separate service). In order to do this we will send an asynchronous request to the AuthService passing userId and password to it, instead of step #2, so the step #1 will immediately return response to the client.
However, what if password field is not properly formatted (breaks validation rules)? The validation logic is only present in the AuthService, so we can't know if password is correct until the call is made to it. And now, the request is processed asynchronously, so we can't get back to user and tell him to correct the password.
SO, how do you properly handle validation in distributed composite requests to microservice application?

*

*The naive solution is to move validation logic to the GatewayService itself, but it's a terrible idea, because it will make it fat and will leak business logic from AuthService.

*The other idea is to provide an additional method for password validation and to call it prior to steps #1 and #2. It looks like a viable solution, but it will force us to have two methods for each business method in our microservices, one for prior validation and one for actual operation. Also, there is a time space between validation and operation, so the earlier correct value could become incorrect when operation is actually performed.

*We could split the form in two to avoid composite requests and ask user for password after asking for personal data and creating an account for him. However, this could lead to security problems, where user account could be intercepted by some other party who could guess the next userId. We could, use some additional security token, but it will introduce odd functionality to services and will make the whole setup more complex.
Also, this approach looks like an attempt to escape the problem, you can't always avoid composite requests.

*We could use full-scale distributed transactions, e.g. 2PC, but it will make the system dramatically complex and will mitigate the use of MSA in the first place.

*And the final idea is to merge those two services together, but it will make no sense in microservice architecture to do so.

A: Here is my thought
1.User Service  - should be responsible for
Creation of user which includes user name ,password (hashed) , email and any other profile data
validation of  input data against validation rules
validation of user using his password
pros
further adition of profile data is easy
finding and validatng user in single request
user related login in single place
2.Authentication Service should be responsible only to generate tokens based upon successful user validation via user service
these token should be used for further processing by all other services in ecosystem and will make sure proper authorisation
pros
future addition of services that will require user authentication and authorisation can work independently and will require only security token.
Generation of token based on previous token can be easy ,user will not need to enter his user name and password each time his token is about to expire.

A: Regarding #5, I really don't see that you are somehow committing a horrible violation of principles by merging into one service here (point 5), a kind of "UserManagementService" that takes care of both tasks; even if it can be argued that one MS should perform one task and do it well, these two are intimately related, IMHO.
Another option is to make UserService a sync client of AuthService (load balanced, with circuit breaker, whatever, to ensure availability of one instance), which would be basically the same as injecting the dependency for a password validation in "normal" code.
If this is a greenfield thing and you are not stuck with these two services, in general, I would go for a simpler first implementation, and resist the impulse for optimizations, as these tend to be premature, or a unwarranted commitment to the purity of principles/dogmas. You yourself are aware of the complexities you could introduce (2PC) plus you have your requirement there ("so we can't get back to user and tell him to correct the password").

A: I agree with #5. The two services will have many dependencies since accessing UserService will always relate to AuthService, and they probably access related data.
If you separate them you may need to separate their shared logic like generating the passport. It can be in a service that has an operation that receives a userID either from AuthService (after validating credentials) or from UserService (after registration).
Also handling the absence of AuthService will raise questions about other scenarios, like if the user already registered and cannot login, how do you handle it?.. If you're showing an error message, why not when they register?..  just a question for more thoughts about your requirements.
Cheers


text:
Q: Injecting commands by sending keystrokes to a command windows? I have a command prompt window that runs a web based piece of software. I want to make a program in C# that injects commands into the running command prompt window.
Any pointers?
Thanks, Paul.

A: Quick and dirty method:
use SetFocus to set the focus to the cmd window, then use SendInput to send keystrokes to the cmd window.
You can use this P/Invoke definition to call SendInput from c#:
[DllImport("user32.dll", SetLastError=true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

and this one for SetFocus
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);

In order to get the window handle that you required for SetFocus, you can use FindWindow  or perhaps get the appropriate cmd process using Process.GetProcessesByName and then use the MainWindowHandle property.


text:
Q: How to make different word with different colour tkinter python? I am making UI with Tkinter and stuck a little bit with coloring words.
Goal is to make first word with red foreground second word with yellow foreground and do the same with next line of words:
Word_A (foreground red) Word_B (foreground yellow)
Word_CCC (foreground red) Word_DDD (foreground yellow)
Every word in my real program is different length (as the same in this example).
My Code:
 class Window(Frame):
    def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master

    S = Scrollbar(self.master)
    T = Text(self.master, height=40, width=100)
    S.pack(side=RIGHT, fill=Y)
    T.pack(side=RIGHT, fill=X, expand=True)
    S.config(command=T.yview)
    T.config(yscrollcommand=S.set)

    for w in [('Word_A', 'Word_B'), ('Word_CCC', 'Word_DDD')]:

        T.insert(INSERT, w[0])
        T.insert(END, "  ")

        T.tag_add("start", "1.0", "1.5")
        T.tag_config("start", foreground="red")

        T.insert(END, w[1])
        T.insert(END, "\n")

        T.tag_add("here", "1.5", "10.0")
        T.tag_config("here", foreground="yellow")

top = Tk()
top.geometry('1000x1000')
app = Window(top)

top.mainloop()

A: You can directly add the tag to the word when you insert it:
text.insert(<index>, <word>, <tag>).
Here is an example:
import tkinter as tk

words = [('Word_A', 'Word_B'), ('Word_CCC', 'Word_DDD')]

root = tk.Tk()
text = tk.Text(root)
text.pack()
text.tag_configure('red', foreground='red')
text.tag_configure('yellow', foreground='yellow')

for w1, w2 in words:
    text.insert('end', w1, 'red')
    text.insert('end', ' ')
    text.insert('end', w2, 'yellow')
    text.insert('end', '\n')

root.mainloop()


text:
Q: object cant access class properties I have a subclassed Button with a couple of properties
public class ZButton : Button
{
    private string UIB = "I";
    public int _id_ { get; set; }
    public int rowIndex { get; set; }
    protected override void OnClick(EventArgs e)
    {
        Form frmNew = new Form(UIB);
        frmNew.ShowDialog();
        base.OnClick(e);
    }
}

I placed that button on the form and here is the code for that button in the form.
private void zButton1_Click(object sender, EventArgs e)
    {
        rowIndex = dataGridView1.CurrentRow.Index;
        _id_ = Convert.ToInt16( dataGridView1["id_city", rowIndex].Value.ToString());

    }

I cant access those properties (rowIndex) and (id) and compiler gives errors
The name 'rowIndex' does not exist in the current context

I am rather new to C# so I must be missing something obviuos.

A: rowIndex and _id_ are properties of your zButton, they are not accesible directly in your form. So if you need to access them in the click event, you have to cast the sender to a zButton and access the properties of that instance.Something like this:
private void zButton1_Click(object sender, EventArgs e)
{
    zButton but=(zButton)sender;
    but.rowIndex = dataGridView1.CurrentRow.Index;
    but._id_ = Convert.ToInt16(dataGridView1["id_city",but.rowIndex].Value.ToString());
}

A: If method zButton1_Click is a member of your form class, then it can directly access properties of the same class or its ancestor classes, not properties of aggregated objects like your button.
In order to access your button's properties, you should explicitly specify which object's properties you are trying to access. This means that if you want to access a property of an aggregated button zButton1, you should replace
dataGridView1["id_city", rowIndex]

with
dataGridView1["id_city", zButton1.rowIndex]

A: cast your sender to button.
var button = sender as zButton;
    if (button != null)
    {
        button.rowIndex ...
        ...
    }


text:
Q: Attempting to move a word to the end of the line with sed I'm trying to select all email addresses and move them to the end of the line using sed. I've successfully figured out how to select the email addresses but can do nothing more than append $ to the end - is there a way to combine the & (to paste back in the selected words) and $ (to go to end of line) operators to accomplish what I'm looking to do? Or should I look for a different method?
-bash-3.2$ sed "s/[a-z]*@*\.*\.[a-z].[a-z]/& $/" address
Xiao Li, lxiao@unc.edu $, 6705462234, Jackson, NC 764
Elizi Moe, emoe@ncsu.edu $, 5208534566, Tempe, AZ 85282
Ma Ta, mta@yahoo.com $, 4345667345, Austin, TX 91030
Diana Cheng, dcheng@asu.edu $, 5203456789, Matitsi, WY 4587
Jackson Five, jfive@ncsu.edu $, 5206564573, Kyenta, AZ 85483
Adi Srikanth Reddy, sadi1@imap1.asu $.edu, 6578904566, Wyo, WS 67854
Natkin William, wnatkin@imap28.asu $.edu, 8044344528, Richmond, VA 22345

*note: these are false names, addresses & phone numbers.

A: You can try this sed command:
sed -r "s/^([^,]+)(,[^,]+)(.*)/\1\3\2/g" address

Explanation

*

*$^([^,]+) captures everything from start of line upto but not including the first comma (i.e. the first column)  into \1

*(,[^,]+) captures the first comma and everything upto but not including the second comma into \2 (i.e. the second column, the email)

*(.*) captures the rest into \3

*then the columns are swapped using \1\3\2 backreference to the capture groups marked by the parentheses

A: Similarly you can do this with perl too..
%_Host@User:/home/Gaurava/study/temp> perl -pe 's/^(.+?),(.+?),(.+)$/$1,$3,$2/g' names.txt
Xiao Li, 6705462234, Jackson, NC 764, lxiao@unc.edu $
Elizi Moe, 5208534566, Tempe, AZ 85282, emoe@ncsu.edu $
Ma Ta, 4345667345, Austin, TX 91030, mta@yahoo.com $
Diana Cheng, 5203456789, Matitsi, WY 4587, dcheng@asu.edu $
Jackson Five, 5206564573, Kyenta, AZ 85483, jfive@ncsu.edu $
Adi Srikanth Reddy, 6578904566, Wyo, WS 67854, sadi1@imap1.asu $.edu
Natkin William, 8044344528, Richmond, VA 22345, wnatkin@imap28.asu $.edu
%_Host@User:/home/Gaurava/study/temp>


text:
Q: Conditional extraction of XML attributes with xmlstarlet I have some XML (say, file minimal.xml) that contains error and warning messages in the following format:
<?xml version="1.0" encoding="UTF-8"?>
  <messages>
     <message subMessage="RSC-004">RSC-004, ERROR, [File 'OEBPS/Text/pdfMigration.html' could not be decrypted.], epub20_encryption_binary_content.epub</message>
     <message subMessage="RSC-012">RSC-012, ERROR, [Fragment identifier is not defined.], OEBPS/toc.ncx (24-67)</message>
     <message subMessage="RSC-012">RSC-012, ERROR, [Fragment identifier is not defined.], OEBPS/toc.ncx (30-82)</message>
     <message subMessage="RSC-012">RSC-012, ERROR, [Fragment identifier is not defined.], OEBPS/toc.ncx (36-81)</message>
     <message subMessage="RSC-012">RSC-012, ERROR, [Fragment identifier is not defined.], OEBPS/toc.ncx (42-75)</message>
     <message subMessage="RSC-012">RSC-012, ERROR, [Fragment identifier is not defined.], OEBPS/toc.ncx (48-61)</message>
     <message subMessage="HTM-023">HTM-023, WARN, [An invalid XHTML Named Entity was found: '&0;'.], OEBPS/Text/pdfMigration.html (18-199)</message>
     <message subMessage="HTM-023">HTM-023, WARN, [An invalid XHTML Named Entity was found: '&l0xb'.], OEBPS/Text/pdfMigration.html (291-6)</message>
  </messages>

I'm looking for a way to extract the subMessage attribute value for all message elements that represent an ERROR (which can be identified from the presence of ERROR in the message  element's text value). I'm using xmlstarlet. After some searching I found this somewhat similar case, so I adapted that as follows:
xmlstarlet sel -t -v '/messages[contains(message,"ERROR")]/message/@subMessage' minimal.xml

Result:
RSC-004
RSC-012
RSC-012
RSC-012
RSC-012
RSC-012
HTM-023
HTM-023

This is not what I expected, since these are the subMessage values of all message elements! As a further test I modified the query to extract only warnings:
xmlstarlet sel -t -v '/messages[contains(message,"WARN")]/message/@subMessage' minimal.xml

In this case the result is empty! I'm fairly new to xmlstarlet and I suspect I'm overlooking something obvious here. Any help greatly appreciated!
BTW some info on the xmlstarlet version I'm using:

compiled against libxml2 2.9.2, linked with 20903
  compiled against libxslt 1.1.28, linked with 10128

A: Try this
xmlstarlet sel -t -v '/messages/message[contains(.,"ERROR")]/@subMessage' minimal.xml

With /messages[contains(message,"WARN")] you erroneously tried to check the content of the messages element and not of each message element.

A: You need to move the predicate to the message, like this:
xmlstarlet sel -t -v "/messages/message[contains(.,'WARN')]/@subMessage" minimal.xml


text:
Q: What is the "pdm" stat in the "rms" R package? I am building an ordinal logistic regression model (ORM). In order to fit my ORM model, I am using the 'orm' function of 'rms' package from R (http://cran.r-project.org/web/packages/rms/rms.pdf).
Now I am trying to assess the goodness of fit of my model. By reading the R documentation, I can see the following statement in the 'stat' property of the 'orm' object (p. 98):

(...) Nagelkerke $R^2$ index, the $g$-index, $gr$ (the $g$-index on the odds
  ratio scale), and pdm (the mean absolute difference between 0.5 and
  the predicted probability that $Y\geq q$  the marginal median) (...).

I don't have enough background to understand the short description of the pdm measure. But when I try to do more research on this measure, I am not able to find related material (e.g. I've been finding "prescription drug misuse"). In summary, my question is:
Would you know if the 'pdm' measure has some synonym which is more widely used? Or can you provide some references where I can study the pdm metric?

A: I don't know yet about the background of the statistic but below is an illustration how it is computed.
$$pdm = \frac{1}{n} \sum_{k=1}^n \left| \hat{P}(Y \geq median|X_k) - 0.5 \right| $$
It is an indication of how much the conditional predicted probability varies around the point of the marginal median.
library(rms)

###
###  generate some data according to a logit model
###
set.seed(1)
n = 10^2
k = 5
x = runif(n,-2,2)  # predictor
noise = rnorm(n,0,1)   # noise
y = x + noise        # latent variable
bounds = seq(-2,2,1) # values to be predicted
z = as.numeric(sapply(y, FUN = function(yi) sum(bounds<yi)))  # ordinal variable

### compute ordinal regression
mod = orm(z ~ x, family =probit)

### marginal median of the data
median = mod$stats[3]
### predictions hat p(y>=median | x) for all x in the data
pr = coef(mod)[median] + coef(mod)[k+1]*x
prs = pnorm(pr)
### mean absolute deviation  ... 0.3308655
mean(abs(prs-0.5))
### value from the function  ... 0.3308655
mod$stats[14]

A: This link: https://www.rdocumentation.org/packages/rms/versions/5.1-0/topics/validate.lrm
describes pdm as a "new" metric, which would imply that is has not been used before.


text:
Q: Overlay panel (above another) I am learning how to use Swing and found myself quite difficult task.
What I am trying to accomplish: I want to have panel (call it menu panel) on the left side (let's say 100px width) and the second panel (call it content panel), which takes the rest of available place.
In menu panel there are 3 buttons. When I press on of them, to the right side of menu panel (over content panel) second menu panel (submenu) should appear (and it should start in the middle of button which was pressed).
It may be hard to understand, so I've created simple draft:

I tried JLayeredPane but there were problems with resizing window (elements in Layered Pane didn't resize).

A: JLayeredPane miss implementations for LayoutManager, you have to setPreferredSize or setBounds manually for sizing/place JComponents,
there is one possible workaround you can add ComponentListener to the JFrame, then on componentResized(ComponentEvent e) you can resize/replace JComponent(s) to the desired Bounds
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class LayeredPaneWithOverlap {

    private JTextArea textArea = new JTextArea(2, 10);
    private JPanel textPanel = new JPanel(new BorderLayout());
    private JTable table = new JTable(30, 5);
    private JScrollPane scroll = new JScrollPane(table);
    private JLayeredPane layer = new JLayeredPane();
    private JFrame frame = new JFrame("Frame with resiziable JLayeredPane");

    public void makeUI() {
        textArea.setBorder(new LineBorder(Color.DARK_GRAY));
        textArea.setText("Frame with resiziable JLayeredPane");
        textPanel.setOpaque(false);
        textPanel.add(textArea, BorderLayout.NORTH);
        Font font = textArea.getFont();
        FontMetrics fontMetrics = textArea.getFontMetrics(font);
        int h = fontMetrics.getHeight() + frame.getInsets().top +
                textPanel.getInsets().top + textArea.getInsets().top
                + textArea.getInsets().bottom;
        scroll.setBounds(0, h, 400, 300);
        layer.add(textPanel, new Integer(2));
        layer.add(scroll, new Integer(1));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent e) {

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        resizeAll();
                    }
                });
            }
        });
        frame.setLocationRelativeTo(null);
        frame.add(layer);
        resizeAll();
        frame.setVisible(true);
    }

    void resizeAll() {
        Insets insets = frame.getInsets();
        int w = frame.getWidth() - insets.left - insets.right;
        int h = frame.getHeight() - insets.top - insets.bottom;
        textPanel.setSize(w, h);
        scroll.setSize(w, h - scroll.getY());
        layer.revalidate();
        layer.repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new LayeredPaneWithOverlap().makeUI();
            }
        });
    }
}

A: You can set a layoutmanager for the layered pane, javax.swing.OverlayLayout uses the full available space and allows resizing.
JLayeredPane layer = new JLayeredPane();
layer.setLayout(new OverlayLayout(layer));

You probably don't want the submenu to occupy the fullspace.  To avoid it you can override its get…size-methods.  Or you can add a second LayeredPane (for it's transperancy and it's layoutmanager), set a normal BoxLayout and use a spacer.
JPanel normalContents = new JPanel();
layer.add(normalContents, JLayeredPane.DEFAULT_LAYER);
JLayeredPane subMenuAuxiliaryLayer = new JLayeredPane()
subMenuAuxiliaryLayer.setLayout(new BoxLayout(subMenuAuxiliaryLayer, BoxLayout.LINE_AXIS));
layer.add(subMenuAuxiliaryLayer, JLayeredPane.PALETTE_LAYER);
JPanel submenuContents = new JPanel();
subMenuAuliliaryLayer.add(submenuContents);
subMenuAuxiliaryLayer.add(Box.createHorizontalGlue());

A: contentPanel.setLayout(null); // Absolute positioning of children.

@Override
public void actionPerformed(ActionEvent evt) {
    final JButton btn = (JButton) evt.getSource();
    final int buttonY = btn.getY(); // Must be final for usage in new Runnable object.

    SwingUtilities.invokeLater(new Runnable() { // Return fast from event handling.

        @Override
        public void run() {
            JPanel child = new JPanel();
            child.setBackground(Color.RED); // So we'll see it.
            child.setBounds(0, buttonY, 100, 300);
            contentPanel.removeAll(); // Clear content panel of prior additions.
            contentPanel.add(child); // Add a new panel.
            contentPanel.repaint(10L);
        }
    });
 }

A: The JLayeredPane works by defualt with no Layout manager, which means that you are using absolute positioning and no resizing. You could add a resize listener and adjust positions and size of inner components from code, as you see fit.
If you don't want to do this from code, you will need a layout manager, nothing fancy, just something to fill the container as it resizes. But here's the thing... if you add a layout manager, it will layout the components as if they are all in one layer, but most layout managers don't overlap their children so they are useless. The only one you could use is the OverlayLayout - it can also resize children. But using an OverlayLayout with JLayeredPane is overkill. You can just use OverlayLayout with a JPanel. So, yes, JLayeredPane is kind of useless. I recommend using a JPanel with an OverlayLayout instead.
Here is how to set things up so that you can have great control over almost any overlapping UI scenario out there: Using a JPanel with an OverlayLayout, have a separate transparent JPanel for each layer. In this way you can combine various LayoutManagers on different layers, by setting a diferent layout manager for each pane, including absolute positioning if necessary. Then add your visible components inside the panels representing the layers. Don't add them directly to the OverlayLayout panel. Just make sure that all of the JPanels you are using as layers have setAlignmentX and Y to center (0.5f) so that they fill the entire OverlayLayout panel as it resizes.


text:
Q: APCu TTL not working php 7.0 By specifying the TTL, the item should be aged out of the cache. But it is not working. This is very very simple. the TTL is set to 1 second. Have I made a mistake?
My version;
PHP 7.0.12-1+deb.sury.org~xenial+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.12-1+deb.sury.org~xenial+1, Copyright (c) 1999-2016, by Zend Technologies

My script;
cat apcu.php
<?php

$key="KEY";

function xxx($key) {
  if (apcu_exists($key)) {
    print ("In Store\n");
    $value = apcu_fetch($key);
    var_dump($value);
  } else {
    $value = "Hello Big Daddy";
    apcu_add($key, $value, 1);
    print ("Not in store, adding\n");
  }
}

xxx($key);
sleep(2);
xxx($key);
sleep(3);
xxx($key);

Output;
php apcu.php
Not in store, adding
In Store
string(15) "Hello Big Daddy"
In Store
string(15) "Hello Big Daddy"

I do not think the item should be in the Cache on the second call.
But even if someone said it should, then it should certainly not be in the Cache on the third call.

A: When apc.use_request_time is set to true, which is the default, this is what happens -- the SAPI request start time is used for TTL calculations, not the time each function is called.


text:
Q: Is there a clang-format setting that will expand tabs to spaces in comments? I am using VSCode with clang-format, and I have the editor set to insert spaces for tabs, and I am using the following clang-format (LLVM v14.0.0) options:
"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: LLVM, UseTab: Never, IndentWidth: 4, TabWidth: 4, IndentCaseLabels: true, ColumnLimit: 0, BreakBeforeBraces: Allman, ReflowComments: true }"

However, if I format the following code, which has a mix of spaces and tabs in the comment block, the tabs inside the comment block are not replaced with spaces. (EDIT: It appears Stack Overflow's code block replaces all tabs with spaces..."This line has preceeding tabs" should have tab characters before the text.)
#include <stdio.h>

/**
 * @brief       This is a comment with mixed spaces and tabs.
 *                      This line has preceeding tabs.
 */
int main()
{
    println("Hello, World!\r\n");

    return 0;
}

I've looked through the clang-format options but have been unable to figure out how to get clang-format to replace the tab characters with spaces inside the comment block.  Is there a clang-format option that will do this?


text:
Q: Expand All Folders using fuel ux treeview I´m using fuelux treeview to display a list , but I want expand all folders or nodes when page load.
I´m using fuelux.tree.min.js.
Below the code for load treeview:
       $('#trvMembers').ace_tree({
           dataSource: treeDataSource,
           loadingHTML: '

',
           'open-icon': 'ace-icon tree-minus',
           'close-icon': 'ace-icon tree-plus',
           'selectable': true,
           'selected-icon': null,
           'unselected-icon': null

       });

The questions is: is there any parameter or function to expand all folders when load page?

A: You can call $().tree('discloseAll');on a Fuel UX tree and it will open all the visible nodes, but I don't know about Ace Admin trees. See the following documentation.