text:
Q: JSON Parsing using Jackson/Gson Java I have the following Json
{
   "messages":[
      {
         "message":{
            "body":"Foo",
            "username":"XYZ"
         }
      },
      {
         "message":{
            "body":"HI",
            "username":"ABC"
         }
      }
   ],
   "response":{
      "status":200
   },
   "more":true
}

I build Custom classes My container class Result holds a List objects a Response object which contains a status and a boolean.
public class Message {

  @SerializedName("body")
  public String body;

  @SerializedName("username")
  public String username;

  @Override public String toString() {
    return "Message{" + "body=" + body + ", username=" + username + '}';
  }
}

public class Response {
  public int status;
}

public class SearchResponseST {
  @SerializedName("messages")
  public Message[] messages;
  public Response response;
  public boolean more;
}

In my main class I do:
SearchResponseST response =
   gson.fromJson(reader, SearchResponseST.class); Message[] results = response.messages;

If I  eliminate the "message": and start the array directly, I am able to deserialize successfully using Gson.
How should I be parsing it with the current structure?

A: Though this does not answer your question directly, because I do not use Gson.  I have always used the org.json.simple package to parse JSSON.   you can read about it here: http://www.mkyong.com/java/json-simple-example-read-and-write-json/  Just throw the JSON into the parser, and get the data you want out.   Data is accessed just like you would access a HashMap (for JSONObject) or ArrayList (for JSONArray).
EDIT with parsing code:
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(new FileReader("file.txt"));
    JSONArray array = (JSONArray) obj.get("messages");
    for (Object o : array) {
      JSONObject jo =(JSONObject)o;
      JSONObject messageObject = (JSONObject)jo.get("message");
      System.out.println(messageObject.get("body"));
      System.out.println(messageObject.get("username"));
    }

A: For a JSON like this
 {
       "messages":
        [
          {"body": "Foo", "username": "XYZ"   },
          {"body": "HI",  "username": "ABC"  }

        ],
        "response": {"status": 200 },
        "more": true
    }

try Container object designed like
Container { List<Message> messages;Response response;boolean more;}

BUT for the JSON you have posted, the Container object should be
Container { public HashMap[] messages;  public boolean more;    public Response response; }


text:
Q: Apache rewrite rule based on a host I have the following configuration, basically its a reverse proxy in front of grafana. I forward the /logout request to the auth server with redirect url and the /login url to /login/generic_oauth.
I want to redirect the /logout to auth server only when the request is from grafana itself that is only if the grafana ui makes the request.
If the request is made by any other origin it should go to the reverse proxy and back. Basically when I logout the user from my angular app I to logout the user my grafana app too. But as I have chained the /logout to the auth server redirect I get a cors error when I make the request.
  RewriteEngine on
  RewriteRule ^/logout - [C]

  I want to excute this rule only if the request is from http://grafana-ip:3001
  RewriteRule . "https://auth-server-ip:31443/auth/realms/MDC/protocol/openid-connect/logout?redirect_uri=http://auth-server-ip:8081/login" [NE,R=302,CO=grafana_sess:INVALID:;]

  RewriteRule ^/login$ /login/generic_oauth [L,R=302]

  ProxyPass / http://grafana-ip:3001/
  ProxyPassReverse / http://grafana-ip:3001/
  RequestHeader set X-Forwarded-Proto "https"

  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Max-Age "1000"
  Header always set Access-Control-Allow-Headers "*"

Is there any way I can execute the rule as it is when request is from grafana-ip but not when it is form any other origin

A: Since you proxy / to the backend, and your clients only request URL's on your proxy w/ referers referencing your proxy, you really have no reason to make the /logout handling conditional. Which is good because you have no ability to discriminate on anything for the same reasons.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alter variable directly or use a setter function? Which is best practice when setting a variable such as a page title tag from within the page controller?
I have:
class About extends Controller {

public function Index()
{
    $this->view->pageTitle = 'test 123' ;
    $this->view->metaDescription = 'Description here' ;
    $this->view->metaKeywords = 'dog, cat, monkey' ;
    $this->view->render('about/about') ;
}
}

Or should I use a setter function like:
$this->view->setPageTitle('My Title') ;

A: Neither. View should request data, that it needs, from model layer and decide, based on acquired data, which templates should be used to generate response.
What you currently have is a dumb template. Since there is no real view, you are not implementing MVC.


text:
Q: Exclude values existing in a list that contains words like I have a list of merchant category:
[
  'General Contractors–Residential and Commercial',
  'Air Conditioning, Heating and Plumbing Contractors',
  'Electrical Contractors',
  ....,
  'Insulation, Masonry, Plastering, Stonework and Tile Setting Contractors'
]

I want to exclude merchants from my dataframe if df['merchant_category'].str.contains() any of such merchant categories.
However, I cannot guarantee that the value in my dataframe has the long name as in the list of merchant category. It could be that my dataframe value is just air conditioning.
As such, df = df[~df['merchant_category'].isin(list_of_merchant_category)] will not work.

A: If you can collect a long list of positive examples (categories you definitely want to keep), & negative examples (categories you definitely want to exclude), you could try to train a text classifier on that data.
It would then be able to look at new texts and make a reasonable guess as to whether you want them included or excluded, based on their similarity to your examples.
So, as you're working in Python, I suggest you look for online tutorials and examples of "binary text classification" using Scikit-Learn.
While there's a bewildering variety of possible approaches to both representing/vectorizing your text, and then learning to make classifications from those vectors, you may have success with some very simple ones commonly used in intro examples. For example, you could represent your textual categories with bag-of-words and/or character-n-gram (word-fragments) representations. Then try  NaiveBayes or SVC classifiers (and others if you need to experiment for possibly-bettr results).
Some of these will even report a sort of 'confidence' in their predictions - so you could potentially accept the strong predictions, but highlight the weak predictions for human review. When a human then looks at, an definitively rules on, a new 'category' string – because it was highlighted an iffy prediction, or noticed as an error, you can then improve the overall system by:

*

*adding that to the known set that are automatically included/excluded based on an exact literal comparison

*re-training the system, so that it has a better chance at getting other new similar strings correct

(I know this is a very high-level answer, but once you've worked though some attempts based on other intro tutorials, and hit issues with your data, you'll be able to ask more specific questions here on SO to get over any specific issues.)


text:
Q: What does `printf` do in rc.local? I've encountered an /etc/rc.local script that gets some data and uses printf on it.
My question is: where does that data that is printed go when rc.local is executed on startup? Is there a log file or something I can look in to get it?

A: Unless you redirect the output, it will be printed on the screen during the boot process. The boot messages are supressed / hidden and go by fast.
Remove the boot options quiet and splash to see the messages.
See How can I show or hide boot messages when Ubuntu starts? for details.
They should be in the logs, ( /var/log/messages ) and/or in dmesg


text:
Q: Is there a way to use putty without authentication? I am trying to access a university server using putty SSH however I don't have a key, all i have is a username and password. Whenever I try to connect I either get the no supported authentication error (server sent public key). Any advice?

A:
Whenever I try to connect I either get the no supported authentication error (server sent public key).

The SSH server always sends a list of acceptable auth methods. In this case, it sent a list consisting only of one method – "public key" – so that's the only method PuTTY will try. (Which it cannot try because you don't have a keypair, so it'll just give up.)

my supervisor said the server has been set up for password authentification however I haven't found where I can do that on putty

There is no option for that. If the server allowed password authentication, PuTTY would have attempted to use it automatically.
If an auth method is disabled on the server, there's nothing a client can do to make it work – sure it can try requesting it, but the server will just refuse anyway, for the same reason why it didn't offer that mechanism in the first place. So you probably won't find any client which will bother including an option to try disabled mechanisms.
It's possible that you might have gotten the wrong server address; or that someone else changed its configuration and your supervisor was unaware of that.

Is my best option using sshd instead of putty?

No matter what client you use, it won't be able to use auth mechanisms that the server doesn't offer.
Note that 'sshd' is the OpenSSH server (daemon); the OpenSSH client is 'ssh'.

A: If the server was truly set to not accept password authentication,
you need in this case ask your supervisor the missing
authentication key (and how to use it).
If your supervisor is convinced that he has set up access via password
to the server, this might be blocked by a wrong setting on the server
where password authentication was not fully enabled.
You haven't mentioned your operating system and putty version,
so I can't give a detailed answer.
The SSH server configuration file may in most cases be found in Linux
inside the file /etc/ssh/sshd_config.
The two important settings here are:

*

*PasswordAuthentication to yes

*ChallengeResponseAuthentication to yes
If changing any of the above, the ssh system service needs restarting
(reboot might be simpler).


text:
Q: use Yourls bulk link shortener api and integrate it in form with javascript and HTML I want to integrate below api with my form, where user can input urls and on submit they should get result on same page just below input.
And result should be one url per line or in table rows.
These are official Instruction for api use

Add in your api request the parameter action=bulkshortener
      Send the list of the URLs to be shortened using the parameter urls[].
      The response contains each shortened URL in a single line.

Example
Request API:
http://example.com/yourls-api.php?signature=ursecretkey&action=bulkshortener&urls[]=http://url1&urls[]=http://url2

Result: On result page it only shows shorten links in single line separated by single space only.
http://example.com/zy1071 http://example.com/ha52ql


text:
Q: How to repeat row N times and increment date by 1 for each new row in Google Sheets? I have rows with start and end date. I need to repeat each row N times and increment new date column by one.
N = the number of days between the start date and en date
My table:

Column A
Start date
End date

A
10/09/2022
12/09/2022

B
15/09/2022
16/09/2022

C
08/09/2022
12/09/2022

The result I'd like to generate automatically (new row will often be added):

Column A
Start date
End date
Date

A
10/09/2022
12/09/2022
10/09/2022

A
10/09/2022
12/09/2022
11/09/2022

A
10/09/2022
12/09/2022
12/09/2022

B
15/09/2022
16/09/2022
15/09/2022

B
15/09/2022
16/09/2022
16/09/2022

C
08/09/2022
12/09/2022
08/09/2022

C
08/09/2022
12/09/2022
09/09/2022

C
08/09/2022
12/09/2022
10/09/2022

C
08/09/2022
12/09/2022
11/09/2022

C
08/09/2022
12/09/2022
12/09/2022

I hope my need is clear.
Thanks,
I've tried THIS, but the solution is for fixed N times while I need N to be dynamic.

UPDATE

I though it'll be easy to reproduce the solution to my exact need, but it's not the case... I've received two great solutions which work with my first example, but not the full need.
Here is an example of the exact need:

Col1
Col2
Col3
Col4
Col5
Col6
Col7
Col8
Start date
End date
Col11
Col12
Col13
Col14
Col15
Col16
Col17
Col18
Col19

A
B
C
D
E
F
G
H
10/09/2022
24/09/2022
K
L
M
N
O
P
Q
R
S

T
U
V
W
X
Y
Z
A
05/10/2022
17/11/2022
D
E
F
G
H
I
J
K
L

A: Here's one way to do that using REDUCE.
=ARRAYFORMULA(
  {A1:C1,"Date";
   QUERY(
    REDUCE(
      {"","","",""},
       BYROW(
         FILTER(A2:C,A2:A<>"",B2:B<>"",C2:C<>""),
         LAMBDA(row,JOIN("❄",row))),
       LAMBDA(acc,cur,
         {acc;
         LAMBDA(a,start,end,
           LAMBDA(dif,
             {IF(dif,{a,start,end}),SEQUENCE(MAX(dif),1,start)})
             (SEQUENCE(end-start+1)))
          (INDEX(SPLIT(cur,"❄"),,1),
           INDEX(SPLIT(cur,"❄"),,2),
           INDEX(SPLIT(cur,"❄"),,3))})),
    "OFFSET 1",0)})

UPDATE
=ARRAYFORMULA(
  QUERY(
    {TRIM(QUERY(
            SPLIT(REDUCE(,
                    BYROW(A2:S3,LAMBDA(row,JOIN("❄",row)))&"♥"&J2:J3-I2:I3+1,
                    LAMBDA(
                        acc,cur,
                        {acc;
                         IF(SEQUENCE(INDEX(SPLIT(cur,"♥",,),,2)),
                            INDEX(SPLIT(cur,"♥",,),,1))})),"❄",,),
            "OFFSET 1",0)),
    QUERY(
      FLATTEN(MAP(I2:I3,J2:J3,LAMBDA(start,end,SEQUENCE(1,end-start+1,start)))),
      "WHERE Col1 IS NOT NULL")},
    "SELECT Col"&JOIN(", Col",SEQUENCE(COLUMN(J1)))&
    ", Col"&COLUMNS(A2:S3)+1&
    ", Col"&JOIN(", Col",SEQUENCE(COLUMNS(A2:S3)-COLUMN(J1),1,COLUMN(J1)+1))))

A: try:
=QUERY(ARRAYFORMULA(SPLIT(FLATTEN(A2:A&"|"&B2:B&"|"&C2:C&"|"&MAP(B2:B,C2:C,LAMBDA(bx,cx,if(bx="",,TRANSPOSE(SEQUENCE(DATEDIF(bx,cx,"d")+1,1,bx,1)))))),"|")),"Select * Where Col4 IS NOT NULL")
-


text:
Q: Change inner user control in Silverlight/WPF by a property at design time I am creating some custom user controls for WPF. This user controls contain custom dependency properties so I can fill them in the designer.
One of this properties is called "InnerUserControlType". This dependency proeprty is a custom enumeration containing some values like TextBox, ComboBox, Label, CheckBox, etc.
I would like to be able to set this property in my XAML pages in the designer and then see the user control change the displayed inner control depending on the property.
How should I implement this? The grid which will contain the inner control in my user control is a normal field, so it cannot be accessed from a static method property (like the dependency properties).
I want it to have it working in the designer so the designers can work easily.
Thanks a lot!

A: Put a ContentControl in the grid, bind the Content property to the UserControl via relative source
<ContentControl Content="{Binding RelativeSource={RelativeSource FindAnsector,
                                  AncestorType={x:Tyle myNamespace:MyControl}}}"

and make a DataTemplateSelector that will check the value of InnerUserControlType and will return an appropriate data template containing the control that was asked for in the property.
Depending on your scenarios, you might need to make sure the controls in the data template have the right data context. If the data context of the controls should be the same as of the user control, then on the root element in the data template, add relative binding for data context. Something like (for the text box data template):
<TextBox DataContext="{Binding DataContext,
                               RelativeSource={RelativeSource FindAnsector,
                               AncestorType={x:Tyle myNamespace:MyControl}}}"
 ......
</TextBox>

EDIT:
I've noticed only the wpf tag and missed the silverlight one.
In Silverlight you don't have ...TemplateSelector properties, so use a converter instead.


text:
Q: Isomorphism between this subgroup of complex numbers and all finitely generated abelian groups ? Every cyclic (abelian) group of infinite order is isomorphic to $G=(\mathbb{Z},+)$. Is there a corresponding set of groups $S_G=\{G\}$ such that every finitely generated abelian group of infinite order is isomorphic to at least one group in $S_G$?
More precisely,

*

*Let $A$ be the set of all finitely generated abelian groups of infinite order, then is there an $S_G$ so that $\exists$ a mapping $f: A \to S_G$ such that $f(A_1)=G\Leftrightarrow A_1 \approx G$?

*Can $S_G,f$ be chosen such that $f$ is an isomorphism?

Here's an idea I had for a possible $S_G$:
$I_N=\{1,...,N\}$, integer $m$ and $p_i$ being the $i$th prime, I posit that each group, with binary operation of multiplication, of the form $$G_{m,N,M}=\{ re^{i \theta}| r=\prod_{i \in I_N}p_i^{a_i} , \theta \in \{\frac{1}{m}\prod_{i \in I_M}p_i^{b_i} \mod 1\}$$
Given that $m,N,M$ are free to vary, I think $S_G$ is sufficiently big for an $f$ to exist. Is this provable, and can a very similar $G_{m,N,M}$ be contructed with fewer free parameters (i.e. here, $m,N,M$)?

A: There is a classification theorem for finitely generated abelian groups. See http://en.wikipedia.org/wiki/Finitely-generated_abelian_group
The statement is that if $G$ is finitely generated and abelian, then $G \cong \mathbb{Z}^n \oplus \mathbb{Z}_{m_1} \oplus \cdots \oplus \mathbb{Z}_{m_\ell}$ where $n \in \mathbb{N}$ and each $m_i$ is a prime power.

A: Take
$$
S_G=\left\{\mathbb Z^r\times \prod_{i=1}^n \mathbb Z/p_i^{a_i}\mathbb Z:n,r,a_i\in\mathbb Z^+,p_i\text{ prime}\right\}.
$$
This is using the classification theorem for finitely generated abelian groups.


text:
Q: Annotations not working, not even in Dygraphs' own example on jsFiddle, why? I'm currently trying out Dygraphs (which seems really great btw!), but for some strange reason, the annotations feature won't work for me, AND it also fails in the exact same way on the jsFiddle version of Dygraphs' own gallery example of annotations, so this is most likely a bug/problem the devs really might want to take a look at(!).
To reproduce (same thing happens in both latest Firefox and latest Chrome):
1.
Look at the "annotations" example in the Dygraphs gallery, here:
http://dygraphs.com/gallery/#g/annotations
It works just fine and looks great, like this:

2.
Press the "Edit in jsFiddle" button, for that very example on that very page.
You are now sent to jsFiddle, and if you press the "Run" button there, the chart itself (colored curves etc) is shown just fine, but, only the "stems" of the annotation "signs" are shown, while the text contents of the annotations are all displayed as normal text to the left of the chart?! Like this:

Seems like some kind of CSS problem or similar to me, am I correct?
Since the example is Dygraphs' own example, which also works on their own site but not on jsFiddle, all suspicions of incorrectly formatted data or code can also be let go, I guess. It also happens to all my own Dygraphs charts on my own computer that I try to annotate, but this native Dygraphs gallery example is a much better example to investigate from I guess?
So, my question is of course, why does this happen, and how do I fix it to get the annotations working and displaying correctly?

ADDITION:
Let's make it even simpler, in order to isolate the problem without any hesitation.
Here is a very simple example for Dygraph annotations that I have put together on my own local disk (i.e. as a stand-alone HTML file):

<link rel="stylesheet" src="dygraph.css" />

When I open this file (locally with file:// in Chrome on my computer, having the latest dygraph.js and dygraph.css in the same directory), this is what I get:

As you can see, exactly the same problem as described above appears here, i.e. only the "stem" of the test annotation is visible in the graph itself, while the annotation text ("A") is displayed to the left of the graph.
The Firebug console is empty after having loaded this file, and no attempts (unsuccessful or otherwise) of loading any images are anywhere to be found in the Firebug network tab either.
Again, this very much feels like some kind of CSS positioning problem to me, but I may of course very well be wrong?
The answer to provide to this question would then be:
How, in as few and simple changes/steps as possible, would I get this local example PoC code for Dygraphs annotations to work as intended, i.e. showing the annotation text "A" inside a square at the correct position inside the graph (i.e. at the position where the "annotation stem" is currently just displayed, just as is done in the working example on the Dygraphs page, in my first screendump above in this question)?

A: Setting
position: absolute
solved the problem for me.

A: The gallery example loads images from dygraphs.com. When you load the demo on jsfiddle, it tries to load the images from jsfiddle, which doesn't work. dygraphs annotations are working fine, it's just that the image files are missing.

A: It seems that I was right about the CSS positioning problem after all.
The annotations are rendered by Dygraphs by adding the following HTML to the DOM of the page (this is the exact HTML for my test annotation in my local example code in the question test above, extracted live using Firebug):

A

If I (as suggested by this SO question) add the CSS property position: relative to this div (manually, using Firebug), the graph suddenly looks like this:

See, the annotation text is now correctly positioned! It's still missing its opaque background and colored border though, but I guess this is just the result of even more CSS properties missing for some reason?
So, let's focus then on why there is missing CSS for the annotations I guess?
My best guess is that the dygraph.css file isn't properly loaded under certain conditions (apparently both on jsFiddle and locally on my computer, even though it is indeed there in the same directory as the HTML file and dygraph.js)? Or am I wrong?
A Firebug dump of the applied CSS for the annotation div seems to support this. Here is the CSS from Firebug for the annotation div of my local example (and also same in jsFiddle):

And here is the CSS for the same thing in the working instance in the gallery on the Dygraphs site:

See, the classes from dygraph.css is completely missing in my local example and in the jsFiddle example (even though indeed explicitly referenced in the class attribute of the annotation div's html code, as can be seen above), even though the CSS file is indeed there in the same directory as the dygraph.js file?!
@danvk, do you have any idea why this happens, and if Dygraphs could be patched somehow to avoid this from happening, and thus load all the CSS that it is supposed to for the annotations?
The only working hack-solution I can find for the moment is to dump the entire contents of dygraph.css inline in the  of the HTML file, as so:

After that it's finally working fine:

Addition:
It seems like others too (1) (2) have this general problem regarding the loading of CSS files. No accepted answer to neither that SO question nor Mozilla support thread though, and indeed, none of the suggested answers work for me either. WTF, how can such a huge problem be generally unknown/unanswered? Please do also note that the same thing happens for me in both Chrome and Firefox, and also on multiple computers, out of which some have never opened the file before, so no strange cache-related effects should be involved either. Either way, it would seem like the bug is outside of Dygraphs' scope.

A: I'm afraid I'm late to the party, but it looks the problem is still valid (or workaround is not well documented). I was able to have better estimation of position by adding in index.html:

However still annotations are not following the chart well:

The option attachAtBottom : true added to annotations might help here a bit, but still annotations are jumping on hovering graph (I guess this is because of legend taking some place)

A: All day trying to solve the same problem as the author at the beginning of this post. Yes, changing the CSN file allows you to somehow solve the problem, but everything worked by itself without dancing with a tambourine when I added this one line:
link rel = "stylesheet" href = "// cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css" /

As always, you need to be more attentive to the little things)


text:
Q: UITabBarControllerDelegate not calling I have a Custom UITabBarController Class with implemented <UITabBarControllerDelegate>.
in the -tabBarController:shouldSelectViewController: method I do some custom animations. (Slide in / Slide out)
When a TabBarItem is pressed the Delegate is called and everything works fine.
Now to the Problem: I also have an UISwipeGestureRecognizer on the View to swipe between ViewControllers. When i set the selectedIndex from the TabBarController no animation appears (but the View Controller changes) and the Delegate method was not called.
My Code to change from the swipe:
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    UISwipeGestureRecognizer *tmp = (UISwipeGestureRecognizer *) gestureRecognizer;
    int newIx = (int)myTabBarController.selectedIndex;
    if (tmp.direction == UISwipeGestureRecognizerDirectionLeft) {
        newIx ++;
    } else if (tmp.direction == UISwipeGestureRecognizerDirectionRight) {
        newIx --;
    }
    if (newIx >= 0 && newIx < myTabBarController.viewControllers.count) {
        myTabBarController.selectedIndex = newIx; //Set the new Index
    }

    return true;
}

I have tried to call -tabBarController:shouldSelectViewController: manually but then the animation don't work as expected.
The delegate is set in the Storyboard.
EDIT: I have update due to @atrebbi's answer.
I have tried to programmatically call the 'press on the item'.
first try:
UIBarButtonItem *newItem = (UIBarButtonItem*)[myTabBarController.tabBar.items objectAtIndex:newIx];
    SEL press = newItem.action;
    id foo = newItem.target;
    [foo performSelector:press];

second try:
[[UIApplication sharedApplication] sendAction:newItem.action to:newItem.target from:self forEvent:UIEventTypeTouches];

But both tries are crashing the App.
2nd EDIT: I have noticed that the animation only breaks at the first swipe when i call the Delegate method programmatically. If i swipe a second time between Views the animation works correctly.
[self tabBarController:myTabBarController shouldSelectViewController:[myTabBarController.childViewControllers objectAtIndex:newIx]];

A: Try to select programmatically the UITabBar item:
[tabBarItem sendActionsForControlEvents: UIControlEventTouchUpInside];


text:
Q: 'FEC limit BER' in communication systems What is the maximum BER that a FEC can correct?
In one of the IEEE papers the value mentioned was 10^(-3).
My question is when FEC can correct BER upto 10^(-3) then why do many communication systems specify BER requirements to be 10^(-12) to 10^(-9)?

A:
" Why do many communication systems specify BER requirements to be \$10^{-12}\$ to \$10^{-9} ~~~?~\$  "

Why not worse or better?
There is no absolute answer as the error probability can never be zero forever, but can be zero in some finite time.  The answer lies in the cost/benefit ratio of an improvement and depends on the value and redundancy of such data.  We cannot put a universal cost factor on this exponent for all cases but just assume for now, it is based on historical technology limits with a sensitivity to cost.
We know bandwidth has costs as well as channel capacity and redundancy has an added cost. Depending on the isolation of the error in redundant systems, the BER (or inversely the MTBF) may be twice the exponent or it may be no improvement if common to both.
The specified BER establishes the channel reliability needs or the integrity of the data.  These are often define as soft errors that can be recovered with retries or correction or hard errors than cannot be corrected or recovered.  The spread of which can be several orders of magnitude.  It can also be rated by the time interval of tolerable retries for acceptable performance.
Retries in transmission systems, may be trivial and even transparent to the user in operating systems {e.g. Windows [win]+R >  cmd > netstat -es} Whereas avoid the error may be costly to reserve time to avoid contention or add more immunity from EMI from infrequent motor shutoff switch arc disturbances.
There are many statistical relationships between BER and other factors that affect cost, bit rate and bandwidth. Factors which  lower BER include environmental stress, aging, noise types, , quality margin loss, but can be improved by coding methods, modulation type, detection method, forward error detection/correction methods, and retry methods.
Each tends to have logarithmic effects on BER equivalent to some noise in addition to the random Gaussian noise defined by the Shannon-Hartley equation \$ C=B ~log_2(1+S/N)~~~\$ and Shannon's Law for Channel capacity, C and Bandwidth, B for power in watts of Signal and Noise. This leads to the general shape and  slope of the BER curve vs number of bits with including all other factors that influence it.
BER Optimization tradeoffs include;
MAXimize transmission bit rate
MAXimize system utilization
Minimize system complexity
Minimize transmission power
Minimize required system bandwidth, B
Optimize costs
Choose optimal modulation for  efficiency of B vs Tx Pwr
Choose optimal modulation due to disturbances, fading loss etc.

Minimize probability of bit error

It all depends on the cost impact of an error vs the cost of retransmission, or overhead of error correction or the cost of each of the above factors, but specifications can be justified for many exponential powers of 10.

I could (probably) write a book on all my experiences with BER vs "any factor" measured by dB or ns jitter or costs to "margin of error" but I have been lucky to have lots of wide exposure to this topic. From 10 yrs experience in testing HDD Disk Drives during the 80-90's but BER was often defined as soft BER  \$ 10^{-10} \$ and hard BER \$ 10^{-14} \$ and originally did not include error correction so analog mapping of defects in the factory was critical.   But still in a SATA drive hard BER \$ 10^{-14} = \$ 8% per terabyte.  Thus the error correction methods with associated overhead and quality of media had to be improved with capacity.  The down-side is that "transparency" and lack of user awareness from automated error correction means the thresholds all appear to be compressed and the user never  gets any warning from working perfect one day to  failed permanently the next day.
BTW "can correct BER upto 10^(-3)" meant the correction method works from 1 bit per thousand and up.
In WiFi networks when the error rate exceeds a hard coded threshold, the bit rate negotiates to a lower rate. The Rx power level associated with this can vary from -80dBm to -60dBm with rising bit rates but can also be adversely affected by Rician Fading loss from phase cancelling echoes and drop the bit rates abruptly.

A: It depends on the type of FEC and the type of BER, and the desired corrected error rate.  Some FEC techniques do well on randomized errors, but fail more quickly with (say) long sequential strings of errors.  In any case, it's not a hard brick wall situation, as the BER increases, the FEC performance degrades before completely failing.  You want good margins to get reasonable error performance.

A: In my experience, the systems that specify 10-9 or better BER are systems that don't use FEC.
They don't use FEC because historically implementing FEC was difficult at high data rates, and even today it requires using more power for the added logic, as well as paying for the chip (or part of a chip) that actually implements the FEC.
The deciding factor when making new standards is likely whether they think it would take more power to run the FEC logic, or just to boost the signal power to increase the SNR and decrease the raw BER. This trade-off will change over time as new technology allows implementing FEC with less power required.

A: I think you are confusing 2 different things. A communication system specifies the receive sensitivity of the receiver and the BER that the specified sensitivity refers to, so for example a transceiver datasheet will typically say something like receive sensitivity is -100dbm at a BER of  \$10^{-9}\$ , meaning that if the input signal has an SNR of -100 then the output data stream will have an output BER of \$10^{-9}\$, obviously if the input SNR is greater than the receive sensitivity then the BER will be lower and if the SNR lower the BER greater. This does not say anything specific about the capabilities of the error correcting code that has been used, it just states the overall performance of the transceiver. Maybe I am misunderstanding your question.


text:
Q: how to background color to pdf view in iphone app I am creating the pdf using the following tutorial is works for me
but it shows white background of pdf i want to give color to the background how to do this
i have seen all the code but there is no any option in this to give color is there anyway to give color.

A: Inside do while loop use these lines of code....
Here pdfpageFrame is the frame of your Pdfpage.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(currentContext, [UIColor redColor].CGColor );
CGContextFillRect(currentContext, pdfpageFrame);

A: Just before the drawBorder, do this:
  CGContextRef currentContext = UIGraphicsGetCurrentContext();
  CGContextSetFillColorWithColor(currentContext, [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0].CGColor);
  CGContextFillRect(currentContext, pdfpageFrame);


text:
Q: Probability to winning chess Two players A and B are playing the final of chess championship which contains a series of matches. Draw is not considered
The probability that A wins is 2/3.
The probability that B wins is 1/3.
The winner will be A if wins at least 12 games and the winner will be B if wins at least 6 games.
we're given that A has won 8 games, and B has won 4 games. who is now most likely to win the championship?
sorry for my english ^ _ ^

A: What we have here is a negative binomial.
$A$ must do one of the following to win:
Win $4$ consecutive games
Win $3$ of the next $4$ games and then win the $5th$ game.
Otherwise, $B$ would have won $2$ games and the game would be over.
We have $n$ trials given $k$ successes where
$${n-1\choose{k-1}}p^k(1-p)^{n-k}$$
Using our numbers,
$${3\choose{3}}{\frac{2}{3}}^4\frac{1}{3}^{0}+{4\choose{3}}{\frac{2}{3}}^4\frac{1}{3}^{1}\approx 0.4609$$
Thus $B$ has a greater chance of winning.
Just to check:
The probability that $B$ wins would be
$${1\choose{1}}{\frac{1}{3}}^2\frac{2}{3}^{0}+{2\choose{1}}{\frac{1}{3}}^2\frac{2}{3}^{1}+{3\choose{1}}{\frac{1}{3}}^2\frac{2}{3}^{2}+{4\choose{1}}{\frac{1}{3}}^2\frac{2}{3}^{3}\approx 0.5391$$
which is the compliment of the probability that $A$ wins, as expected.

A: The problem can be modeled through a Markov chain:

Red arrows represent transitions with probability $\frac{1}{3}$ and green arrows represent transitions with probability $\frac{2}{3}$. The transition matrix is
$$ P=\left(\begin{smallmatrix}0 & \frac{1}{3} & \frac{2}{3} & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & \frac{2}{3} & 0 & 0 & 0 & 0 & 0 & \frac{1}{3} \\
0 & 0 & 0 & \frac{1}{3} & \frac{2}{3} & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & \frac{2}{3} & 0 & 0 & 0 & \frac{1}{3} \\
0 & 0 & 0 & 0 & 0 & \frac{1}{3} & \frac{2}{3} & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & \frac{2}{3} & 0 & \frac{1}{3}\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & \frac{2}{3} & \frac{1}{3} & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \frac{2}{3} & \frac{1}{3} \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ \end{smallmatrix}\right)$$
and the probability that $B$ wins is
$$\left(1,0,0,0,0,0,0,0,0,0\right)\,P^5 \left(0,0,0,0,0,0,0,0,0,1\right)^T = \color{red}{\frac{131}{243}}.$$


text:
Q: ECMAScript Promise.all method works with jQuery.Deferred. Why? I was making a research for Promises in JavaScript. I'm was interesting can I combine ECMAScript Promises with other implementations, for example jQuery $.Deferred. And I was surprised when Promises.all works fine with jQuery $.Deferred. I'm trying to find the answer in jQuery source code and CommonJS Promises/A specs, but I still misunderstood why this code works as I expected(do console.log after 10 seconds, not 5 seconds):
var promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve();//resolve first promise after 5 secs
        console.log('Promise resolved');
    }, 5000);
});

var deferred = $.Deferred();
setTimeout(function () {
    deferred.resolve();//resolve after 10 seconds
    console.log('Deferred resolved');
}, 10000);

Promise.all([promise,deferred]).then(function () {
    console.log('All is done');//log after 10 seconds
});

Do you have any ideas?
Promise.all must rely on something field or method of $.Deferred to understand is resolved it or not. What is that method/field?

A: The promises A+ specification (on which the promises unwrapping specification was based on which native promises use) was specifically built to do this.
With a design goal of libraries inter-oping well, the specification is built around a single method: .then.
The then method specifies how a continuation of a promise works. jQuery promises expose .then since version 1.8 which means they try to participate in this game. While jQuery deferreds and promises are not Promises/A+ promises - they attempt to be Promises/A promises which means the following:
return Promise.resolve($.get(...))

Will always work. A+ promises (and native promises) will assimilate every .thenable recursively and resolve with its value when you return it.
Promise.resolve({then:function(fn){ return fn(3); }}).then(function(el){
    console.log(el); // this logs 3
})

If we check the specification , we can see:

Let result be Invoke(nextPromise, "then", (resolveElement, promiseCapability.[[Reject]])).

(also related is this)
Which calls .then and resolves the next item when that .thenable resolves
jQuery's deferred uses a nonstandard promise implementation so it cannot consume native promises (That is, you can't predictably $.when a native promise. The other way around works.


text:
Q: Powershell doesn't read files size correctly if these are in progress of change (i.e files being downloaded) I am crafting a Powershell script that aims to turn off a Windows machine (laptop/PC) once a download of one or more files is completed (for the sake of the example, let's assume one large file is the case here).
In few words, we're reading the size of the entire downloads folder each x seconds and we compare the before and after delay sizes. If there is no change in the recent time, that means the download is either completed or stuck, both cases lead to shutdown.
Given the following script (the size getter can be a standalone function at some point, yes):
#Powershell5
#Major  Minor  Build  Revision
# -----  -----  -----  --------
# 5      1      19041  1320

$downloadDir = "C:\Users\edi\Downloads"

while (1)
{
    $s1 = Get-ChildItem -Path $downloadDir | Measure-Object -Property Length -Sum | Select-Object Sum
    write-host "S1:" $s1.sum

    # this 3 seconds time is just for testing purposes; in real case scenario this will most
    # likely be set to 60 or 120 seconds.
    Start-Sleep -s 3

    $s2 = Get-ChildItem -Path $downloadDir | Measure-Object -Property Length -Sum | Select-Object Sum
    write-host "S2:" $s2.sum

    if ($s1.sum -eq $s2.sum)
    {
        write-host "Download complete, shutting down.."
        # loop exit is this, actual shutdown; commented out for testing purposes.
        #shutdown /s
    }
}

The problem I am facing is that the file sizes reading is not done "in real time". In other words,  the file size is not changing as you would normally see in Explorer view. I need to be able to read these numbers (changing file size) in real time.
Interesting fact: while the download is in progress and the script running, if manually going to the downloads folder and hit F5 / Refresh... the numbers change (the size reading is accurate).
Side note: My research got me to this article that might present the root cause, but I am not 100% sure of it: https://devblogs.microsoft.com/oldnewthing/20111226-00/?p=8813
Appreciate any idea on this. Thanks in advance!

A: This answer is meant to demonstrate that, even though unreliable, file size can be monitored in real-time. In this case [System.IO.StreamWriter] is appending data to a file in a separate job while the main thread monitors the current folder size.
I have also performed the same test while downloading a "test file" and it's working fine for me, the total size of the folder is being properly updated.
The possible causes for what you're observing and purely based on assumptions:

*

*The file being download has pre-allocated space - I don't see how that would be possible since, as you explained, by looking on Explorer you can see the file size increasing.

*There is not enough time between the size before vs the size after calculation - This could be due to buffering, mklement0 has explained this in detail. Increasing the sleep time might solve this problem. Also, calling the .Refresh() method, as explained in his helpful answer, might help.

My thoughts, I personally don't think this is the right approach to solve this problem. Process monitoring would be a much better approach (assuming this is a possibility - also explained by mklement0 and I totally agree with him).
function Get-FolderSize {
    param($Path = $PWD)

    ($Path | Get-ChildItem -File | Measure-Object -Property Length -Sum).Sum
}

$startingSize = Get-FolderSize

$job = Start-Job {
    try {
        $chunk   = 'a' * 10kb
        $tmpFile = Join-Path $PWD -ChildPath "testfile.dump"
        $writer  = [System.IO.StreamWriter] $tmpFile
        $writer.AutoFlush = $true

        foreach($i in 0..200kb) {
            $writer.WriteLine($chunk)
        }
    }
    finally {
        $writer.Dispose()
        $tmpFile | Remove-Item
    }
}

try {
    do {
        $sizeBefore = Get-FolderSize
        $waitId     = [Threading.WaitHandle]::WaitAny($job.Finished, 5000)
        $sizeAfter  = Get-FolderSize

        '[StartSize {0, -5} | SizeBefore {1, -10} | SizeAfter {2, -10}]' -f @(
            $startingSize
            $sizeBefore
            $sizeAfter
        )
    }
    while ($waitId -eq [Threading.WaitHandle]::WaitTimeout)
}
finally {
    $job | Stop-Job -PassThru | Remove-Job
}

Results for me:
[StartSize 11270 | SizeBefore 11270      | SizeAfter 400391534 ]
[StartSize 11270 | SizeBefore 400391534  | SizeAfter 847762094 ]
[StartSize 11270 | SizeBefore 847762094  | SizeAfter 1349824934]
[StartSize 11270 | SizeBefore 1349824934 | SizeAfter 1744551614]
[StartSize 11270 | SizeBefore 1744551614 | SizeAfter 11270     ]

A: I suggest adopting a different strategy:

*

*Set an overall timeout for each download process, such as curl.exe's --max-time option.

*Unfortunately, PowerShell's own Invoke-WebRequest and Invoke-RestMethod appear to have only a connection timeout (-TimeoutSec), not a timeout for the overall connection.
That way you can track the download processes, and trigger a reboot once all of them have terminated (whether due to completion or timeout).

As for your approach:

*

*The on-disk file size that you can query via Get-ChildItem is not updated continuously while a file is being written, as you've observed, and while it is eventually updated, that may not happen until the file has been closed, i.e. written in full.

*

*You can experiment with throttled writes based  on Santiago Squarzon's helpful answer.

*However, you can update the file-size information on demand, namely via the System.IO.FileSystemInfo.Refresh() method, which is the equivalent of the manual refreshing you performed via File Explorer.

*

*Note, however, that this still isn't real-time size information due to internal buffering of writes.

# Perform this before every Measure-Object call.
# It refreshes the size information of all files in the specified dir.
(Get-ChildItem -File -LiteralPath $downloadDir).Refresh()

As an aside: As Santiago points out, this approach fundamentally wouldn't work for download utilities / APIs that preallocate the output file with the full size of the download, which is a feature that some BitTorrent clients apparently offer.
As for narrowing down what downloads have completed vs. which ones are assumed to be stuck:
Invoke-WebRequest / Invoke-RestMethod exclusively lock their output files while a download is ongoing, so you can make a read attempt to see which files cannot be read from, from which you can infer what downloads, if any, are still ongoing:
# Note: In PowerShell (Core) 7+, use -AsByteStream instead of -Encoding Byte
Get-ChildItem -File -LiteralPath $downloadDir |
  Get-Content -Encoding Byte -First 1 -ErrorVariable errs -ErrorAction SilentlyContinue |
    Out-Null

if ($errs) { Write-Warning "Incomplete downloads:`n$($errs.TargetObject)" }


text:
Q: Moving SSH keys from Ubuntu I have set up SSH keys on my Ubuntu machine (10.04) and now I am moving to Debian.
On the Debian machine, do I generate new SSH keys corresponding to my username or is it possible to (and is OK) if I copy the ~/.ssh folder from Ubuntu and place it in the new Debian installation?
Long story short, how do I move around my SSH keys.

A: Just copy them. There is no need to generate a new pair.


text:
Q: How do you give non-root permissions when creating a volume with docker compose? I'm using Docker Desktop with WSL2 and I'm having trouble with the fact that some of my container using a non-root user can't create or paste file in a volume.
It seems that when creating a volume with docker-compose, it automatically gives root ownership to it.
Is there a way to change permissions of the volume or to allow non-root user to write in it?
Docker version below:
Client: Docker Engine - Community
 Cloud integration: 1.0.2
 Version:           19.03.13
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        4484c46d9d
 Built:             Wed Sep 16 17:00:27 2020
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.13
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       4484c46d9d
  Built:            Wed Sep 16 17:07:04 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.3.7
  GitCommit:        8fba4e9a7d01810a393d5d25a3621dc101981175
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

A: If you create a bind mount, like this:
version: "3"

services:
  example:
    image: myimage
    volumes:
      - ./host/path:/container/path

Then the directory in the container will have whatever ownership and permissions the directory has on your host filesystem. As @rzlvmp points out in a comment, you can adjust the directory permissions as necessary to match the requirements of your container.
If you mount a named volume:
version: "3"

services:
  example:
    image: myimage
    volumes:
      - myvolume:/container/path

volumes:
  myvolume:

The volume will be inherit the permissions of the target directory in the container. If your image was created from a Dockerfile that includes something like:
RUN useradd myuser; mkdir -p /container/path; chown myuser /container/path

Then the directory in the running container would look like:
root@d268cf1fcd7c:/# ls -ld /container/path
drwxr-xr-x. 2 myuser root 6 May 23 03:42 /container/path

From the above, you can see that using named volumes is going to be the easiest way to manage storage: you get a directory with appropriate permissions without requiring any special initialization scripts or any sort of elevated privileged in the container.
If you're in the rare situation in which a named volume isn't appropriate, one option is to include an ENTRYPOINT script, running as root, that ensures the correct permissions on your directories before executing the main command as an unprivileged user.  That is, create a Dockerfile that includes:
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["sh", "/entrypoint.sh"]

And in entrypoint.sh:
#!/bin/sh

chown -R myuser /container/path

exec runuser -u nonrootuser "$@"

This works, but requires that your container start as root in order to change permissions (and if you're working with an existing image this requires that you take into account any existing entrypoint script).


text:
Q: enable or disable csrf_protection for a bundle Symfony2 propse to enable or disable csrf_protection for framework, for example:
    csrf_protection:
        enabled: false

or
        csrf_protection: false
we should notice the two configuration is totally diffrent, the first one means the csrf is loaded but is false, the senconde one we do not even load this functionality. well, we can easily enable it for a special form, example:
    public function getDefaultOptions(array $options)
{
    return array(
            'data_class' => 'xxx\Entity\Company',
            'csrf_protection' => true,
    );
}

in a form builder class.
But i do not think it is enough, so i ask this question, could we do something like :
mybundle:
    csrf_protection:
        enabled: false

A: You can globally disable csrf_protection in your config.yml file for every bundle in your project, but I don't think it's possible to do it for just one of your bundles.
Instead, you will need to modify the options array on every Form class of that bundle, like this:
class TaskType extends AbstractType
{
    // ...

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class'      => 'Acme\TaskBundle\Entity\Task',
            'csrf_protection' => false
        );
    }

    // ...
}


text:
Q: Android Xml File: full phone screen width (to display caller name) I just built an app similar to TrueCaller but I have an issue with displaying the caller name. I tried match_parent & fill_parent & wrap_content methods in XML, but I'm having issues.
I want to set the width to the phone screen width.
How can I achieve this? Here is my layout.
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/btn_arsenic"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btn_arsenic"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Hello"
            android:textColor="#789546"
            android:textSize="20dp"
            android:textStyle="bold"
            android:typeface="monospace" />

        <TextView
            android:id="@+id/address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Hello"
            android:textColor="#fff"
            android:textSize="20dp"
            android:textStyle="bold"
            android:typeface="monospace" />

        <TextView
            android:id="@+id/active"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Hello"
            android:textColor="#fff"
            android:textSize="22dp"
            android:textStyle="bold"
            android:typeface="monospace" />

        <TextView
            android:id="@+id/activaa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Hello"
            android:textColor="#fff"
            android:textSize="22dp"
            android:textStyle="bold"
            android:typeface="monospace" />
    </LinearLayout>
    <!-- android:onClick="onPurchaseClick" -->

</AbsoluteLayout>

A: AbsoluteLayout is deprecated, better not to use it.
I tried to fix your layout by simply keeping only one parent layout.
Try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello"
        android:textColor="#789546"
        android:textSize="20dp"
        android:textStyle="bold"
        android:typeface="monospace"/>

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello"
        android:textColor="#fff"
        android:textSize="20dp"
        android:textStyle="bold"
        android:typeface="monospace"/>

    <TextView
        android:id="@+id/active"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello"
        android:textColor="#fff"
        android:textSize="22dp"
        android:textStyle="bold"
        android:typeface="monospace"/>

    <TextView
        android:id="@+id/activaa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello"
        android:textColor="#fff"
        android:textSize="22dp"
        android:textStyle="bold"
        android:typeface="monospace"/>

    <!-- android:onClick="onPurchaseClick" -->
</LinearLayout>


text:
Q: Understanding "top" users I am running a website on a LAMP stack, and new to managing servers.
When I run the command top, it lists several users named nobody accessing the command httpd.
Does that correspond to the number of visitors currently on my website?
If so, sometimes I have 20 or 30 "nobody"'s accessing my website, each taking a certain % of my memory. As the traffic increases,  I will increase my memory, but are there other ways around this problem?
(I know it is a broad question, but I need some general advice)
Thanks

A: No, top stands for 'table of processes' and will list the processes (running, sleeping, waiting for i/o or otherwise) on your machine. With a typical LAMP setup you will will have a few processes that wait for, accept a connection, processs a request and return to a kind of idle state. Thus, there is no direct correlation to the number of 'active users'.
To properly analyze the load of your apache server, you should use the logs that your apache writes (usually to /var/log/apache, check your config).
Starting points for understanding what is going on might be the apache documentation, and your system manual for top (man top). Detailed insight on what your apache httpd is currently doing can be gained using mod_status, but make sure you protect the status url with a good password.

A: nobody so far has answered your question about the "nobody" user....here goes:
when top lists the username 'nobody', it has NOTHING at all to do with which user is logged in to your web site.
top doesn't know, doesn't care, and has no access to details about your web site or the user accounts it has.  top displays details about running unix processes, including which unix user id (uid) each process is running as.
i.e. the 'nobody' mentioned by top is the Unix user which is running the apache process.
presumably your system is configured to run apache as user nobody as that  is a minimal priviledge account which can't do much even if someone manages to compromise the apache program.  this is quite normal.  some systems run apache as user "apache", "httpd", "www-data", or some other username but running it as "nobody" is fine...it's just another unix user on the system.
unless you're using suexec or similar, all apache processes will be running as 'nobody', regardless of who happens to be logged in on your web site.  since you're asking questions about who the nobody user is, i think it's safe to guess that you're not running suexec.

to summarise: it's NOT a problem and doesn't need to be worked around.

A: The web server handles incoming connections by forking off child httpd processes. Those "extra" processes will sit and wait for incoming connections so there's not a delay...in other words, there's spare processes waiting to handle incoming connection requests.
If you look through the config file for apache you'll see a setting that controls how many spare child processes are supposed to be waiting in the wings.
As these processes start handling new connections, if they're all busy even more httpd processes spawn off.
They're not all eating memory, though; it's misleading because some memory is being shared among other processes.
Watch your logfiles in /var/log (probably /var/log/http, /var/log/httpd, or /var/log/apache or /var/log/apache2). That lists all incoming requests.
You can monitor in realtime using tail -f /var/log//access.log ; use control-c to break out of it.


text:
Q: Making custom test result Is it possible to add a custom test result at same level as: passed, failed, xfail, skipped, deselected? I would like to be able to assign the custom test result during fixture setup similar to calling pytest.skip().
Alternatively, is it possible to "deselect" a test case from a fixture (i.e. during fixture setup - not collection phase)?
My problem
I'm using pytest not for testing python code, but for making black box testing of different devices connected to a host PC running the pytest code. During one pytest session, I'm only testing one device, but possibly multiple interfaces (IP, RS-232, GPIO, etc.).
When launching pytest, I supply as argument a configuration file. That file specifies the IP address of the device and also which interfaces the host PC has connected to the device.
I'm using fixtures to skip tests that can not be run because either:

*

*The particular device does not implement the functionality of the test case

*The host does not support the functionality (physical interface) of the test case

I need to be able to distinguish between those two reasons for skipping a test case: when making a software release, I need to make sure that there are no tests that were skipped because of the host configuration.
Hence, I would like to set test result "not applicable" in the former case and "skipped" in the latter.
I could of cause specify the device capabilities on the command line and have the pytest collection phase deselect the test cases, but I really need/require/want this done at runetime. Otherwise the number of arguments for running the tests will quickly explode.
My current test results look like this:

*

*Device A: 235 skipped out of 468

*Device B: 445 skipped out of 468

You can see that I use the same test suite for both devices because they share much of the same functionality (I just haven't written many of the test cases validating the shared functionality).
How would it look?
I would like to be able to mark a test "not applicable" like this:
@pytest.fixture
def device(myconfig):
    cfg = myconfig.get_ip()
    return Device(cfg.ip, cfg.port)

@pytest.fixture
def serial(device, myconfig):
    if not device.has_serial:
        mark_not_applicable("Device does not support: serial")

    try:
        cfg = myconfig.get_serial()
        return serial.Serial(cfg.device, baudrate=cfg.baudrate)
    except:
        pytest.skip("Host interface not defined for: serial")

@pytest.fixture
def has_alpha(device):
    if not device.has_alpha:
        mark_not_applicable("Device does not support: alpha")

@pytest.fixture
def has_beta(device):
    if not device.has_beta:
        mark_not_applicable("Device does not support: beta")

def test_serial_protocol_alpha(serial, has_alpha):
    check_serial_protocol_alpha()

def test_serial_protocol_beta(serial, has_beta):
    check_serial_protocol_beta()


text:
Q: Алгоритм разделения строки по два элемента Например, есть строка a1b2c3d4f5, а должно получиться ['a1', 'b2', 'c3', 'd4', 'f5']
Строка всегда будет четной длины
Мне интересно какие есть эффективные способы получить такой результат.

A: Используя регулярные выражения (RegEx):
import re

In [12]: re.findall(r'.{2}', text)
Out[12]: ['a1', 'b2', 'c3', 'd4', 'f5']

для двух символов можно использовать более короткий ваниант - '..' как посоветовал @Qwertiy
In [13]: re.findall(r'..', text)
Out[13]: ['a1', 'b2', 'c3', 'd4', 'f5']

Еще один вариант:
n = 2
[text[start : start+n] for start in range(0, len(text), n)]

Пример:
In [33]: [text[start : start+n] for start in range(0, len(text), n)]
Out[33]: ['a1', 'b2', 'c3', 'd4', 'f5']

A: Прикладываю свой пример через zip и использование среза с шагом:
text = 'a1b2c3d4f5'
print([a + b for a, b in zip(text[::2], text[1::2])])
# ['a1', 'b2', 'c3', 'd4', 'f5']


text:
Q: My rewritten url redirecting but to a website without css or any other rule being applied This is my original url
http://havemybooks.com/blog_single?blog_no=39&blog=Ten%20quotes%20by%20national%20leader%20to%20make%20this%20independence%20day%20more%20speacial.

This is my rewritten url
http://havemybooks.com/blog_no/39/blog/Ten%20quotes%20by%20national%20leader%20to%20make%20this%20independence%20day%20more%20speacial.

Here is the code I'm using in .htaccess. I don't know a much about .htaccess so I'm using htaccess generator tool.
RewriteEngine On
RewriteRule ^blog_no/([^/]*)/blog/([^/]*)$ /blog_single?blog_no=$1&blog=$2 [L]

This is the error I get when I inspect elements of my website.
Resource interpreted as Stylesheet but transferred with MIME type text/html

A: As Mike commented above, you just need to load the static content from site root. Current, all your URLs are being rendered relative to the page you are visiting.
Add a base tag in the <head> of you pages, and the content will load as required.
<base href="www.example.com/">


text:
Q: EditText in ListView with windowSoftInputMode adjustPan I have a ListView with an EditText in each row. I have set windowSoftInputMode to adjustPan in the manifest for this activity, so when I tap on an EditText the layout pans so that it is visible above the keyboard.
This works the first time I tap on an EditText. But if I hit the back button to dismiss the keyboard, then tap the same EditText again (without tapping anything else, so the cursor remains in the first EditText), the keyboard comes back up but the layout does not pan this time. The result of this is that the EditText is obscured behind the keyboard.
Has anyone experienced this behaviour / knows how to solve it?
Thanks

A: Still not sure why this happens, but I have a solution.
I have subclassed EditText and overridden the method onKeyPreIme(int keyCode, KeyEvent event) as follows:
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        clearFocus();
    }
    return super.onKeyPreIme(keyCode, event);
}

Now when the back key is pressed, the EditText gives up focus. Then tapping it again has the desired behaviour.


text:
Q: Name of an 80's cartoon character? Does anyone remember the name of this kid from an old 80's cartoon (and the name of the cartoon)?

A: That looks like Dylan Taylor from Adventures in Odyssey.  Notice the similar facial features in this image:

Here you can see him in a red and while shirt, similar to your image:
[


text:
Q: .trim() is not a function I have a very simple string that can contains a list which can possibly contain whitespace:
string = "one, two,three ";

I want to first split the string by , to create an array of three strings and then remove any whitespace using .trim()
array = string.split(',').trim();

which returns "one","two","three"
however sometimes it fails and returns an error .trim() is not a function
I read that .trim() returns a new string not a trimmed version of the current string. So i used a for loop to do the above:
array = string.split(',');
for (var i = 0; i < array.length; i++) {
    var item = array[i].trim();
    array.push(item);
}

which returns "one","two","three"
my question is, can anyone explain why i was getting the error only sometimes? if the array never changed from my example and can anyone provide a cleaner solution to my fix.

A: split() does not work on arrays, but on strings.
As you wrote your String into an array you have to get that string via array[0], since the string is the very first Element.
If you splitted your string into an array you can call the map function and trim each value in your newly created array.
like this:
array = ["one, two,three "];
array = array[0].split(',')
array = array.map(function(a){return a.trim()})

Or in short:
array = ["one, two,three "][0].split(',').map(function(a){return a.trim()})

A: In ES6 compliant runtime (i.e: node 4+) you can use use arrow function that gives you a less verbose code to achieve your goal:
> "one, two, three ".split(',').map(s => s.trim());
[ 'one', 'two', 'three' ]

A: It is apparent that there could be other problems with your codes but sticking specifically to your question .trim() is not a function, there is a change in how the function is called especially for jQuery 3.5 upwards. This is already explained elsewhere but brought here for quick reference:
For codes using jQuery 3.5 and below, the usual function call works:
let xString = " This is my string with spaces  ";
let xTrimmed = xString.trim();

But for codes using jQuery 3.5 upwards:
let xString = " This is my string with spaces  ";
let xTrimmed = $.trim(xString);

A: I saw this same issue trying to iterate the output of String.split using a "for (var i in splitTokens)". Note it only happened to me in the browser (Chrome in my case) i.e. not when using the same code in a node process.
It confused me until I hooked up a debugger and then I saw the problem. String.split returns an Array object instance (splitTokens), which has functions on it ("each" etc). The "for (var i in splitTokens)" loop iterates the functions too, so splitTokens[i] was getting back e.g. the each function of the Array instance, which caused things to explode if I tried to call e.g. "trim()" (because the function object doesn't have a function called trim()).


text:
Q: Flutter InkWell splash strength - how to make it more visible globally for the entire app? In my flutter app, when I click a button (or anything decorated with InkWell) the splash/ripple effect is very gentle, almost invisible. (It is there, it's not covered, just very gentle, too subtle).
When I use other apps (e.g. Google's Gmail app) every time I tap something, the splash/ripple effect is VERY strong and gives good visual to the user what he/she just tapped.
Question:
How to make splash/ripple effect stronger in flutter app?

A: the InkWell widget gives you control over the splashColor and the highlightColor of it, you need simply to assign them like this:
InkWell(
 splashColor: Colors.red,
 highlightColor: Colors.green,
 onTap: () {},
 child: `yourChild()`,
 ),

this now will give it a splash ( ink effect ) red color, and when it's highlighted, it will shows green.

A: Pro Tip: build a wrapper for InkWell and use in the entire app
class MyInkWell extends StatelessWidget {
  const MyInkWell({Key? key, this.child, this.onTap}) : super(key: key);

  final VoidCallback? onTap;
  final Widget? child;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      // customized you want
      // splashColor: ,
      // focusColor: ,
      // hoverColor: ,
      // highlightColor: ,
      // overlayColor: ,
      // radius: ,
      onTap: onTap,
      child: child,
    );
  }
}

and use your own customized InkWell
class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
            child: MyInkWell(
                onTap: () {
                  // on tap callback
                },
                child: const Icon(Icons.abc))),
      ),
    );
  }
}

Regards


text:
Q: Postgres: how to use LIKE on every word of user input, AND-ing the results In postgresql (9.6), given a variable length user input of the type 'alice chaplin' or 'alice' or 'alice chaplin meyer' but also 'lic chapl', I would like to search for records that contain 'alice' in column firstname OR column lastname (AND contain 'chaplin' in firstname OR lastname (AND contain 'meyer' in firstname OR lastname)), etc.
I had decided to use ILIKE %searchterm% for the matching, so the query would presumably be along the lines of:
... where
     ((lastname ILIKE '%' || SEARCHTERM1 || '%') OR (firstname ILIKE '%' || SEARCHTERM1 || '%'))
 AND ((lastname ILIKE '%' || SEARCHTERM2 || '%') OR (firstname ILIKE '%' || SEARCHTERM2 || '%'))
 AND etc.

After lots of attempts and searching, nothing comes up that resolves this... As a last resort I'll write a very procedural pgplsql function that loops over a split search string, intersecting the ILIKE results, but there has to be some more idiomatic SQL way of resolving such a run of the mill problem.

A: You can use string_to_array to convert an input string into an array of words. You can then use unnest to convert the array into a (virtual) table, and operate on the words to add '%' before and after. And finally, you can use the ALL comparison using ILIKE ALL (SELECT ...). This ALL will actually be AND-ing the results, as desired.
WITH q AS
(
  SELECT 'Alice Chaplin Meyer'::text AS q
)
, words AS
(
SELECT
  '%' || word || '%' AS wordish
FROM
  q
  JOIN LATERAL unnest(string_to_array(q, ' ')) AS a(word) ON true
)
SELECT
    *
FROM
    t
WHERE
    concat_ws(' ', first_name, last_name) ILIKE ALL(SELECT wordish FROM words)

You can check it all at http://rextester.com/LNB38296
References:

*

*string_to_array and unnest

*Using ALL
NOTE: This can probably be simplified, but I've prefered a step-by-step approach.


text:
Q: How to list subdirectories from an URL on a HTTP file share? I would like to know if there is an easy name to list all files/directories from a HTTP file share - by default the HTTP server displays them but I'm wondering is there is an easy way to get the list of files without manually parsing the returned webpage.
Any solution that would use curl, wget or python should be just fine.

A: No, there's no generic way to do this.

A: wget is only designed to download files not list directories.
If that's all you've got, though...
wget -r http://SOME.SITE/PATH 2>&1 | grep 'Saving to:' | sed "s/Saving to: \`\([^?']*\).*'/\1/" | uniq -u
rm -rf SOME.SITE

(Just so you don't sue me later, this is downloading all of the files from the site and then deleting them when it's done)
Edit: Sorry, I'm tired. If you want only the top-level directories, you can do something like this:
wget -rq http://SOME.SITE/PATH
ls -1p SOME.SITE | grep '/$'
rm -rf SOME.SITE

This does the same as above, but only lists immediate subdirectories of the URL.


text:
Q: Error when checking target: expected dense_3 to have shape (256,) but got array with shape (1,) I am working on training a VGG16-like model in Keras, trying to predict a continue / time-to-event value (regression) having as input images, and encountered the following error:

Error when checking target: expected dense_3 to have shape (256,) but
  got array with shape (1,)

This is the structure of the model:
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 256, 256, 64)      1792
_________________________________________________________________
batch_normalization_1 (Batch (None, 256, 256, 64)      256
_________________________________________________________________
.
.
.

_________________________________________________________________
conv2d_16 (Conv2D)           (None, 16, 16, 512)       2359808
_________________________________________________________________
batch_normalization_16 (Batc (None, 16, 16, 512)       2048
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 8, 8, 512)         0
_________________________________________________________________
flatten_1 (Flatten)          (None, 32768)             0
_________________________________________________________________
dense_1 (Dense)              (None, 1000)              32769000
_________________________________________________________________
dense_2 (Dense)              (None, 1000)              1001000
_________________________________________________________________
dense_3 (Dense)              (None, 256)               256256

Total params: 54,072,656
Trainable params: 54,061,648
Non-trainable params: 11,008

I have tried adding another layer at the end with only one neuron and it seems to work that way, but i do not think that is the right way to do it.
I have read about similar issue but i have not managed to find a solution.
The last layers of the model built by the code below
#Convolution Layer
#input: 64x64x128, image with 128 channels, appy 256 convolution filters
model.add(Conv2D(512, kernel_size=3, activation='relu',padding='same' ))
#the output of the layer above is 64x64x256

#Normalization layer
model.add(BatchNormalization())

#Convolution Layer
#input: 64x64x128, image with 128 channels, appy 256 convolution filters
model.add(Conv2D(512, kernel_size=3, activation='relu',padding='same' ))
#the output of the layer above is 64x64x256

#Normalization layer
model.add(BatchNormalization())

#Max-Pooling
#poolsize:(2,2), factors by which to downscale (vertical, horizontal)
model.add(MaxPooling2D(pool_size=(2,2), dim_ordering="tf"))

#Flatten layer
model.add(Flatten())

#Fully connected layer
#number of neurons is chosen randomly
model.add(Dense(1000, activation='relu'))

#Fully connected layer
model.add(Dense(1000, activation='relu'))

#Fully connected layer
model.add(Dense(256, activation='softmax'))

model.summary()

#Compile model
model.compile(loss='categorical_crossentropy', optimizer='adagrad')

I am also not sure which loss function should i use in case of predicting time-to-event values.

A: model.add(Dense(256, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adagrad')

Change your last but one layer to relu activation and finally add one linear activation layer. Use MSE loss as it is a regression problem.


text:
Q: How to display checkbox, that binds dynamically using ajax and php I need to display checkbox that binds dynamically using ajax and php  .
my code is
<?php

include 'dbconnect.php';
$result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' ");

while($city_row=mysqli_fetch_array($result)){
    ?>

    <input type="checkbox" value="<?php echo $city_row['id']; ?>"/><?php echo $city_row['city_name']; ?>
<?php
}
}

?>

ajax script
$.ajax({

type: "POST",
cache: false,
url: "get_locality.php",
    data:{districts:hi },
success: function(response){
    alert(response);
    $('#city').html(response);

}
});

html div

but it only displays the values . not displaying the checkboxes

A: The issue is you print only the value of checkbox and not the checkbox html. So  store all code inside one variable and print that variable.
<?php
include 'dbconnect.php';
$result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' ");
$str = '';
while($city_row=mysqli_fetch_array($result)){
$str .= '<input type="checkbox" value="'.$city_row['id'].'"/>'.$city_row['city_name'];
}
echo $str;
?>


text:
Q: Unable to add multiple rows using WHILE statement in servlets I am making an online e-portal site for my project using jsps and servlet using jdbc.However I am getting a strange error.I am unable to add multiples rows using the while statement.I am getting the Product ID(PID) of all the items available in a cart from a hashmap  via session.and I store corresponding keys i.e (keys are pids here and values are quantities).I am getting pids and getting the corresponding attributes of that product using that pid.and I am updating the particular user table with items in his/her cart in a while loop.using an insertuserdata.First I am checking if a table exists for a particular user..then I am just adding the records else I am creating a new table and inserting records one by one
Here is the servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession ses=request.getSession();
            HashMap h=(HashMap)ses.getAttribute("list");
            String usr=(String) ses.getAttribute("usr");
            String usertable="USER"+usr;
            Collection c=h.keySet();
            Iterator itr=c.iterator();
            connect.dbconnect con=new connect.dbconnect();
            int tCost=Integer.parseInt((String)ses.getAttribute("tCost"));
            while(itr.hasNext())
            {
                Object pid=itr.next();
                String v;
                v=con.Pid_buy((String)pid);
                String pname=v;
                String quan=(String)h.get(pid);
                Date dt=new java.util.Date();
                String date=(dt.toString());
                String status="Purchased";

               try{
                    if(con.chktable(usertable))
                {
                   int num=con.getSID(usertable);
                   con.insertuserdata(usertable,num+1,quan,date,pname,status,tCost);
                }
                if(!con.chktable(usertable))
                {
                    con.createnewuser(usertable);
                    con.insertuserdata(usertable,1,quan,date,pname,status,tCost);
                }
               }catch(Exception e)
               {
                   e.printStackTrace();
               }
               con.updateStock((String)pid,Integer.parseInt(quan));
            }
               h.clear();
               String count=null;
               ses.setAttribute("count", count);
               ses.setAttribute("list", h);
              // response.sendRedirect("home.jsp");

        } finally {

            out.close();
        }
    }

here list is the hashmap containing the list of items and their quantity.tCost is just a total cost I am getting as parametre.
getSID function gives me the number of rows in the table.
PID_BUY gives me the name of the product
Here the problem is that its only adding the last product in the database and not all the products.and I am getting a GENERAL error
following is my Insertuserdata method
public void insertuserdata(String tbname,int pk,String quantity,String date,String pname,String status,float tCost) throws SQLException, ClassNotFoundException
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con=DriverManager.getConnection("jdbc:odbc:product");
              // Table exists
            String data=tbname ;

            PreparedStatement smt1=con.prepareStatement("insert into ["+data+"] values (?,?,?,?,?,?)");

            smt1.setInt(1,pk);
            smt1.setString(2,quantity);
            smt1.setString(3,date);
            smt1.setString(4,pname);
            smt1.setString(5,status);
            smt1.setFloat(6,tCost);
            smt1.executeUpdate();

        }


text:
Q: How do I fix This error: DistributionNotFound: The 'ptyprocess>=0.5' distribution was not found and is required by pexpect Hi I have difficulties in fitting data using Fitter module in Python and I don't understand the error as I am quite new to Python. The following code below is what I done so far in order to get the summary.
import fitter
f=fitter.Fitter(data=data["ROAS"], distributions= ['gamma'])
f.fit()
f.summary()

The error I get is:
DistributionNotFound                      Traceback (most recent call last)
<ipython-input-29-c00604ced33b> in <module>
      1 f=fitter.Fitter(data=data["ROAS"])
----> 2 f.fit()
      3 f.summary()

~\anaconda3\lib\site-packages\fitter\fitter.py in fit(self, amp, progress)
    259         warnings.filterwarnings("ignore", category=RuntimeWarning)
    260
--> 261         from easydev import Progress
    262         N = len(self.distributions)
    263         pb = Progress(N)

~\anaconda3\lib\site-packages\easydev\__init__.py in <module>
     28     version = __version__
     29 else:
---> 30     version = pkg_resources.require("easydev")[0].version
     31     __version__ = version
     32

~\anaconda3\lib\site-packages\pkg_resources\__init__.py in require(self, *requirements)
    882         included, even if they were already activated in this working set.
    883         """
--> 884         needed = self.resolve(parse_requirements(requirements))
    885
    886         for dist in needed:

~\anaconda3\lib\site-packages\pkg_resources\__init__.py in resolve(self, requirements, env, installer, replace_conflicting, extras)
    768                     if dist is None:
    769                         requirers = required_by.get(req, None)
--> 770                         raise DistributionNotFound(req, requirers)
    771                 to_activate.append(dist)
    772             if dist not in req:

DistributionNotFound: The 'ptyprocess>=0.5' distribution was not found and is required by pexpect

Please can someone help me to run the code without the error, thanks.

A: I had the same problem. I installed the "ptyprocess" library and now it works.


text:
Q: Reduce/reduce conflict in a C-style cast operator I am writing a bison+flex parser for a certain query language and I need to add a C-style cast operator to it. Here is the relevant part of the code:
%token <characterToken>  Identifier
%token <commandToken>    LRPAR RRPAR

%type <characterToken>   typename
%type <operationValue>   generalExp castExp variable

%%
generalExp: variable
      | LRPAR generalExp RRPAR
       { /* some code here */ }
      | castExp
      ;

castExp: LRPAR typename RRPAR generalExp
   { /* some code here */ }
   ;

variable: Identifier
    { /* some code here*/ };
typename: Identifier;
%%

The problem here is that (typename) in castExp clashes with (variable) in generalExp and gives a reduce/reduce conflict:
test.yy: conflicts: 1 reduce/reduce
test.yy:23.11-20: warning: rule useless in parser due to conflicts: typename: Identifier

Possible solution could be to list all valid typenames (like long, int, char) in the corresponding  lex file, however I need to support used-defined types as well.
UPD:
another solution is to use bison GLR-parser, which I don't want due to performance drop.
bison -v output is here.

A: Yes, the C cast syntax was very badly chosen. It is impossible to resolve correctly without knowing whether what is inside the cast is a type or a value. Here are some cases in C:
(f)*a    // cast the value pointed to by a to type f, or multiply f by a?
(f)(a+b) // cast a+b to type f or call the function f with argument a+b?

The easiest way I've found to handle this is to let the lexer consult the symbol table, so that it can return different token types for Typenames and Identifiers. (Which is pretty well the way the C grammar works.) Sharing the symbol table between the lexer and the parser is a bit ugly, particularly if you allow scoped type definitions, but it can be done. For the purposes of correct lexing, the only thing that the lexer should need to know is whether the symbol is the name of a type or not; you can probably get away with assuming that a symbol is not a type unless it has been explicitly declared a type, so that it is not strictly necessary to insist that all symbols be declared before use. (In C++, for example, a non-type class member does not have to be declared before use, and that can still work.)
Having said all that, I'd strongly encourage you to think seriously about using a different syntax for casts, if at all possible. Aside from being a pain for parsers, they can also be annoyingly ambiguous for human readers (see the examples above), and casting is not (or should not be) so common that it requires an abbreviated syntax.
C++-style casts -- cast<TYPE>(value) -- suffer from the ambiguity introduced by recycling a comparison operator as a bracket, but are tolerable if the operations using angle brackets are a fixed set of keywords. (Otherwise, you create another context where the lexer needs to distinguish between name kinds.)
Personally, particularly for a query language, I'd go with something like
value as type

as in
(3 + 4) as double

which is (IMO) more readable and much easier to parse without being harder to type.

A: Best guess -- some other part of your grammar that you don't show allows for two consecutive generalExp with no token between them.  So when you have an input like ( Identifier ) expression, it might be either a cast or two consecutive generalExps.
The way to proceed is the same as with all conflicts -- run bison with the -v option to get a .output file showing all the states and exactly which states have what conflicts on which symbols.  Once you know that, you have a chance of figuring out what can be done.

A: I had similar problem - colision of following rules:
expr: expr "+" expr
expr: "(" type ")" expr

I solved it by setting precedence of operators:
%precedence "+"
%precedence ")"

This set higher precedence to ")", so the second rule will be prefered.


text:
Q: Crop an image using another Rect in Unity I have a Texture2D, applied on a RawImage, taken from a webcam, which I call "originalImage". I want to crop just a block of this originalImage in base of the position of another rect, called "cropArea". Basically cropArea is a "guide" over my originalImage where I want the user to put his hand, so that I can get another image for just the hand.
The problem is that I can't get the correct pixels of the originalImage relative to the cropArea position. The actually cropped area has an offset relative to cropArea's position I can't understand. Here's a picture showing my problem (I used a random image taken from google as originalImage Texuter2D instead of my webcam)
Crop Issue Screenshot
I have cropArea as child of originalImage in my Hyerarchy, and here's how they were both set up on my inspector when I took the screenshot above.
Images in Inspector
Here's my code (It's a code I've written to reproduce my problem, so there's no other codes involved in the function):
[SerializeField] private RawImage originalImage;
[SerializeField] private RawImage cropArea;
[SerializeField] private RawImage croppedImage;

void Update() {
    if (Input.GetKeyDown(KeyCode.S))
    {
        Texture2D croppedTexture = new Texture2D((int)cropArea.rectTransform.rect.width, (int)cropArea.rectTransform.rect.height);
        Texture2D originalTexture = (Texture2D)originalImage.mainTexture;

        croppedTexture.SetPixels(originalTexture.GetPixels((int)cropArea.rectTransform.anchoredPosition.x, (int)cropArea.rectTransform.anchoredPosition.y, (int)cropArea.rectTransform.rect.width, (int)cropArea.rectTransform.rect.height));
        croppedTexture.Apply();
        croppedImage.texture = croppedTexture;
    }
}

Again, I've tried many combinations in my code, triyng to use localPosition or rect instead of anchoredPosition to get cropArea's position, getting different results, but never the correct one.
I think I maybe missing some relations between the position of cropArea and the pixels to get from originalImage, but I really can't get what is it.
Everytime I have to deal with Unity UI in runtime it gets me headache, it's so confused and anti-intuitive.

A: Ok, so as I've written under @obywan answer, my problem was that my originalImage was being stretchet to fill the canvas, but the source to crop wasn't the RawImage, but RawImage's texture, which doesn't get stretched instead.
I thank obywan for making me realize that my code was actually working fine and for bringing me to think that there might have been a dimension problem.
I've found a working solution writing a function to resize the texture, so that I have a correspondence between texture pixels position and what my eyes actually see in the UI.
Once resized the texture, I was able to use cropArea position to get pixels from the resized texture, with the wanted result.
So, this is the resizing texture function:
Texture2D ResizeTexture2D(Texture2D originalTexture, int resizedWidth, int resizedHeight)
{
    RenderTexture renderTexture = new RenderTexture(resizedWidth, resizedHeight, 32);
    RenderTexture.active = renderTexture;
    Graphics.Blit(originalTexture, renderTexture);
    Texture2D resizedTexture = new Texture2D(resizedWidth, resizedHeight);
    resizedTexture.ReadPixels(new Rect(0, 0, resizedWidth, resizedHeight), 0, 0);
    resizedTexture.Apply();
    return resizedTexture;
}

This is instead my Update method with ResizeTexture2D function implemented to work fine:
void Update()
{
    if (Input.GetKeyDown(KeyCode.S))
    {
        Texture2D croppedTexture = new Texture2D((int)cropArea.rectTransform.rect.width, (int)cropArea.rectTransform.rect.height);
        Texture2D originalTexture = (Texture2D)originalImage.mainTexture;
        Texture2D originalTextureResized = ResizeTexture2D(originalTexture, (int)originalImage.rectTransform.rect.width, (int)originalImage.rectTransform.rect.height);
        croppedTexture.SetPixels(originalTextureResized.GetPixels((int)cropArea.rectTransform.anchoredPosition.x, (int)cropArea.rectTransform.anchoredPosition.y, (int)cropArea.rectTransform.rect.width, (int)cropArea.rectTransform.rect.height));
        croppedTexture.Apply();
        croppedImage.texture = croppedTexture;
    }
}

A: Your script works fine. You just need to adjust hierarchy and pivots.
I placed crop area under main image and set pivot of crop area to 0,0 as well as min-max anchors to 0,0,0,0.
See images. (you can ask questions in comments if there is any)

A: 4th line in ResizeTexture2D should be:
Texture2D resizedTexture = new Texture2D(resizedWidth, resizedHeight);

A: If you're okay boxing the texture as a Sprite. Then Sprite.Create can handle the cropping for you by using its rect argument:
void Update()
{
    if (Input.GetKeyDown(KeyCode.S))
    {
        Texture2D originalTexture = (Texture2D)originalImage.mainTexture;
        var textureCropArea = Rect.MinMaxRect(cropArea.rectTransform.anchoredPosition.x, cropArea.rectTransform.anchoredPosition.y, cropArea.rectTransform.rect.width, cropArea.rectTransform.rect.height);
        croppedImage.texture = Sprite.Create(originalTexture, textureCropArea, Vector2.one / 2, 100).texture;
    }
}


text:
Q: BigQuery not so fast today - tables with just 1 row taking a minute to query We've been experiencing timeouts, and long running queries with BigQuery. The table is 1 row (8 bytes) and the query is taking on average 50 seconds.
This is causes issues with our applications, which are timing out after 10 seconds. They don't expect a query over 1 row to take that long.
Is there something wrong with BigQuery today?
Some example job ids:

*

*job_TlXh5ISWUc6QXpf3HQ3KC-iRdRw

*job_4OLNwAFN_j6mqMsnw2q8UUAJ528

*job_3bZjpkVOfb55PZbldCwot53HqWA

*job_V_EJzsuM9hjikBM-zQ_hCoEJNu8

*job_66awPpXPPfd7WrDuRzYf7o3bKPs

A: there was a temporary issue yesterday afternoon where some queries experienced added latency. I looked at several of your queries and they all appeared to have run during that time.
The issue was related to a blocking call that we were making to a monitoring service that was timing out. We've since fixed the issue. We're in the process of conducting an internal post-mortem to figure out how to prevent issues like this in the future.


text:
Q: expect script not working with bash script I want a script that ssh to remote server and then run a script which is at my local machine and then store the output on my local machine
Expect script for ssh to remote server:
#!/usr/bin/expect -f

set Timeout 2
        set IPaddress 10.118.137.78
        set Username "username"
        set Password "password"

        spawn ssh $Username@$IPaddress
        expect "ssword:"
        send "$Password\r"

script to be run on remote machine and gather the data:
#!/bin/sh

for serveraddress in `cat list.out`
do
"seeisso $serveraddress | grep -E -i ' os |proddropdown'"
done >> getos

===
Not sure how to :
1. combine both and get the result.
2 in expect script it does not takes the \r and returns to newline.

A: Quick sample
#!/usr/bin/expect -f
set timeout -1
set Username "user"
set password "pass"
set ipaddress "host"
set script "script-name"

spawn $env(SHELL)
send -- "ssh $Username@$ipaddress $script\r"
expect "assword: "
send -- "$password\r"
send -- "exit\r"
expect eof

That will work to execute the script on the remote side.  I didn't toy with it too much but when it's done you have to Ctrl+C to exit expect.  At this point I'd be setting up ssh keys for a small environment and for a larger use puppet or something to manage it then for even larger go for single sign-on probably kerberos.


text:
Q: ACE editor auto-completion duplicating prefix I'm trying to add auto-completions for mermaid diagrams to my editor:
    const mermaids = Object.entries({
        "mermaid graph": `graph LR\n    x --> y`,
    }).map(([name, autocompletion]) => ({
        caption: name,
        meta: name,
        value: "``mermaid\n" + autocompletion + "\n```"
    }));

    aceeditor.setOptions({
        enableBasicAutocompletion: [{
            getCompletions: (editor, session, pos, prefix, callback) => {
                callback(null, [
                    ...mermaids
                ])
            }
        }],
        enableSnippets: false,
        enableLiveAutocompletion: true
    });

In the resulting editor, if the user types "graph" or "mermaid" and hits enter to auto-complete, it works as expected. (With the exception of less-than desirable cursor position after the completion.) If the user types "```" and hits enter, the autocompletion occurs after the originally typed "```". E.g.,
``````mermaid
graph LR
    x --> y
\```                  <-- just escaped here for SO's sake

Is there an efficient way to correct this? If not, what event can I use to determine when an auto-completion has actually occurred and search for duplicate markers?
Is there a better way to do this in general?

A: I think the broader issue here is that your completion item more closely resembles a snippet. Using snippets would also give you better control over where the cursor goes after insertion.
Answering your second question, Autocomplete.insertMatch is the function responsible for inserting the chosen completion item. You could hook it, or perhaps use the mysteriously undocumented .completer field on the completion items? It's been there for 9 years now, perhaps it is not an accident.
const FakeCompleter = {
    insertMatch: (editor, data) => {
        // stolen from default insertMatch, needed to erase text that triggered our completion:
        if (editor.completer.completions.filterText) {
            var ranges = editor.selection.getAllRanges()
            for (var i = 0, range; range = ranges[i]; i++) {
                range.start.column -= editor.completer.completions.filterText.length
                editor.session.remove(range)
            }
        }

        // if there are ` symbols immediately before cursor, omit those from completion:
        let text = (data.value || data)
        const lead = editor.selection.lead
        const prefix = editor.session.getLine(lead.row).substring(0, lead.column)
        const mt = /.*?(`{1,3})$/.exec(prefix)
        if (mt && text.startsWith(mt[1])) text = text.substring(mt[1].length)

        // and finally call the regular insertion:
        editor.execCommand("insertstring", text)
    }
}
const mermaids = Object.entries({
    "mermaid graph": `graph LR\n    x --> y`,
}).map(([name, autocompletion]) => ({
    caption: name,
    meta: name,
    value: "``mermaid\n" + autocompletion + "\n```",
    completer: FakeCompleter
}));


text:
Q: Solr - search suggestions Some of my product names are:
Bella cycling gloves for women white and graphite size L
Daisy cycling gloves for children white and blue size XS
Bars cycling gloves for men red size XL

Using Solr to search them is not a problem, but i would also like to make suggestions for searching.
So when someone is writing in search input:
cycling gloves

I would like Solr to give suggestions like:
cycling gloves for children
cycling gloves for men
cycling gloves for women
bella cycling gloves
daisy cycling gloves
bars cycling gloves

I tried various examples, but none worked.
If u can please provide me example with schema and solrconfig.