Q: Is there an equation for the strong nuclear force? The equation describing the force due to gravity is $$F = G \frac{m_1 m_2}{r^2}.$$ Similarly the force due to the electrostatic force is $$F = k \frac{q_1 q_2}{r^2}.$$

*

*Is there a similar equation that describes the force due to the strong nuclear force?

*What are the equivalent of masses/charges if there is?

*Is it still inverse square or something more complicated?

A: The strong force as seen in nuclear matter

The nuclear force, is now understood as a residual effect of the even more powerful strong force, or strong interaction, which is the attractive force that binds particles called quarks together, to form the nucleons themselves. This more powerful force is mediated by particles called gluons. Gluons hold quarks together with a force like that of electric charge, but of far greater power.

Marek is talking of the strong force that binds the quarks within the protons and neutrons. There are charges, called colored charges on the quarks, but protons and neutrons are color neutral.  Nuclei are bound by the interplay between the  residual strong force , the part that is not shielded by the color neutrality of the nucleons, and the electromagnetic force due to the charge of the protons. That also cannot be simply described. Various potentials are used to calculate nuclear interactions.
Simplicity and similarity of form for all forces comes not in the formalism of forces, but as Marek said the formalism of quantum field theory.

A: I think that the earlier answers haven't adequately explained why there isn't a force law for the strong force. It's not because it's relativistic or quantum (electromagnetism is both of those). It's because it's nonlinear.
In the gravitational and electromagnetic formulas in the question, $q_1$ and $q_2$ (or $m_1$ and $m_2$) are the charges at exactly two points, and $r$ is the distance between those two points. The formulas can't be used if there are more than two charges. You can extend them to the general case by turning them into sums over pairs of points, but that only makes sense if the force is linear.
You can write down a two-particle force law for the strong force. It's $F=-V'(r)$ where $V(r)$ is the function in Johannes's answer. What you can't do is use that same force law when there are more particles – not because the law is wrong as such, but because you can't use linearity to generalize it.

Though there is no simple force law, you can build an intuition for the magnitude and direction of the strong force from these rules:

*

*Strong force field lines prefer to cluster in regions with a diameter of about 1 fm. They attract each other when farther apart and repel each other when closer (this is the nonlinearity).

*If the total strong charge in an enclosed region of space isn't "zero" (color singlet), then there have to be strong-force field lines crossing the boundary of the region. (This is the strong-force version of Gauss's law.)

*The energy density of the field is roughly constant where there are field lines and zero elsewhere.

*The force is minus the gradient of the potential.
If there are two charges in an otherwise empty universe, then applying "Gauss's law" to any region containing one particle and not the other tells you that there have to be field lines crossing the space between the particles. The lines can follow any path, but the lowest-energy configuration is that in which they're all in a straight "flux tube" with a diameter of about 1 fm. In that configuration, the only way to reduce the field energy is to bring the charges closer together, so there is a force in that direction, i.e., of each particle directly toward the other. The energy density of the tube per unit distance is constant, so the strength of the force is independent of the length of the tube. (It's about 10,000 newtons; that's the $k$ in Johannes's answer.)
If there are three or more charges, no proper subset of which is color neutral, then again there have to be field lines connecting all of the particles. The shortest, hence lowest energy, way to connect them is a Steiner tree. The force on each charge is toward the nearest vertex of the Steiner tree, and the magnitude of it is again a constant 10,000 N if the separations are large enough.
This is only an approximation, but it's not too bad. In figure 4 of this paper, which shows pentaquarks simulated in lattice QCD, you can clearly see the Steiner-tree structure.
Note that it's very common to see diagrams with incorrect flux tube geometries. For example, all of the configurations in this illustration are wrong except the single tube in the $u\overline c$ meson.

This approximation ignores pair production of quarks. The practical effect of pair production is that the flux tubes connecting charges can't get very long, because it's energetically cheaper to create quarks which allow them to "break".
Quark-like particles with high rest masses, charged under a strong-like force, could be connected by much longer flux tubes. Such particles are known as "quirks" and there are a few papers about them, such as this one which proposes searching for them at the LHC.

I said that the energy density of the field is zero where there are no field lines, but that isn't quite true: in principle it's nonzero out to infinity, but it dies off exponentially.
"Gauss's law" says that there aren't (or at least needn't be) flux tubes connecting different hadrons, but there is a residual strong force between hadrons, which dies off exponentially with distance. It's weak enough that it can (as far as I know) be treated as linear, and there is a "pairwise" force law for it like the gravitational and electrostatic laws. That's $F=-\nabla V$ where $V$ is the function in dmckee's answer.

A: Strong force holds up and down quarks together into a proton or neutron.
It's really the nuclear force (or residual strong force) that keeps nucleons together in an atomic nucleus. The mass defect and therefore the nuclear binding energy is determined by the number of protons and neutrons in the nucleus.
There are 5 terms that add up and contribute in the calculation of nuclear binding energy. It is called the Semi Empirical Formula of Nuclear Binding Energy.
See http://en.wikipedia.org/wiki/Nuclear_binding_energy#Semiempirical_formula_for_nuclear_binding_energy
For details check out - http://en.wikipedia.org/wiki/Semi-empirical_mass_formula

A: From the study of the spectrum of quarkonium (bound system of quark and antiquark) and the comparison with positronium one finds as potential for the strong force
$$V(r) = - \dfrac{4}{3} \dfrac{\alpha_s(r) \hbar c}{r} + kr$$
where the constant $k$ determines the field energy per unit length and is called string tension.
For short distances this resembles the Coulomb law, while for large distances the $k\,r$ factor dominates (confinement). It is important to note that the coupling $\alpha_s$ also depends on the distance between the quarks.
This formula is valid and in agreement with theoretical predictions only for the quarkonium system and its typical energies and distances. For example charmonium: $r \approx 0.4 \  {\rm fm}$. So it is not as universal as eg. the gravity law in Newtonian gravity.

A: At the level of quantum hadron dynamics (i.e. the level of nuclear physics, not the level of particle physics where the real strong force lives) one can talk about a Yukawa potential of the form
$$ V(r) = - \frac{g^2}{4 \pi c^2} \frac{e^{-mr}}{r} $$
where $m$ is roughly the pion mass and $g$ is an effective coupling constant. To get the force related to this you would take the derivative in $r$.
This is a semi-classical approximation, but it is good enough that Walecka uses it breifly in his book.

A: No, there is none such equation. Reason is that these equations are highly classical and invalid in both relativistic (there is an action at a distance, incompatible with finite speed of light) and quantum mechanical regime (distances strong force is important at are quite microscopic). Also, strong force is confining, meaning you can't ever observe individual color charged particles (color is a property associated with strong force), so there can't really be a macroscopic equation for them.
You obviously need at least quantum mechanics to account for strong force, because distances are so tiny (on the scale of nucleus or smaller). But it turns out you need relativity too. The complete theory which incorporates both QM and relativity is called quantum field theory and individual forces are described by QFT Lagrangians which essentially tell you which particles interact with which other particles (e.g. photons with electrically charged particles, gluons with color charged particles, etc.). This is the fundamental theory and the electric force equation you described can be derived from it in classical (both non-QM and nonrelativistic) limit. As for gravitation law, that too can be derived but from different theory, namely general relativity.

A: Let me add one obvious thing: There is an exact equation for the strong force.  It is what Gross, Politzer and Wilczek got the Nobel prize for.
It is called quantum chromodynamics (QCD).  Google it or look it up in Wikipedia, and you can see the Lagrangian for QCD, and  compare it to the Lagrangian for electrodynamics.
Of course, you could argue about the similarities and differences of a Lagrangian, and a force equation, such as your two examples.


Q: For Loop through text file only outputs last line I think I am about to have an a brain aneurysm. I am trying to print the lines of a text file to a new file, but it only outputs the last line. I have done this a dozen times, now I am not sure what I am doing wrong.
for /F "tokens=*" %%A in (results.txt) do (
   echo %%A
) > imsofrustrated.txt
PAUSE

Am I literally retarded? This is in reference to a previous question I posted.
FINDSTR - Stop on last string match

A: > is to redirect output and overwrite whatever is in the file.
>> is to redirect output and append to the file.
for /F "tokens=*" %%A in (results.txt) do (
   echo %%A
) >> imsofrustrated.txt


Q: coldfusion requesttimeout I have a ColdFusion template that executes a long running query.  I have increased the request timeout from 3600 to 6600 but my template continues to timeout.  I would like to increase the request timeout again from 6600 to 9600 but before doing so I would like to know if there are any disadvantages or risks from increasing the request timeout so much?
Basically, what my cfm file does is. It has to take records from a table and insert them into an excel sheet. The table consists of around 30,000 records. The cfm file takes every 1000 records at a time and inserts them into Excel, then it takes the next 1000 and so on.  To complete this entire process it sometimes stops abruptly because of the timeout problem. So before I increase the "requesttimeout" I want to know, would there be any problem (ram usage, performance) if I increase requesttimeout tremendously.

A: Upping the timeout is fine where it's needed. You should use cfsetting requestTimeOut="xxx" to up the timeout just where it's needed, not upping it in the administrator, as that will affect all templates.
The disadvantages are that there's a pool of threads to handle requests and whilst one is handling your long-running request, it's not available to do other things. This is fine as long as you're confident that the long-running request will only be run by one or two people at a time, but problematic if lots of people could be running it. If CF will run 8 requests concurrently and all 8 are hadnling your long-running request, then your site is effectively offline. CF will queue requests up to a certain point, but you don't want to get to this state in the first place.
I've worked on apps where there are background admin-only tasks which can take up to an hour, but we were confident that no more that 2 people would ever run them.
You could also look at using cfthread in order to run your query without blocking the page, but then it's harder to provide feedback to the user.

A: I think it would help if we understood the situation a little better.  Is this something like a nightly job that is run?  Or is this a page that a user might navigate to which generates a report while they wait for it?  Give us some basic information about what your page is doing.
Also, there are different ways to increase the request timeout; system wide via the administrator or page specific via the <cfsetting requestTimeOut=""> tag.  Which one are you increasing?  I would suggest that you not increase the system wide setting but it is okay to increase the page level setting when needed.
There is also a timeout attribute for the <cfquery> tag.  Are you using that?
Can you tell us if the <cfquery> is timing out or if the timeout is happening after the cfquery and during the data output?
I would also suggest attempting to optimize your query as much as possible.  Can an index be setup (if one is not already)?  Do you really only need a subset of the records being returned?
Perhaps you could split this one page up into multiple pages that would each run faster.

A: Rather than just increase your timeout limit, IF the user who initiates the request doesn't need to wait for the results (i.e an end of day or overnight report) then I would use a cfthread with its timeout set to 0 (never times-out) and leave it running in the background until it has finished, or set an extremly long timeout, like 1 hour. I would also use cflock to prevent the thread being able to proccess more than once otherwise you could grind your system to a halt with many heavy threads.
read this -docs- and see what you think


Q: Many laravel apps in one server. How to organize? I'll be setting up a server that will host several laravel applications. There will be a few ones at the beginning, but with time we can end up having dozens of them. Most of which (if not all) will be laravel projects.
I'm not sure how to organize all this. I have several choices:

*

*Use a different laravel project for each application. Every application would be placed in a different directory. That would mean lots of files and space taken up by apps.

*Use a single laravel project, having a src folder inside the project where I would be placing each application in a separate subfolder. Each of these subfolders would contain only the service provider(s) of each app, as well as their own routes, controllers, rules, etc.

*I've been told lately of an approach similar to the second one, but instead of placing the apps in src directory, each app would be developed as a library, and the main laravel project would require each one of them. That way, apps would be in vendor dir, and could easily be required or unrequired.

*I can also group applications across a few laravel projects, using either approach 2 or 3.
What are the advantages and inconvenients of each one of these approaches? Is there an optimal approach to this problem?
Thanks!

A: If they are different and not connected in anyway, the best thing in my opinion is to have their own seperate projects because it would be easier to deal with the webserver (like nginx) and the other options would just make everything more complicated.


Q: Subsetting a data set and plotting means I have a data set including Year, Site, and Species Count. I am trying to write a code that reflects in some years, the counts were done twice. For those years I have to find the mean count at each site for each species (there are two different species), and plot those means. This is the code I have generated:
DataSet1 <- subset(channel_islands,
                   channel_islands$SpeciesName=="Hypsypops ubicundus, adult" |
                   channel_islands$SpeciesName=="Paralabrax clathratus,adult")
years<-unique(DataSet1$Year)

Hypsypops_mean <- NULL
Paralabrax_mean <- NULL
Mean <- NULL
years <- unique(DataSet1$Year)

for(i in 1:length(years)){

  data_year <- DataSet1[which(DataSet1$Year == years[i]), ]
  Hypsypops<-data_year[which(data_year$SpeciesName=="Hypsypops rubicundus,adult"), ]
  Paralabrax<-data_year[which(data_year$SpeciesName=="Paralabrax clathratus,adult"), ]

  UNIQUESITE<-unique(unique(data_year$Site))

  for(m in 1:(length(UNIQUESITE))){
    zz<-Hypsypops[Hypsypops$Site==m,]

    if(length(zz$Site)>=2){
      Meanp <- mean(Hypsypops$Count[Hypsypops$Site==UNIQUESITE[m]])
      Hypsypops_mean <- rbind(Hypsypops_mean,
                             c(UNIQUESITE[m], years[i], round(Meanp,2),
                               'Hypsypops rubicundus,adult'))
    }

    kk <- Paralabrax[Paralabrax$Site==m, ]

    if(length(kk$Site)>=2){
       Meane <- mean(Paralabrax$Count[Paralabrax$Site==UNIQUESITE[m]])
       Paralabrax_mean <- rbind(Paralabrax_mean,
                                c(UNIQUESITE[m], years[i], round(Meane, 2),
                                  'Paralabrax clathratus,adult'))
    }
  }

  if(i==1){
    Mean<-rbind(Hypsypops_mean, Paralabrax_mean)
  }

  if(i>1){
    Mean<-rbind(DataMean, Hypsypops_mean, Paralabrax_mean)
  }

  Hypsypops_mean<-NULL
  Paralabrax_mean<-NULL
}

Mean <- as.data.frame(Mean,stringsAsFactors=F)
names(Mean) <- c('Site','Year','mean_count','SpeciesName')

Mean$Site <- as.integer(Mean$Site)
Mean$Year <- as.integer(Mean$Year)
Mean$mean_count <- as.numeric(Mean$mean_count)

par(mfrow=c(5,5), oma=c(4,2,4,2), mar=c(5.5,4,3,0))
for(i in 1:length(years)){

  if(any(Mean$Year==years[i])) {
    year1<-Mean[which(Mean$Year==years[i]),]

    Species<-unique(as.character(year1$SpeciesName))
    Colors<-c("pink","purple")[Species]

    Data_Hr<-year1[year1$SpeciesName=="Hypsypops rubicundus,adult",]
    Data_Pc<-year1[year1$SpeciesName=="Paralabrax clathratus,adult",]

    plot(Data_Hr$mean_count~Data_Pc$mean_count,
       xlab=c("Hypsypops rubicundus"),
       ylab=c("Paralabrax clathratus"),main=years[i],pch=16)
  }
}

It's a lot I'm sorry, I'm not sure of a way to streamline the process. But I keep getting an error:

Error in names(Mean) <- c("Site", "Year", "mean_count", "SpeciesName")
  :    'names' attribute [4] must be the same length as the vector [0]

Not sure how I can debug this.

A: Not sure why you want to do this with an elaborate loop code. It sounds like you are trying to summarise your data.
This can be done in different ways. Here is a solution using dplyr:
DataSet1 %>%
  group_by(Year, SpeciesName, Site) %>%
  summarise(nrecords = n(),
            Count = mean(Count))

To get a better answer, it might be helpful to post a subset of the data and the intended result you are after.


Q: Vectors - What is Magnitude, What is actually an vector? first of all, I'm not that good at math, and I'm struggling with understanding the concept of "A vector", I've done some research, but I'm not sure if I did understand right the concept. So, a vector, in my own definition is a entity, something, which has a size and a direction. Like, throwing a ball from up to down... when it comes down, the vector is composed from the direction, which points to bottom, and the magnitude is the size we do have in this context, like the speed. Another example, on the previous one, we can aswell thinking to the action of throwing a ball from up to down as a vector which has the magnitude related to weight, and the direction. So, did I understand it or I'm missunderstanding it?

A: Let me give you a formal answer, a bit informally. I'll first point to the (abstract) definition, then relate them to some familiar concept:

*

*mathematically speaking, a vector is a member of a vector space (definition). Essentially, if you have a collection of things, a "sum" operation defined on those things, as well as "scaling by a number" operation on those things, then you can "give that set a vector space structure" and call the elements of that set "vectors". My linear algebra teacher always said that also potatoes can be vectors, if you manage to sum potatoes and multiply them by scalars in a suitable way that respect all the requirements you found in the link above

*an example of vectors, according to this definition, are arrows in the plane that start at the origin of the plane, where the sum is defined by the parallelogram law (in such a way that the resulting vector starts at the origin too) and the multiplication of scalars definined as you would imagine. To be more concrete, i.e. to formally define an arrow, you can think of it as a point in $\mathbb{R}^2$, in the sense that the point $(x,y)$ corresponds to the arrow starting at $(0,0)$ and ending at $(x,y)$. Sum and multiplication by scalar are $(x,y)+(z,w):=(x+z,y+w)$, and $a\cdot (x,y):=(ax,ay)$

*so, now you know what a vector is. However, let me say something more, by making vectors more dynamic entities. There is another structure called affine space, that will hopefully clear things even better (or worse). An affine space is a set of points $S$, together with a vector space $V$ and an operation that makes vectors (elements of $V$) "act" on points (elements of S) in a standardized way (definition)

*as an example, $S$ could be a sheet of paper, say, $S = \mathbb{R}^2$, which you should imagine without origin and axis, and one could take $V$ to be the set of arrows from before, so, $V=\mathbb{R}^2$ as well. The action of vectors on points could be the following: $p+\overrightarrow{v}=q$, where $p=(x,y)$, a point, $\overrightarrow{v}=(v_x, v_y)$ a vector (arrow), and $q=(x+v_x, y+v_y)$. Here, although vectors and points are in the same set, you should imagine them as different entities: points belong to $S$, and get acted upon by vectors, belonging on $V$. Physically speaking, this is just the formalization of moving $p$ by $\overrightarrow{v}$ to $q$.

So, to complete, vectors may be often thought as things that can move things. However vectors can be very abstract things, in mathematics. If we are still on the plane before, vectors also have a magnitude (the distance of the tip of the arrow from the origin). The direction would be the line on which the vector lies.
I left a lot of things unsaid, let me know if I should expand some points.


Q: Why this function is not working without adding double quotes around the arguments?  function symbols(shape) {
   alert ("This is a " + shape)
}

symbols (circle)
symbols (star)

A: You might be knowing data types in JS.
If you pass circle or star as argument without quotes then the argument will be interpreted as object (which is not your intension).
As per you function definition it is expecting string, means you should pass string literal e.g. symbols('star') or you should have a variable containing string value e.g. var circle = 'circle';
symbols(circle);


Q: App crash while setting Box APi key I register by app on box.com and get API key and start using it in my xcode project,but app get crash while setting BoxAPI at line:
[Box setBoxAPIKey:@"insert_key_here"];.

The error:

-[NSURL initFileURLWithPath:]: nil string parameter

No idea how to solve this issue.

A: This is pretty simple. Follow these steps
1) Go to your target build setting
2) Click on Add Build Phase (at buttom right corner) and choose Add Run Script
3) In the Edit Text Box copy paste this script
#!/bin/bash

echo "Copy Box database schema into bundle"
cp -fr ./Box.framework/Resources/BoxCoreDataStore.momd "${BUILT_PRODUCTS_DIR}/${CONTENTS_FOLDER_PATH}/BoxCoreDataStore.momd"

After Doing this click on build and you are done.
Happy coding

A: If someone faces the same problem than here is the fix:
You need to add files in Box.framework/Resources/BoxCoreDataStore.momd folder to your application package.
Add "Copy Files" phase and specify Destination = Executables, Subpath = ./BoxCoreDataStore.momd then add all files from above mentioned folder.


Q: ros: how to track changes in agents movement I'm a noob in this matter so this question might be a bit dumb but I'm trying to launch a multi agent world file where each agent need to know wHo is closest to it.
What I have by now: multi agent system where each agent has a laser sensor and they all move randomly and change direction when they are close to an obstacle which can be another agent or a wall defined in the world file
I'm trying to find a way not just to realize when I hit an obstacle but also to know if it is a moving one and if so where is it moving and how fast.
Thanks guys for any suggestion


Q: How to make an auto-complete textbox in a winforms desktop application I have a list of words. The list contains about 100-200 text strings (it's names of metro stations actually).
I want to make an auto-complete textbox. For an example, user press 'N' letter, then an (ending of) appropriate option appear (only one option). The ending must be selected.
How to do that?
PS1: I guess, there is a textbox control with a Property something like this:
List<string> AppropriateOptions{/* ... */}

PS2: sorry for my english. If you didn't understand -> ask me and I will try to explain!

A: Use a ComboBox instead of a TextBox. The following example will autocomplete, matching any piece of the text, not just the starting letters.
This should be a complete form, just add your own data source, and data source column names. :-)
using System;
using System.Data;
using System.Windows.Forms;

public partial class frmTestAutocomplete : Form
{

    private DataTable maoCompleteList;
    private const string MC_DISPLAY_COL = "name";
    private const string MC_ID_COL = "id";

    public frmTestAutocomplete()
    {
        InitializeComponent();
    }

    private void frmTestAutocomplete_Load(object sender, EventArgs e)
    {

        maoCompleteList = GetDataTableFromDatabase();
        maoCompleteList.CaseSensitive = false; //turn off case sensitivity for searching

        testCombo.DisplayMember = MC_DISPLAY_COL;
        testCombo.ValueMember = MC_ID_COL;
        testCombo.DataSource = maoCompleteList;
        testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
        testCombo.KeyUp += testCombo_KeyUp;
    }

    private void testCombo_KeyUp(object sender, KeyEventArgs e)
    {
        //use keyUp event, as text changed traps too many other evengts.

        ComboBox oBox = (ComboBox)sender;
        string sBoxText = oBox.Text;

        DataRow[] oFilteredRows = maoCompleteList.Select(MC_DISPLAY_COL + " Like '%" + sBoxText + "%'");

        DataTable oFilteredDT = oFilteredRows.Length > 0
                                ? oFilteredRows.CopyToDataTable()
                                : maoCompleteList;

        //NOW THAT WE HAVE OUR FILTERED LIST, WE NEED TO RE-BIND IT WIHOUT CHANGING THE TEXT IN THE ComboBox.

        //1).UNREGISTER THE SELECTED EVENT BEFORE RE-BINDING, b/c IT TRIGGERS ON BIND.
        oBox.SelectedIndexChanged -= testCombo_SelectedIndexChanged; //don't select on typing.
        oBox.DataSource = oFilteredDT; //2).rebind to filtered list.
        oBox.SelectedIndexChanged += testCombo_SelectedIndexChanged;

        //3).show the user the new filtered list.
        oBox.DroppedDown = true; //this will overwrite the text in the ComboBox, so 4&5 put it back.

        //4).binding data source erases text, so now we need to put the user's text back,
        oBox.Text = sBoxText;
        oBox.SelectionStart = sBoxText.Length; //5). need to put the user's cursor back where it was.

    }

    private void testCombo_SelectedIndexChanged(object sender, EventArgs e)
    {

        ComboBox oBox = (ComboBox)sender;

        if (oBox.SelectedValue != null)
        {
            MessageBox.Show(string.Format(@"Item #{0} was selected.", oBox.SelectedValue));
        }
    }

}

//=====================================================================================================
//      code from frmTestAutocomplete.Designer.cs
//=====================================================================================================
partial class frmTestAutocomplete

{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private readonly System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.testCombo = new System.Windows.Forms.ComboBox();
        this.SuspendLayout();
        //
        // testCombo
        //
        this.testCombo.FormattingEnabled = true;
        this.testCombo.Location = new System.Drawing.Point(27, 51);
        this.testCombo.Name = "testCombo";
        this.testCombo.Size = new System.Drawing.Size(224, 21);
        this.testCombo.TabIndex = 0;
        //
        // frmTestAutocomplete
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.Add(this.testCombo);
        this.Name = "frmTestAutocomplete";
        this.Text = "frmTestAutocomplete";
        this.Load += new System.EventHandler(this.frmTestAutocomplete_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ComboBox testCombo;
}

A: Just in case @leniel's link goes down, here's some code that does the trick:
AutoCompleteStringCollection allowedTypes = new AutoCompleteStringCollection();
allowedTypes.AddRange(yourArrayOfSuggestions);
txtType.AutoCompleteCustomSource = allowedTypes;
txtType.AutoCompleteMode = AutoCompleteMode.Suggest;
txtType.AutoCompleteSource = AutoCompleteSource.CustomSource;

A: The answer link by Leniel was in vb.net, thanks Joel for your entry. Supplying my code to make it more explicit:
private void InitializeTextBox()
{

    AutoCompleteStringCollection allowedStatorTypes = new AutoCompleteStringCollection();
    var allstatortypes = StatorTypeDAL.LoadList<List<StatorType>>().OrderBy(x => x.Name).Select(x => x.Name).Distinct().ToList();

    if (allstatortypes != null && allstatortypes.Count > 0)
    {
        foreach (string item in allstatortypes)
        {
            allowedStatorTypes.Add(item);
        }
    }

    txtStatorTypes.AutoCompleteMode = AutoCompleteMode.Suggest;
    txtStatorTypes.AutoCompleteSource = AutoCompleteSource.CustomSource;
    txtStatorTypes.AutoCompleteCustomSource = allowedStatorTypes;
}

A: Use combo box, sets its datasource or give hard coded entries but set the following properties:
    AutoCompleteMode = Suggest;
    AutoCompleteSource = ListItems;

A: You want to set the TextBox.AutoCompleteSource to CustomSource and then add all of your strings to its AutoCompleteCustomSource property, which is a StringCollection. Then you should be good to go.

A: I want to add that the standard autocomplete for TextBox does only work from the beginning of your strings, so if you hit N only strings starting with N will be found. If you want to have something better, you have to use some different control or implement the behavior for yourself (i.e. react on TextChanged Event with some timer to delay execution, than filter your tokenlist searching with IndexOf(inputString) and then set your AutoCompleteSource to the filtered list.


Q: Developer Studio BPEL project doesn't recognize analytics extension Using wso2bps-3.5.1, wso2das-3.0.1 and Developer Studio 3.8.0
I'm following a guideline for Monitoring a BPEL Process with WSO2 DAS. I recieve this from inside Developer Studio and my .bpel file:
Error: Extension "http://wso2.org/bps/monitoring/publisher" is not supported by this implementation.
<bpel:extensions>
    <bpel:extension namespace="http://wso2.org/bps/monitoring/publisher" mustUnderstand="yes"/>
</bpel:extensions>

A: WSO2 Developer Studio uses Eclipse bpel plugin to add support for bpel creation for WSO2 BPS. This BAM publishing bpel extension activity that you are referring to, is a custom extension developed by WSO2 and default bpel editor is not aware of this extension. This is why it gives syntax errors when you add this extension activity from the source view.
However, you should be able to export and deploy the CAR file without any issues regardless of the syntax errors.
According to this, there's a possibility to add support for custom extension activities in bpel editor.
Hence, I have raised a jira in WSO2 BPS Tooling jira for this feature.
Thanks.


Q: Can I build easily a static binary to be used inside fakeroot and how? fakeroot seems to build some  libfakeroot.a (but inside  a .lib directory).
But I am not sure, that the static linker can indeed replace/rename symbols  as the dynamic linker can.

A: Fakeroot uses the dynamic linker in order to do its magic (specifically, LD_PRELOAD). Unfortunately, the dynamic linker is not involved in loading statically linked binaries (which is how the dynamic linker itself is invoked: /lib/ld-linux.so.2 is statically compiled).
As answered above, your only option, as far as I'm aware, is to use fakeroot-ng, which uses a completely different mechanism to inject into the process, and is, thus, able to work on statically linked libraries without a problem.
In fact, statically linked libraries was part of the reason I set out to write fakeroot-ng in the first place. At the time, there was no way to tell ldconfig to run on a subtree, and ldconfig is statically linked.
Shachar

A: seems the solution is to use  fakeroot-ng, which works for statically linked binaries.


Q: How can I restrict jQuery UI connected lists drag and drop to single direction I am using jQuery UI Connectedlist
Here drag and drop is working fine with both side from left to right and right to left.
How can I disable right to left ? It has to work only one way, from left to right.
I need also sorting to still work inside ul yellow items like in grey items.

$(function() {
    $( "#sortable1, #sortable2" ).sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
  });
#sortable1, #sortable2 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
  }
  #sortable1 li, #sortable2 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
  }

  <meta charset="utf-8">
  <title>jQuery UI Sortable - Connect lists</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: You could cancel the drag event in the right list sortable2 using receive event in sortable1 to prevent receiving any item from second list.
To drag grey lis back to the left side we will add helper class e.g s2 that will identify the sortable2 original items and cancel the drag only on them :
$("#sortable1").sortable({
     receive: function(ev, ui) {
          if(ui.item.hasClass("s2"))
               ui.sender.sortable("cancel");
     }
});

Hope this helps.

$(function() {
    $( "#sortable1, #sortable2" ).sortable({
         connectWith: ".connectedSortable"
    }).disableSelection();

    $("#sortable1").sortable({
        receive: function(ev, ui) {
           if(ui.item.hasClass("s2"))
               ui.sender.sortable("cancel");
        }
    });
});
#sortable1, #sortable2 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
  }
  #sortable1 li, #sortable2 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
  }

  <meta charset="utf-8">
  <title>jQuery UI Sortable - Connect lists</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: Currently your connectWith selector matches both the sortable, i.e it's a two way connection. If you only want one way connection from left to right, just connect the left sortable to right sortable using a more specific selector (#sortable2) than a common one:
$(function() {
  $("#sortable1").sortable({
      connectWith: "#sortable2"
  }).disableSelection();

  $("#sortable2").sortable({}).disableSelection();
});

The demo below has the shorter code that does the same thing:

$(function() {
  $(".connectedSortable").sortable({
    connectWith: "#sortable2"
   //----------^---------- #sortable2 connectWith #sortable2 has no effect
  }).disableSelection();
});
#sortable1,
#sortable2 {
  border: 1px solid #eee;
  width: 142px;
  min-height: 20px;
  list-style-type: none;
  margin: 0;
  padding: 5px 0 0 0;
  float: left;
  margin-right: 10px;
}
#sortable1 li,
#sortable2 li {
  margin: 0 5px 5px 5px;
  padding: 5px;
  font-size: 1.2em;
  width: 120px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: The options you are looking for are cancel and update (s2 inspired by the post above), it will disable the drag on matched elements.
$(function() {
    $( "#sortable1, #sortable2" ).sortable({
        connectWith: ".connectedSortable",
        cancel: ".ui-state-highlight, .s2",
        update: function( event, ui ) {ui.item.addClass("s2");}
    }).disableSelection();
});


Q: Auto reboot of a Luks Container I have tried autobooting a luks container on Ubuntu Server (20.04) with a keyfile and a keyscript.  My '/etc/crypttab' entry for both options are as follows.
Keyfile:
dm_crypt-0 /dev/sda3 /root/keyfile luks

Keyscript:
dm_crypt-0 /dev/sda3 none luks,keyscript=/root/lukopen.sh

With the keyfile crypttab line it is ignored on reboot and I have to get in manually with the passkey.  With the keyscript crypttab line I get a fatal error (nothing coming back from the script) and the OS hangs.
The keyfile and script are in the root directory.  The keyscript returns the contents of the keyfile.  The last character in the data returned from the script is not a newline character.  I am using 'echo -n' in the script.
I understand that this may be bad for security on the one level.  My hardware is an embedded solution and I only need to secure the drive in the event that it is powered up by another system.  It's too easy to brute force a non encrypted drive and redo the sudo password so I would rather there be some encryption to thwart this.
I have been struggling with this for a couple of days and any pointers to getting either of these approaches running would be much appreciated.
My current thinking is that 'none' in the keyscript line may need something in it, and bash may not be up and running at the time of the passkey request.  The problem in the keyfile example may be an order thing in the luks keyfile.  Either way I don't know what I don't know.
Thanks in advance.

A: Two excellent posts from 2015 by Pavel Kogan here regarding Arch Linux luks and here regarding a Debian twist that he worked out, along with the nudge from @davidgo provided me with my luks encrypted autoboot solution.  This is how it works for me.
On a new Ubuntu server 20.04, built with the standard luks options create a keyfile to use as a key then add it to the next luks key slot using cryptsetup.
dd bs=512 count=4 if=/dev/urandom of=/crypto_keyfile.bin
cryptsetup luksAddKey /dev/sda3 /crypto_keyfile.bin

nano into the /etc/crypttab file and using your own encrypted drive logical partition name and primary partition drive enter
dm_crypt-0 /dev/sda3 /crypto_keyfile.bin luks,keyscript=/bin/cat

This fixes the second thing I was doing wrong.  I didn't appreciate that the third entry in the crypttab line (normally seen as 'none') is in fact an argument of the executable (in this case 'cat') called by the keyscript equate.
The third thing I would not have considered unless I had read Pavel's document was that in order for the physical keyfile to be seen there needed to be a hook for initramfs to use.  I copied Pavel's simple script called crypto_keyfile
#!/bin/sh
cp /crypto_keyfile.bin "${DESTDIR}"

into /etc/initramfs-tools/hooks/ and made it executable.
chmod +x /etc/initramfs-tools/hooks/crypto_keyfile

The last thing I did was update the initramfs with
update-initramfs -u

Once I got back to the command line I rebooted linux and this time it loaded without needing the passphrase.
When I took the drive out of the embedded hardware and put it into a separate system and try to mount it, it asked for a passphrase to mount the disk, which is the functionality I was aiming for.


Q: How to manage contiguous memory chunks in modern C++? I've been doing some low level C++ programming these days and it involes a lot of memory management issue. For example, I may need to maintain a chunk of contiguous memory:
char* ptr = static_cast<char*>(malloc(sizeof(char)*512*1024));
....
do_something(ptr); // pass to other functions
....
do_something(ptr+sizeof(int)*4); // random access may be needed
....
free(ptr);

However, many books say that we should avoid using any raw pointer in modern C++ programing and smart pointers are preferred. Thus, what's the best practice for contiguous memory chunk management in modern C++? Should I use something like std::unique_ptr or std::allocator？

A:
"many books say that we should avoid using any raw pointer in modern C++"

It is only owning raw pointers that should be avoided. In your case you need to std::free() the pointer so you own it. Therefore you should definitely put it in a std::unique_ptr but with a custom deleter to call std::free().
// some type aliases to make life shorter...
struct malloc_deleter{void operator()(void* vp) const { std::free(vp); }};
using  malloc_uptr = std::unique_ptr<char, malloc_deleter>;

auto ptr = malloc_uptr(static_cast<char*>(std::malloc(sizeof(char)*512*1024)));
....
do_something(ptr.get()); // pass to other functions
....
do_something(ptr.get()+sizeof(int)*4); // random access may be needed
....
// no need to free, gets done when ptr` goes out of scope.


Q: Python open() function without variable initialization. Is close() method needed? I trying to understand file operations in Python 2.7. Script bellow is writing contents of input_file into output_file.
from sys import argv
script, input_file, output_file = argv

open(output_file, 'w').write(open(input_file).read())

Should I call close() method on files opened in example? (and how to reference object that isn't referenced by variable?) Are opened file objects kept in memory even when not referenced by variable?
English is not my native language; please excuse errors.

A: A better approach would be to use context managers:
with open(inputfile, 'r') as inf:
    with open(outputfile, 'w') as outf:
        out.write(in.read())

close will then be called implicitly on leaving the with block even if an exception is encountered.
However, for that specific example, why not just copy the file?


Q: String Format with undefined number of characters c# So I'm working on formatting a string and I need to line it up in a table, but this string has an undetermined number of characters. Is there anyway to have the string be in the same spot for each column? so far I have:
ostring +=  "Notes\t\t"
+ "       :  "
+ employees[number].Notes
+ "\t\t"
+ employees[number].FirstNotes
+ "\t\t"
+ employees[number].SecondNotes;

I use a similar fashion on the other rows, but they have a pre-determined number of digits, this however doesn't so I can't use the string modifiers like I would like.
Any ideas on what I need to do?

A: You can use String.PadRight() to force the string to a specific size, rather than using tabs.

A: When you are using String.Format item format has following syntax:
{ index[,alignment][ :formatString] }

Thus you can specify alignment which indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).
Also it's better to use StringBuilder to build strings:
var builder = new StringBuilder();
var employee = employees[number];
builder.AppendFormat("Notes {0,20} {1,10} {2,15}",
    employee.Notes, employee.FirstNotes, employee.SecondNotes);

A: You would first have to loop over every entry to find the largest one so you know hoe wide to make the columns, something like:
var notesWidth = employees.Max(Notes.Length);
var firstNotesWidth = employees.Max(FirstNotes.Length);
// etc...

Then you can pad the columns to the correct width:
var output = new StringBuilder();
foreach(var employee in employees)
{
    output.Append(employee.Notes.PadRight(notesWidth+1));
    output.Append(employee.FirstNotes.PadRight(firstNotesWidth+1));
    // etc...
}

And please don't do a lot of string "adding" ("1" + "2" + "3" + ...) in a loop. Use a StringBuilder instead. It is much more efficient.


Q: Lebesgue Integrable in $\mathbb{R}$ Implies Convergence of Integral on $[-n,n]$ $f: \mathbb{R}\rightarrow [0,\infty)$ is integrable on $\mathbb{R}$ with Lebesgue measure $\lambda$, need to show that $f$ is Lebesgue integrable on $[-n,n]$ for each integer $n$, and the sequence $u_n = \int_{-n}^n f d\lambda$ converges.
The part to show that $f$ is Lebesgue integrable on $[-n,n]$ is easy, but how to show that $u_n$ converges? I am currently here:
$$\int_{\mathbb{R}} f d\lambda = \int_{(-\infty,-n]}f d\lambda + \int_{[-n,n]}f d\lambda + \int_{[n,\infty)}f d\lambda$$ using the definition of Lebesgue integral of nonnegative functions. If $u_n =\int_{[-n,n]} f d\lambda$ converges, then $\int_{(-\infty,-n]}f d\lambda + \int_{[n,\infty)}f d\lambda$ needs to go to $0$, and I am not sure how to show that. There is nothing I can say about $f$, and the measure $\lambda([n,\infty))$ is always infinite (?).
Thanks for any help.

A: Let $f:\mathbb{R}\to \mathbb{R}$ be Lebesgue integrable. We have that $\mathbb{I}_{[-n,n]}|f|\leq |f| \in \mathcal{L}^1(\lambda)$ therefore $\mathbb{I}_{[-n,n]}f \in \mathcal{L}^1(\lambda)\, \forall n \in \mathbb{N}$. This also satisfies one of the requirements of the DCT. Pointwise, $\lim_{n \to \infty}\mathbb{I}_{[-n,n]}f(x)=f(x)$ because eventually the set $[-n,n]$ of the indicator function will contain any fixed $x \in \mathbb{R}$. Therefore we can use the DCT
$$\lim_{n \to \infty}\int_{[-n,n]}f\,d\lambda=\lim_{n \to \infty}\int_{\mathbb{R}}\mathbb{I}_{[-n,n]}f\,d\lambda=\int_{\mathbb{R}}f \,d\lambda$$

A: this is a direct consequence of the Monotone Convergence Theorem, by letting $f_n(x)=1_{[-n,n]}f(x)$.


Q: Azure App Service Errors after VIP Swap - Affinity Bug? OK, this is a really weird one and I'm not even sure how to properly describe it.   We had a customer complain that a specific page on our website wasn't working, and one of our internal technicians was able to reproduce the issue as well.  Most of the website is working fine.  This is deployed on Azure App Service.
I checked running the exact same page as the technician, and it worked fine for me.  The entire request is identical, except for authentication cookies.  When I run the request, I get 200 OK, but the technician and the customer get 404 NOT FOUND.
The issue only started after we did a VIP swap this morning on Azure App Service (which I am new to).  I deployed a service update this morning to the Staging Deployment Swap, then a few minutes later did the VIP Swap.  I think that both the customer and the technician had their browser open and session active during the VIP Swap.
I've done some troubleshooting, and here is what I discovered. I can use Fiddler to capture the exact trace for the web page that works fine for me.  Then I can copy only one value from the request for the technician that gets 404 Error, and suddenly I can reproduce the 404 error as well.  The difference is one cookie:
Cookie: ARRAffinity=blahblahblahblah;

My basic understanding is that this is a key for identifying which server the user is connecting to so they get affinity to a specific instance in the load-balanced set (2 servers).  We were able to fix the issue by having the technician and customer delete all cookies in their browser, but even logging out and back in wouldn't fix the issue.
Why would a "stale" affinity key cause a random 404 on one specific page?  Is it possible that some of the user's requests are actually getting directed to the old staging deployment site, even though they are hitting the url that connects to the Production deployment site?

A: There are 2 things here:

*

*The session affinity. As you may read in this article, you can now remove session affinity in web apps, if this deserves your use case (ex. you handle sessions outside the web app or simply you don't have session specific info).

*The 404 error is a bit strange one. It may be from a faulted deployment, so you may want to redo a full deployment on a new slot and swap it again. If still have errors, take a look at the web site itself and see if there isn't any "stateful" code which would give you specific behavior.

Please let us know what happened at the end.


Q: Python Module Not Found Error: First function found, but second is not I have a simple dir structure:
project/
  __init__.py
  main.py
  dir1/
    __init__.py
    foo.py
  dir2/
  dir3/

Inside of main.py:
from dir1.foo import function1, function2

function1 is imported, but function2 is not, and the following error is thrown.

No module named dir1.foo found.

I have no idea how this is possible.
Edit: I am able to use function1 in main(), but when function2 is called the error is thrown.


Q: Is there a way to allow command in sudo based on the current working directory? I want sudo to allow me to run a command when my current working directory is, for example, /tmp. Example usage is removing files from /tmp directory, so I am in /tmp ($PWD of shell == /tmp), then I can run, rm -v someuseless.bin (someuseless.bin of course not belongs to me, so I can't remove it).
If it is impossible (I can't find references in sudo manuals), then why? Maybe there is a security violation that I did not spotted here. Thanks.

A: You can definitely embed the $cwd in sudoers, to allow someone only to remove a file under a particular directory, but you're going the wrong way about it.  The way to do what you want is to use absolute paths in sudoers, eg
orc       ALL=(ALL) /bin/rm /tmp/someuseless.bin

A: You can write a shell script which checks for the current directory, then give sudo rights to run that script.
/usr/local/bin/cwddostuff.sh:
#!/bin/sh

if [ "$CWD" != "/tmp" ]; then
   exit 1
fi

echo do your stuff

/etc/sudoers:
user       ALL=(ALL) /usr/local/bin/cwddostuff.sh

But beware doing this is dangerous, as now you need to check also if all arguments are ok (for example, the user might be in /tmp, but run 'rm -rf /').
The best way is to do as MadHatter told, explicitly add the paths the user is allowed to remove, or as Kwaio suggested, set ACLs on the directories.


Q: How do you get Endeca to search on a particular target field rather than across all indexed fields? We have an Endeca index configured across multiple fields of email content - subject and body. But we only want searches to be performed on the subject lines. Endeca is returning matches within the bodies too. How do you limit the search to the subject?

A: You can search a specific field or fields by specifying it (them) with the Ntk parameter.
Or if you wish to search a specific group of fields frequently you can set up an interface (also specified with the Ntk parameter), that includes that group of fields.

A: This is how you can do it using presentation API.
final ENEQuery query = new ENEQuery();
final DimValIdList dimValIdList = new DimValIdList("0");
query.setNavDescriptors(dimValIdList);
final ERecSearchList searches = new ERecSearchList();
final StringBuilder builder = new StringBuilder();
for(final String productId : productIds){
    builder.append(productId);
    builder.append(" ");
}
final ERecSearch eRecSearch = new ERecSearch("product.id", builder.toString().trim(), "mode matchany");
searches.add(eRecSearch);
query.setNavERecSearches(searches);

Please see this post for a complete example.

A: Use Search Interfaces in Developer Studio.
Refer - http://docs.oracle.com/cd/E28912_01/DeveloperStudio.612/pdf/DevStudioHelp.pdf#page=209


Q: Build failure while trying to update to "org.jooq:jooq-codegen-maven:3.15.1" [ERROR] Failed to execute goal org.jooq:jooq-codegen-maven:3.15.1:generate (default) on project event-dao-jooq: Execution default of goal org.jooq:jooq-codegen-maven:3.15.1:generate failed: Unable to load the mojo 'generate' in the plugin 'org.jooq:jooq-codegen-maven:3.15.1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/jooq/codegen/maven/Plugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

A: jOOQ 3.15 requires Java 11 (class file version 55) and you are using Java 8 (class file version 52) in your build. You either need to upgrade to Java 11, downgrade to jOOQ 3.14, or purchase a license for jOOQ 3.15 as all of the commercial editions still support Java 8.


Q: CSS and HTML doesn't shows properly in iOS and MacOS Safari even Chrome I have the following issue:
I have this under construction state website, https://endertainment.com, it was build with PHP and MySQL from scratch, like any other I did. The issue is when you access the website from Mobile Safari or Safari the website doesn't show all the elements must show. When you access from Android (Any Browser) or Windows or even in Linux the website shows any element well. I already run test in BrowserStack and CrossBrowserTesting... in both shows the same result; the web didn't show properly. I already remove every flexbox property and use inline-block instead. For example, this other website (https://tuticketazo.com) is under construction state too and use the same structure of https://endertainment.com.
I already made tests changing the server folder the domain points; upload a simple html page from scratch, without PHP ; use without SSL... I think already test everything but in iOS Safari, Mac OS Safari and even in Chrome in MacOS shows the elements but not in the right way.

A: You should set line-height of your heading titles.
#MainTitles h1 { line-height: 50px }

#LangSelect a { line-height: 20px; }

But the problem is not inside these 2 rules. I didn't determinate full code of CSS, I just check small fixes for places which I saw broken

A: I found the problem and resolve the Issue.
OS X have a rendering issue with some fonts.
I start my research searching a common pattern, I has this issue with 3 websites:

*

*Adjusting the line-height didn't work properly.

*Change the ul from inline-block to flexbox, didn't work

*The issue is present in any browser in Mac OS (I test Chrome,
Firefox and Safari)

Continue researching an I found some documentation about the issue.
I found this article
OS X type rendering - text baseline is shifted upwards, effectively no-longer centered vertically within the line-height
I test in the 3 different websites have the issue and VOILA!
Everything works fine now.
I used in the 3 websites the same fonts (the common pattern):

*

*Gotham Book

*Gotham Black

I can confirm this two fonts evoke the rendering issue in Mac Os.
The problem is solved right now.


Q: Wireless N extend G range? I've searched all over the internet for an answer to this and I can't find one. If I purchase a wireless N router, with greater range than my current G router will the range of the wireless G signal go as far as the wireless N signal? I say this because Wireless N routers are supposed to be compatible with wireless G devices. Is the wireless G a lesser signal coming out of the router?
Sorry if I confused you, I am a little confused myself.

A: The greater range for N protocol routers and WNICs is when you are using them together.  Thus an N router with a G Nic won't have any greater range than a G router with a G Nic.  As always, different routers will provide different ranges... some are just better than others (dual antennae, internal antennae, etc.)
You can think back to when G was new and people were still using B protocol devices.  It was the same deal.  So, in order to get an increased range using an N router, you would have to purchase N Nics for all the devices you were connecting to it... unless you wanted to move your N router somewhere more centrally located, or swap any antenna with high gain units.  So, either you replace all your networking hardware, or rework your network setup.

A: What makes it confusing, is the term N wireless refers both to the protocol 802.11N and less accurately to the new devices that may have implemented that protocol at a particular frequency. So depending on the device pair you are using (router and wireless card) may support both protocols (G and N). Typically routers that support 802.11N have 5ghz signal options that help N but don't support G.


Q: How to get a UTF8 encoded string from a Base64 encoded string in Javascript? AEEAQgBDAGEAYgBj is Base64 for ABCabc however when I run this code:
let a = Buffer.from('AEEAQgBDAGEAYgBj', 'base64').toString('utf-8');
console.log(Buffer.from(a, 'utf8'));

the printed result in the console is <Buffer 00 41 00 42 00 43 00 61 00 62 00 63> which is UTF16 (LE).
I would assume that since I am creating a Buffer from a UTF8 encoded string the result would be <Buffer 41 42 43 61 62 63>.
So how can I get an actual UTF8 encoded string from Base64?

A: The problem is that your original data is Base64 encoded UTF16-BE. If you look at a after your first line, you'll see that it has those zero bytes that you see in the final buffer:
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").toString("utf-8");
console.log(a.length);
// 12
console.log([...a].map(ch => ch.charCodeAt(0).toString(16).padStart(2, "0")).join(" "));
// 00 41 00 42 00 43 00 61 00 62 00 63

So the question becomes: How to read the UTF16-BE text you have in the buffer from Buffer.from("AEEAQgBDAGEAYgBj", "base64"). Node.js's Buffer doesn't support UTF16-BE directly (there is no "utf16be" encoding in its standard library), but you can get there via swap16 and then reading the buffer as UTF16-LE ("utf16le", which is in Node.js's standard library):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc

Now a is a normal string. If you want a buffer containing its contents in UTF8, you can use Buffer.from(a).toString("utf8"):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
let b = Buffer.from(a); // (Default is `"utf8"` but you could supply that explicitly)
console.log(b);
// <Buffer 41 42 43 61 62 63>


Q: Host (baseband) controller in mobile phone Hi mobile world I met many times the term "host controller" or "baseband controller" used interchangeably in the context of being the heart of the mobile. What exaclty is that, som SoC with CPU, GPU, GSM modem???

A: Typically the 'host' refers to the master device/entity that belongs to the
side of the computer. It could be inside computer or external to a computer.
[it could be a microcontroller , but the point is host is more closer to you
when you writing software to work with].
The main idea is before you communicate with the other device, you communicate
with the host, for a example hard disk controller is a host, USB controller chip
is a host.
So according to your GSM module thing, The chip hardware/software that parsing the
AT command set and act as a front end is refereed as a host.
Your Manual/Specification probably should have a chapter called terms and Abbreviations.
Turn out for that page and you'll find the specific abbreviation which is specific to
your module.


Q: Check if PDFTOHTML is installed on server I'm trying to check before running a php script if pdftohtml is installed on server.
Is there a way to check if pdftohtml is installed on server (linux or mac) from within the code.
I'm looking for something similar to function_exists()

A:
Perhaps, the following will solve your case:
$isInstalled = (bool) shell_exec('which pdftohtml');

which returns nothing if the program isn't found. But it will only work if it's installed globally (without specifying an absolute path). And returns a full path if it's there


Q: Does every operation need to be a single Command?
What I want to know:
Does every single operation provided on the list in the background paragraph need to be a single command? What do the single commands do?

Background:
I need to write a program which gets started from the cmd and performs operations on a string you can enter as argument to the command line. You also need to pass the operations to be performed as CLA.
For example: myprogram.exe /es "This is the string" /ds /rs .
Es = Enter string, ds = display string, rs=  reverse string.
It is not necessary to implement Undo/Redo.

Possible Operations are:
• Enter string
• Display string
• Reverse string
• Upperace all letters
• Lowercase all letters
• Uppercase specific letters
• Lowercase specific letters
• Eliminate consecutive duplicates
• Rotate left
• Rotate right
• Run-length encoding
• Run-length decoding
• Drop every n'th character
• Split by string and take first
• Split by string and take last

What did I do / What is my approach:
I recognized after some research that the optimal way of implementing this example would be to use the Command Pattern and Chain Of Responsibility. I'm reading the book written by the Gang of Four : Design Patterns.
But I think I do not understand perfectly the concept. I know, that using Command Pattern there is a: Invoker, Receiver, Command, CommandInterface etc. I know that the Invoker (here my ProgramHandler.cs class) generates the single Commands, equips them with a receiver and an Action. And the single Command calls the receiver to execute the action. The receiver is a class called StringManipulator which holds all the methods to manipulate a string. My idea is also, that the parser parses the CLA and "tells" the ProgramHandler which Commands need to be created.
(Please have a look on my first design approach, picture at the end!)
But:

Additional Questions:
Isn't that quite a bit of an overhead of having an abstract class SimpleCommand which holds the receiver and action and afterwards the concrete commands inherit from SimpleCommand?
It feels a bit wrong, but on the other hand: Each command needs an action and a receiver, so giving each concrete command these fields separately would be against the "rules" of object oriented Programming.
How is this designed correctly?

Class Diagram
Class Diagram
Thank you for your time and help!
Best regards!


Q: How to click automatically on "Content" button This is element HTML:
<button class="search-vertical-filter__filter-item-button button-tertiary-medium-muted" data-ember-action="" data-ember-action-5975="5975"> Content </button>

Code:
driver.find_element_by_link_text('Content').click()

Even i also tried:
driver.find_element_by_class_name('search-vertical-filter__filter-item-button button-tertiary-medium-muted').click()

I want to click on "Content" button on LinkedIn automatically and I am using Selenium and Python for that.

A: As per the HTML provided to click on the button with text as Content you can use the following line of code :
driver.find_element_by_xpath("//button[@class='search-vertical-filter__filter-item-button button-tertiary-medium-muted' and normalize-space()='Content']").click()

A: Try to use the following code:
driver.find_element_by_css_selector(".search-vertical-filter__filter-item-button.button-tertiary-medium-muted").click()

Hope it helps you!


Q: Error a la hora de llamar a un método con Java Intento llamar a un método de otro método para que me lea un archivo y depuse escriba los resultados en un archivo externo. pero estoy teniendo problema a la hora de llamar al método.

==== Código =====
import java.util.Scanner;
import javax.swing.*;
import java.io.*;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;

// Declared class Invie
public class Invie {
    // Declared Object Scanner;
  static Scanner input = new Scanner(System.in);

// Declaring the metohd menu
// And declaring menu items.
// Declaring variable lisMenu for creating menu
 public static void Menu () {
    String listMenu = "";

    JOptionPane.showMessageDialog(null, "Welcome to Invie App");

    do {
        listMenu = JOptionPane.showInputDialog(null, "a. Add items\n b. Show items\n c. Remove items\n x. Exit", "Menu", JOptionPane.INFORMATION_MESSAGE);

        if (listMenu.equals ("a")) {
            JOptionPane.showInputDialog(null, "Upc Number of product:\n", "Addign items", JOptionPane.INFORMATION_MESSAGE);
            JOptionPane.showInputDialog(null, "Name of product:\n", "Addign items", JOptionPane.INFORMATION_MESSAGE);
            JOptionPane.showInputDialog(null, "Date of product:\n", "Addign items", JOptionPane.INFORMATION_MESSAGE);
            JOptionPane.showInputDialog(null, "Quantity Sold of product:\n", "Addign items", JOptionPane.INFORMATION_MESSAGE);
            JOptionPane.showInputDialog(null, "Items Prices of product:\n", "Addign items", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (listMenu.equals ("b")) {
            JOptionPane.showMessageDialog(null, "Showing items");
        }
        else if (listMenu.equals ("c")) {
            JOptionPane.showConfirmDialog(null,"Are you sure you want to delete a product? ", "Delet the items", JOptionPane.YES_NO_CANCEL_OPTION);
        }
        else if (listMenu.equals ("x")) {
            JOptionPane.showMessageDialog(null, "Thank you for user own system. See it soon!", "Exit!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
        else {
            JOptionPane.showMessageDialog(null, "Please try agen.", "Error!", JOptionPane.ERROR_MESSAGE);
        }
    }while(!listMenu.equals("x"));
}

     // Declaring the metohd call name
    // And declaring multiple variable
    // Reader, fileInput, fileOutput and the array name productNamesList has 50 items
    // Adding integer variable matchesCount, date, upcNumber, experDate, quantitySold, itemsPrices
    // Collect the data when the user enters the product number
    public static void Name (String listMenu) {
        FileReader reader;
        Scanner fileInput;
        PrintWriter fileOutput;
        String productNamesList [] = new String [30],
        product, strLine;

        int matchesCount = 0, date, upcNumber, experDate, quantitySold, itemsPrices;

        String namesOfInputFile = JOptionPane.showInputDialog(null, "Name of the input file and add .txt: ");

        String namesOfOutputFile = JOptionPane.showInputDialog(null, "Name of the output file and add .txt: ");

        // Input try
        try {
            reader = new FileReader(namesOfInputFile);
            fileInput = new Scanner (reader);

            while (fileInput.hasNextLine()) {
                strLine = fileInput.nextLine();
                product = strLine;
                upcNumber = Integer.valueOf(strLine);

                if (productNamesList.equals("b")) {
                    productNamesList[matchesCount] = product;
                    matchesCount += 1;
                }
            }
            fileInput.close();
        }catch(IOException error) {
            System.out.print("File error " + error);
        }

        // Output try
        try {
            fileOutput = new PrintWriter(namesOfOutputFile);
            for (int i = matchesCount - 1; i >= 0; i --) {
                if (namesOfOutputFile.equals(productNamesList)){
                    JOptionPane.showMessageDialog(null, productNamesList[i]);
                }
            }
            fileOutput.close();
        }catch(IOException error) {
            System.out.print("File error " + error);
        }
    }
    // The main function
    // Calling the matohd
    public static void main(String[] args) {
        Invie myMenu = new Invie();
        String[] menuList = {"Meet", "Fish", "Cake"};
        Menu();
        Name(listMenu);
  }
}

El Error es el siguiente:
====Error=====

PS C:\Users\herna\Documents\Projecto-Final> javac Invie.java
  Invie.java:118: error: cannot find symbol
                  Name(listMenu);
                       ^   symbol:   variable listMenu   location: class Invie 1 error

A: Hola la solución es dejar tu variable String listMenu = "";
Como global a la clase y estatica:
public class Invie {
// Declared Object Scanner;
static Scanner input = new Scanner(System.in);
static String listMenu = "";

Esto porque la variable listMenu esta en otro contexto, es una varible local así como la tienes.
Saludos y esper que te sirva.

A: El error:
Invie.java:118: error: cannot find symbol
                Name(listMenu);
                     ^
  symbol:   variable listMenu

se refiere a que no encuentra la definición de la variable listMenu.

La definición de la variable listMenu se esta realizando dentro de el método:
 public static void Menu () {
    String listMenu = "";
   ...
   ...
 }

por lo tanto al usarla dentro del método main() no encuentra su definición, debes realizarla a nivel de clase (global):
public class Invie {

  static Scanner input = new Scanner(System.in);
  String listMenu = "";

 public static void Menu () {
 ...
 ...
 }
}


Q: Get body of request in ASP.NET Web Api I faced problem like this.
I have method in controller, that receive data in body of POST request.
Here is method.
 // POST: api/StartWorkingDays
    [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully"});
        //return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }

How I can see body of request that I receive?
Thank's for help.

A:     [HttpPost]
    public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay)
    {
      //here above startWorkingDay is body your mobile developer will send
       //you and data can be viewed while debugging ,
       //tell mobile developer to set content-type header should be JSON.
       return Request.CreateResponse(HttpStatusCode.Created, "Success");
    }

Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder


Q: Google Cloud Endpoint do not receive a request coming from ORANGE money API I have an endpoint that receives get or post requests from postman or a browser. but when the ORANGE service sends me the request in post I receive nothing.
anxious to believe that the problem comes from the ORANGE service, I went to this site https://webhook.site which generates an end point and listens to the requests made on this one, and to my surprise this endpoint receives many requests from ORANGE.
I don't understand where the problem could come from.


Q: SQLException Error Says Existing Column Doesn't Exist When running a searchQuery, I get a SQLException error saying that one of my columns cannot be found. This is very confusing, as I reference that column earlier in the code, and the program can find the column just fine at that point. do I have something wrong in the syntax? Thank you!
public void createDB(){
    String createCharTableSQL = "CREATE TABLE CosplayCharacter (" +
                "CharacterID int NOT NULL primary key GENERATED ALWAYS " +
                "AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
                "name varchar(60) not null," +
                "gender varchar(10)," +
                "genreID int, " +
                "universeID int, " +
                "mediaID int, " +
                "description varchar(60))";

      statement.executeUpdate(createCharTableSQL);
}

public void insertCharacter(){
  String fetchAllDataSQL = "SELECT * from CosplayCharacter";

    //Code can find the universeID column here
        resultSet = statement.executeQuery(fetchAllDataSQL);
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            int universeCharID = resultSet.getInt("universeID");

            System.out.println("Character Name : " + name +
                    " UniverseID : " + universeCharID);
        }
}

//But returns error here
public void searchCharacter(String characterName){
    String fetchAllDataSQL = "SELECT * from CosplayCharacter where name = '" + characterName +"'";

        resultSet = statement.executeQuery(fetchAllDataSQL);
        while (resultSet.next()) {
            String gender = resultSet.getString("gender");
            int genreID = resultSet.getInt("genreID");
//Method to search a column in a joined table; no error
            String genreName = getGenreName(genreID);
            int universeID = resultSet.getInt("universeID");
   }
}

Stack Trace:
 java.sql.SQLException: Column 'universeID' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown
Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)

A: ResultSet was used globally. ResultSet used in getGenreName method override the resultSet in the main searchCharacter method. Solution: set ResultSet variable individually in each method.


Q: How to return value from addEventListener and use it out When I want to access to variable det out of addEventListener I get  undefined.
ElementInfo = function(element) {
  var myVar;
  this.tagName = element.tagName;
  document.addEventListener('Mylistener', function(e) {
    myVar = e.detail.workspaceName;
  });
  this.injected = myVar;
}

How can I get the value of myVar out of addEventListener? I don't use JQuery.


Q: How to get all pom.xml present under maven repo Is there any way to get all the pom.xmls which are under http://repo.maven.apache.org/maven2
Thanks,
Vijay

A: As a best practice, you should not scan and parse poms neither in remote nor local repository. On maven central they already scanned and parsed for you.
Just download nexus-maven-repository-index.gz from index dir (you need that big file 700M length, other files named nexus-maven-repository-index.XXX.gz are incremental updates)
Then use Maven Indexer to unpack index, maven indexer is available as java library and CLI program
As a result of running Maven indexer you'll get ordinary Apache Lucene index, with abitility to update it incrementally.
Here is a documentation, which explains how to unpack index and query data from it.
Most probably, index contain all the data you need.

A: For people still having the same question, I have developed a much simpler way to extract maven index indexes that works for most Nexus-based Maven repositories: the Maven Index Exporter.
From there you could simply get a list of poms and download them, if that's what you aim for.
Note however that it's huge: roughly 20 million documents are indexed for Maven Central and the text export is 14GB. There are as of today approximately 6.5 million pom files on Maven Central.


Q: Set credentials on an Android Webview using secured HTTPS connection I would like to create an Android Webview that connects to a website via a secured HTTPS connection with the use of credentials.
First difficulty was to accept the certificate (private), it was solved with this very useful post.
Second difficulty is to use credentials, I found this post.
(first answer from dparnas) which seems to deal pretty well with it, but it talks about HTTP connection and not HTTPS. I ve tried it, but it doesnt work, I just reach the sign-in form page without any error message, just the normal blank form.
Here is my code:
import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ConnectorWebView extends Activity {
  WebView mWebView;
  String mUsrName;
  String mPassC;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connwebview);

    // Getting info from Intent extras
    // Get it if it s different from null
    Bundle extras = getIntent().getExtras();
    mUsrName = extras != null ? extras.getString("username") : null;
    mPassC = extras != null ? extras.getString("passcode") : null;

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setHttpAuthUsernamePassword("myhost.com", "myrealm", mUsrName, mPassC);

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedHttpAuthRequest  (WebView view, HttpAuthHandler handler, String host, String realm){
          handler.proceed(mUsrName, mPassC);
        }

        public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
          handler.proceed() ;
        }
      });

    mWebView.loadUrl("https://myhost.com/secured_area");
  }
}

A: The WebView class doesn't provide as much flexibility in its connectivity as using the low level classes (such as HttpPost or the like) directly.
If you need to fully control the connection to the server -- or deal with complicated authorization scenarios such as this one -- use the low level classes, retrieve the data, then use WebView.loadData() to load and show the HTML.
Here is a good example of loading content using SSL and a BasicCredentialProvider.  The result of this could be loaded into the WebView as described above.

A: As it seems that WebView cannot natively handle Basic authentication when using HTTPS, I started toying with the idea of setting the Authorization header (containing the encoded username/password) manually.
Here's how I think this can be done:
import org.apache.commons.codec.binary.Base64;

// ...

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.connwebview);

  // Getting info from Intent extras
  // Get it if it s different from null
  Bundle extras = getIntent().getExtras();
  mUsrName = extras != null ? extras.getString("username") : null;
  mPassC = extras != null ? extras.getString("passcode") : null;

  mWebView = (WebView) findViewById(R.id.webview);
  mWebView.getSettings().setJavaScriptEnabled(true);
  // mWebView.setHttpAuthUsernamePassword("myhost.com",
  //                                   "myrealm",
  //                                   mUsrName,
  //                                   mPassC);

  mWebView.setWebViewClient(new WebViewClient() {
      @Override
      public void onReceivedHttpAuthRequest(WebView view,
                                            HttpAuthHandler handler,
                                            String host,
                                            String realm){
        handler.proceed(mUsrName, mPassC);
      }

      public void onReceivedSslError(WebView view,
                                     SslErrorHandler handler,
                                     SslError error) {
        handler.proceed() ;
      }
    });

  String up = mUserName +":" +mPassC;
  String authEncoded = new String(Base64.encodeBase64(up.getBytes()));
  String authHeader = "Basic " +authEncoded;
  Map<String, String> headers = new HashMap<String, String>();
  headers.put("Authorization", authHeader);
  mWebView.loadUrl("https://myhost.com/secured_area", headers);
}

This takes advantage of the WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method and for this example I'm using the Base64Encoder from Apache Commons. The Base64Encoder part is quite trivial and if you didn't want to include external libraries in your application (for whatever reason), you could always write your own (reference).
Also note that the aforementioned WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method is only available in API 8+. For reference, see also the Wikipedia article on Basic Authentication (which discusses the headers, etc).

A: Alternative Scenario:
If willing to write roundabout 10 lines of javascript using jQuery, this scenario is rather simple.
Inject your javascript code into the webview or in case you're controlling the html page you are displaying, include it there.
If you need to interface back from javascript, you can do that. For heavier command exchange, use the CordovaWebView-Interface which has a lower delay depending on api level.


Q: Draw on desktop (windows/ubuntu) using python I am doing a project in which I need to show lines on window. Also I want to move cursor along the line. I am looking forward to work in python.
How can I do this using python or other languages. Please help me

A: i only just found this out and here you go.
import win32gui

def DRAW_LINE(x1, y1, x2, y2):
    hwnd=win32gui.WindowFromPoint((x1,y1))
    hdc=win32gui.GetDC(hwnd)
    x1c,y1c=win32gui.ScreenToClient(hwnd,(x1,y1))
    x2c,y2c=win32gui.ScreenToClient(hwnd,(x2,y2))
    win32gui.MoveToEx(hdc,x1c,y1c)
    win32gui.LineTo(hdc,x2c,y2c)
    win32gui.ReleaseDC(hwnd,hdc)

x1 = 640
y1 = 400
x2 = 840
y2 = 600

DRAW_LINE(x1, y1, x2, y2)

as for moving your mouse underneath the lines i cant figure that out


Q: 'Group by' is not grouping by in the order that I need it to I want to 'group by' beers so that they are grouped together, with the respect aggregate rating and tasters (people who review the beers) listed in separate columns.
Here is my code:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
;

Yet my output looks like this:
beers=# select * from tasters_avg_ratings1;
 taster |          beer          | rating
--------+------------------------+--------
 Peter  | XXXX                   |    5.0
 Sarah  | James Squire Pilsener  |    3.0
 Raghu  | Sierra Nevada Pale Ale |    3.0
 Hector | Fosters                |    3.0
 John   | Chimay Red             |    3.0
 John   | Sierra Nevada Pale Ale |    5.0
 Geoff  | James Squire Pilsener  |    4.0
 Ramez  | Sierra Nevada Pale Ale |    4.0
 John   | 80/-                   |    4.0
 John   | Rasputin               |    4.0
 Adam   | Old                    |    4.0
 John   | Crown Lager            |    2.0
 Jeff   | Sierra Nevada Pale Ale |    4.0
 Sarah  | Burragorang Bock       |    4.0
 Sarah  | Scharer's Lager        |    3.0
 Sarah  | New                    |    2.0
 Geoff  | Redback                |    4.0
 Adam   | Victoria Bitter        |    1.0
 Sarah  | Victoria Bitter        |    1.0
 Raghu  | Rasputin               |    3.0
 Ramez  | Bigfoot Barley Wine    |    3.0
 Hector | Sierra Nevada Pale Ale |    4.0
 Sarah  | Old                    |    3.0
 Jeff   | Burragorang Bock       |    3.0
 John   | Empire                 |    3.0
 Sarah  | James Squire Amber Ale |    3.0
 Rose   | Redback                |    5.0
 Geoff  | Empire                 |    3.0
 Adam   | New                    |    1.0
 Jeff   | Rasputin               |    1.0
 Raghu  | Old Tire               |    5.0
 John   | Victoria Bitter        |    1.0
(32 rows)

As you can see, the beers are NOT grouped together. Ideally for example, the 'Victoria Bitter' beers should be displayed as a group, not separated.
The desired result is achieved using 'order by'. For example:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
order by a.beer
;

OUTPUT:
beers=# select * from tasters_avg_ratings1;
 taster |          beer          | rating
--------+------------------------+--------
 John   | 80/-                   |    4.0
 Ramez  | Bigfoot Barley Wine    |    3.0
 Jeff   | Burragorang Bock       |    3.0
 Sarah  | Burragorang Bock       |    4.0
 John   | Chimay Red             |    3.0
 John   | Crown Lager            |    2.0
 Geoff  | Empire                 |    3.0
 John   | Empire                 |    3.0
 Hector | Fosters                |    3.0
 Sarah  | James Squire Amber Ale |    3.0
 Geoff  | James Squire Pilsener  |    4.0
 Sarah  | James Squire Pilsener  |    3.0
 Adam   | New                    |    1.0
 Sarah  | New                    |    2.0
 Adam   | Old                    |    4.0
 Sarah  | Old                    |    3.0
 Raghu  | Old Tire               |    5.0
 Jeff   | Rasputin               |    1.0
 John   | Rasputin               |    4.0
 Raghu  | Rasputin               |    3.0
 Geoff  | Redback                |    4.0
 Rose   | Redback                |    5.0
 Sarah  | Scharer's Lager        |    3.0
 Hector | Sierra Nevada Pale Ale |    4.0
 Jeff   | Sierra Nevada Pale Ale |    4.0
 John   | Sierra Nevada Pale Ale |    5.0
 Raghu  | Sierra Nevada Pale Ale |    3.0
 Ramez  | Sierra Nevada Pale Ale |    4.0
 Adam   | Victoria Bitter        |    1.0
 John   | Victoria Bitter        |    1.0
 Sarah  | Victoria Bitter        |    1.0
 Peter  | XXXX                   |    5.0
(32 rows)

So while I know order by achieves my result, why doesn't 'group by' do the same thing? It is frustrating because I have seen numerous examples on the internet using 'group by' and succeeding especially in cases similar to mine with non-aggregate and aggregate columns. For example: https://learnsql.com/blog/error-with-group-by/ , at tip #3.
Any help would be appreciated, thanks!

A: GROUP BY is only being used to compute the aggregate value (average rating in this case). It doesn't have anything to do with the ordering of the results when they are displayed. As you have mentioned, you need to use ORDER BY to get the desired ordering.

A: Group By should be used to group rows that have the same value for the specified column,
Full explanation here https://stackoverflow.com/a/2421441.
In your case, you want to group beers with the respect to aggregate rating and tasters, so you need to GROUP  BY a.beers and order by the first and the third column.
Thus the view should be like this:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by a.beer
order by 1,3;

1 and 3 are the ordinal positions of columns that appear in the select list.

A: The SQL standard defines that a SELECT statement without an ORDER BY may return the resulting rows in an arbitrary order. There is a good explanation of why it might look different at first.
GROUP BY is for grouping and aggregating related tuples together. A trivial implementation for grouping is of course sorting the data first and then working your way from top to bottom and aggregate related tuples. If your database chooses to use such an implementation chances are high you will receive an ordered result set. But there are other implementations possible and your database may change to using one of those at any time. And if it does you will receive the same rows but in a different order.
So in short, if you want your result set to be ordered use an ORDER BY.
Regarding the example you mentioned it is perhaps a bit misleading. The result is ordered by the columns it is also grouped by. This is a possible ordering and given the thoughts before probably quite a likely one. But since the query is without an ORDER BY this is just coincidence and not guaranteed.


Q: Add URL to selected post in meta box How can I change this code
$posts = get_posts(array('post_type'=> 'lesson', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
        //here you add the HTML of the dropdown you add something like

        echo '
Select the lesson: <select name="_dappcf_i_dropdown" class="widefat"  style="width:170px" >';
        foreach ($posts as $post) {
        echo '<option value="', $post->ID, '"'; if  ($my_dropdown == $post->ID){echo ' selected="selected"';} echo '>'.$post->post_title.'</option>';

        }
    echo '</select>';
}

to echo the title of the selected post in page template with the URL of of SELECTED post(the title should be a link)?
Thanks in advance

A: Super short version:
Replace $post->post_title with get_permalink($post->ID).
Short version:
Add a filter to your current Code, where you output the post_title.
$posts = get_posts(array('post_type'=> 'lesson', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
        //here you add the HTML of the dropdown you add something like

        echo '
Select the lesson: <select name="_dappcf_i_dropdown" class="widefat"  style="width:170px" >';
        foreach ($posts as $post) {
        echo '<option value="', $post->ID, '"';
        if  ($my_dropdown == $post->ID){echo ' selected="selected"';}
        echo '>'.
        apply_filters('filter_list_cpt', $post->post_title, $post).
        '</option>';

        }
    echo '</select>';

Somewhere in your functions.php or plugin file:
function filter_list_cpt($title, $cpt) {
    return sprintf(__('%1$s [%2$s]', 'my_textdomain'), $title, get_permalink($cpt->ID));
}

add_filter('list_cpt', 'filter_list_cpt', 10, 2);

But why stop here? Let us improve the provided code and put it into a WordPress perspective.
Better approach
WordPress has its own helper functions to return a select of e.g. pages. So instead of just writing code, lets try to copy and rewrite this function to our needs. I call it: my_dropdown_post_type
function my_dropdown_post_type( $post_type = 'lesson', $args = '' ) {
    $defaults = array(
        'depth' => 0, 'child_of' => 0,
        'selected' => 0, 'echo' => 1,
        'name' => "{$post_type}_id", 'id' => '',
        'class' => '',
        'show_option_none' => '', 'show_option_no_change' => '',
        'option_none_value' => '',
        'value_field' => 'ID',
        'post_type' => $post_type
    );

    $r = wp_parse_args( $args, $defaults );

    $cpt = get_posts( $r );
    $output = '';

    if ( ! empty( $cpt ) ) {
        $class = '';
        if ( ! empty( $r['class'] ) ) {
            $class = " class='" . esc_attr( $r['class'] ) . "'";
        }

        $output = "<select name='" . esc_attr( $r['name'] ) . "'" . $class . " id='" . esc_attr( $r['id'] ) . "'>\n";
        if ( $r['show_option_no_change'] ) {
            $output .= "\t<option value=\"-1\">" . $r['show_option_no_change'] . "</option>\n";
        }
        if ( $r['show_option_none'] ) {
            $output .= "\t<option value=\"" . esc_attr( $r['option_none_value'] ) . '">' . $r['show_option_none'] . "</option>\n";
        }
        $output .= walk_page_dropdown_tree( $cpt, $r['depth'], $r );
        $output .= "</select>\n";
    }

    $html = apply_filters( 'wp_dropdown_pages', $output, $r, $cpt );

    if ( $r['echo'] ) {
        echo $html;
    }
    return $html;
}

Then we apply our list_pages filter
function filter_list_cpt($title, $cpt) {
    if ($cpt->post_type == 'lesson')
        return sprintf(__('%1$s [%2$s]', 'my_textdomain'), $title, get_permalink($cpt->ID));
    return $title;
}

add_filter('list_pages', 'filter_list_cpt', 10, 2);

In the end we can call our my_dropdown_post_type function like any other basic WP function:
my_dropdown_post_type(
    'lesson',
    array(
        'selected' => $my_dropdown,
        'post_status'=> 'publish',
        'suppress_filters' => false,
        'posts_per_page'=>-1
    )
);


Q: When is the screenshot taken for the app drawer? I have an app with a login page.  In the login page, I have a switch to allow the user to show the password they are entering in plain text to ensure they are entering it correctly.  However, when I pause the app and the app goes into the background, a screenshot is taken and the plain text password can be seen in the app drawer.
I tried adding a statement in the onPause() method of the activity to turn off the Hide/Show switch before pausing.  You can see the password revert back to a masked password before the app pauses, but the screenshot still shows the plain text password.
So I'm wondering when the screenshot for the app drawer is taken and whether I can get the password switched back to masked before that happens.
I know about the FLAG_SECURE window flags but that creates a black app drawer screenshot and I would prefer to give something more user-friendly to the user.
Thanx in advance.

A: Unfortunately, what you want is not supported. There is a method in Activity called onCreateThumbnail() that can be overridden to provide a custom thumbnail, but according to a post from Dianne Hackborn in 2009, this method is never actually called:
https://groups.google.com/d/msg/android-developers/J5uBtHzhG8E/bX43j_GAm4gJ
I've tried it relatively recently myself to no effect, so I have to assume that's still the case.


Q: Retaining a value obtained from file within the return value of a method Assuming I will need to access the values contained within a given file a small number of times, from different methods, can I include some sort of boolean value within a method to determine whether or not it is appropriate to call the file?
Lets say I have the file config.cfg. In that file, there are three values:
string/name>max|
bool/adult>yes|
int/age>20|

The method getUserName() returns the value of "max". It does this by calling the file:
using (StreamReader reader = new StreamReader(path))
{
    //get line beginning with string/name here
    return //string value containing name
}

Let's assume I need to use the value of name several times, as well as the values isAdult and clientAge. Rather than accessing the file over and over again, it could be much easier to save the requested value in some form of static variable. However, this variable still needs to be changed in value at least once, when the method is first called.
Can I do this inside the method getUserName()?
Furthermore, is this idea even possible within the bounds of OOP? Is it a similar concept to Prefetch?

A: Create a static class. Something like this:
 public static class ClientConfig{

    public static string Name{get;set;}
    public static bool IsAdult{get;set;}
    public static int Age{get;set;}

     public static void Load(){
     // load your values
    // ClientConfig.Name = name from file etc.
    }

    public static void Save(string newName, int age, bool value){
     // save your values to the config file
    }
    }

And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)

A: It really looks to me that you  need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());

Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value.


Q: Facebook JavaScript SDK help 1002 I am using the jQuery library for authenticating the user, using this script:


Q: whitelist allowed hosts, block everything else using the chrome.declarativeWebRequest, it is possible to execute actions if some conditions apply. The only available Condition is an Instance of declarativeWebRequest.RequestMatcher which is useful to test if the url has some features. I am searching for a way to test if an url does not have some features For instance:
chrome.declarativeWebRequest.onRequest.addRules([
  {
    conditions: [
      new chrome.declarativeWebRequest.RequestMatcher({
        url: { hostSuffix: 'google.com' } })
    ],
    actions: [
      new chrome.declarativeWebRequest.CancelRequest()
    ]
  }
]);

Will block all Requests to the host google.com. But I am interested in a rule that does the opposite, block everything but google.com.

A: According to documentation, you can use the rules' priorities to achieve your goal: create one rule to cancel all requests and another rule, with higher priority, to ignore the first rule if the host is google.com.


Q: How to list out all the api in an Django application? I have an Django application which is around 4 years old.
I want list out all the api in order to remove all inactive api's from the codebase.
Is there any way to figure out all the API?
The application is based on Djnago. We are using javascript for the frontend part.