text:
Q: MySQL query wrong COUNT I'm developing an app. I have to do a query where I see the rooms where I'm guest or admin. That's easy. The problem is that I want to get, at the same time, the number of players inside the same room.
SELECT rooms.id, rooms.name, rooms.buyin, rooms.administrator, rooms.creation_date,
       rooms.max_players, rooms.min_players, count(room_players.room)
FROM rooms, room_players
WHERE administrator = 1 and room_players.room = rooms.id

I have a table with the rooms and the other (room_players) that is a match between users and rooms. If i delete the count(room_players.room) and and room_players.room = rooms.id I have the rooms that I'm admin. But I need the number of players inside the same room too.

A: Your query needs a group by.  With the COUNT() in the select, it becomes an aggregation query that returns one row -- a summary of all the rows in the table.
SELECT r.id, r.name, r.buyin, r.administrator, r.creation_date,
       r.max_players, r.min_players, count(rp.room)
FROM rooms r join
     room_players rp
     ON rp.room = r.id
WHERE administrator = 1
GROUP BY r.id;

I also fixed the join syntax to be an explicit join and added table aliases to make the query more readable.
EDIT:
I suspect the query you want is something like:
SELECT r.id, r.name, r.buyin, r.administrator, r.creation_date,
       r.max_players, r.min_players, count(rp.room)
FROM rooms r join
     room_players rp
     ON rp.room = r.id
WHERE administrator <> 1
GROUP BY r.id
HAVING sum(user = 1) > 0;

A: How about subtracting the # of admin from the total users?


text:
Q: Differential equation: mixing salt into water problem where there is also leakage. Is my differential equation correct, and how to solve?
Initially, a tank contains $50$ litres of water and the tank water contains no
salt. Salt is added to the water at time $t=0,$ at a constant rate
of $5$ grams per minute. The salt does not change the volume of the
water in the tank. The water in the tank is stirred constantly, so
that the concentration of salt throughout the tank is uniform. Furthermore,
the saltwater solution leaks out the tank a constant rate of $100$ml per minute. What is
the concentration of salt in the tank after $4$ hours?

My attempt:
Let $t$ be time in minutes, let $V(t)$ be the volume of water at time $t$, and let $m(t)$ be the mass of salt dissolved in the water in the tank at time $t$.
Then, changing units of volume from litres into metres cubed, $V(t) = (0.05 - 0.0001t) m^3.$
Now, in order to find the rate of mass of salt leaving the tank with respect to time, we first should find the concentration of salt in the tank water.
Concentration of salt in tank water = $\left(\frac{m(t)}{V(t)}\right)\ = \left(\frac{m(t)}{0.05 - 0.0001t}\right)\ g/m^3.\ $ Hence we need only need to find $\ m(240)\ $ and then the answer to the question is just $\left(\frac{m(240)}{0.05 - 0.0001\times 240}\right)\ g/m^3. $
Now I believe that the rate at which the mass of the salt leaks out the tank with respect to time is (concentration of salt in tank water in $g/m^3$) $\times$ (the rate at which water leaks out the tank in $m^3$/second), although I am not certain of this.
On the basis that this is all correct so far, the mass of salt in the water in the tank should satisfy the differential equation:
$$\frac{dm}{dt} = 5 - 0.0001 \times \left(\frac{m(t)}{0.05 - 0.0001t}\right),$$
or to tidy up the final term,
$$\frac{dm}{dt} = 5 - \frac{m(t)}{500 - t}.$$
I am not sure how to solve such an equation. Wolfram Alpha says that the general solution is:
$$m(t) = c(t-500) + 5(t-500)\log(t-500).$$
However, this doesn't allow for the initial condition $m(0) = 0$ to be satisfied, so something has gone wrong here. Perhaps $\log(t-500)$ should be $\log\lvert t-500 \rvert$ ? Or Is it the differential equation itself wrong? I suspect so, in which case, can someone give me a hint as to how to figure out what the differential equation should be ?
I am looking for pointers in the right direction, rather than a complete solution to the problem.

A: At first, in order to simplify things a bit, we get rid of grams, minutes and litres. So the mass of salt in the saltwater $m(t)$ is in grams, the volume of saltwater in litres and the time in minutes.
Clearly, the volume of the salt water is
$$
V(t)=50-\frac{t}{10}
$$
Equation for $m(t)$:
The amount of salt in the saltwater increases in time $\Delta t$ by $5 \Delta t$ and decreases by
$$
\frac{.1}{V(t)} m(t)\Delta t=\frac{1}{500-t} m(t)\Delta t,
$$ thus
$$
m(t+\Delta t)-m(t)=5\Delta t-\frac{m(t)\,\Delta t}{500-t},
$$
and hence the sought for ODE is
$$
m'=5-\frac{m}{500-t}
$$
with initial value $m(0)=0$. Solving the IVP we obtain
$$
\frac{m'}{500-t}+\frac{m}{(500-t)^2}=\frac{5}{500-t}
$$
or
$$
\left(\frac{m}{500-t}\right)'=\frac{5}{500-t}
$$
and integrating in the interval $[0,t]$ we obtain
$$
\frac{m(t)}{500-t}=5\log\left(\frac{500}{500-t}\right),
$$
and hence
$$
m(t)=5(500-t)\log\left(\frac{500}{500-t}\right),
$$
and consequently
the concentration of salt in the saltwater will be
$$
c(t)=\frac{5(500-t)\log\left(\frac{500}{500-t}\right)}{50-\frac{t}{10}}=50\log\left(\frac{500}{500-t}\right) \quad\quad\text{[grams/litre]}.
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Duda sobre mi javascript enlazado con html Buenas a todos,
Estoy intentando hacer un menú el cual al clickar la etiqueta "label" cambie el src de la imagen por otro a modo de "hacer check", me explico:
Mi intención es que al hacer click se me ilumine el icono, y al volver a clickar el icono, se me ponga mas grisáceo (tengo dichos iconos en imagenes las dos versiones) y solo consigo que se ilumine pero no vuelve al estado anterior.

function Cambio(){
    var id = document.getElementById().getAttribute('id');

    switch(id){
    case id == "imgJuegos":

    if (document.getElementById('imgJuegos').src == 'img/juegos.png'){
    document.getElementById('imgJuegos').src ='img/bjuegos.png';
      }

    if (document.getElementById('imgJuegos').src == 'img/bjuegos.png'){
    document.getElementById('imgJuegos').src ='img/juegos.png';
      }
    }

<input type="checkbox" name="ks-radio" value="Books" >

A: Juega con las clases.
En mi caso si es si, cambio a no y le modifico el src.
Si es no cambio a si y lo mismo, modifico el src.
Recuerda borrar la clase antes de añadir otra, o tendras las dos.

$("#imagen").click(function(){
    $(this).toggleClass( "no" );
    $(".si").attr("src","http://www.i2clipart.com/cliparts/9/3/a/f/clipart-green-tick-93af.png");
    $(".no").attr("src","http://www.i2clipart.com/cliparts/8/9/e/0/clipart-red-cross-89e0.png");
});

A: Pues, ahí te hago un efecto con un div, tiene comentarios de lo que voy haciendo en el mismo código para que lo entiendas,ya que veo que te gustan los efectos, usando solo Javacript

/* Imágenes */
var imagenes = {
  imagen1: "https://vignette3.wikia.nocookie.net/universosteven/images/4/4b/Circular_Quartz_Fusion_Gem-0.png/revision/latest?cb=20160815020913&path-prefix=es",
  imagen2: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRwg3PByXSW9HXmU8u8wwt_uNS5gYsuvuOvXrnyta8OqGo39N7O"
};
/* Elementos necesarios */

/* Div */ var div = document.getElementById("cambiame");
/* Elemento IMG */ var mg = document.getElementById("imgg");

/* Evento al pasar mouse encima */
div.addEventListener("mouseover",cambiar); /* Al pasar el mouse por encima ejecuta la función cambiar */
div.addEventListener("mouseleave",original) /* Al sacar el mouse de encima ejecuta la función original */
function cambiar(){
  mg.src = imagenes.imagen1;
  mg.style.boxShadow = "0px 0px 40px 6px yellow"; // Color
  mg.style.transform = "scale(1.2)"; // Efecto agrandar
  mg.style.transition = "all 2s"; // Cuanto demorará en agrandar
}
function original(){
  mg.src = imagenes.imagen2; // Esta imagén es la original y al sacar el mouse de encima del div, vuelve el fondo a esta imágen.
  mg.style.boxShadow = "0px 0px 0px 0px dimgray"; // Saco color
  mg.style.transform = "scale(1)"; // Volver tamaño original
  mg.style.transition = "all 2s"; // Cuanto demorará en volver al tamaño
}
#cambiame{
  width:300px;
  height:300px;
  border-radius:150px;
  position:absolute;
  top:20%;
  left:20%;
  background-color:dimgray;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>


text:
Q: Read large number of .asc-files, delete rows and save as raster in R I need to read a large number of .asc-files, delete rows and transform them to a raster-stack by stack(). The source of the zip-packed data is here: ftp://ftp.dwd.de/pub/CDC/grids_germany/monthly/radiation_global/
I've already unziped the files. But now I wrote this code that's really slow, my computer can't accomplished it:
files <- list.files("mydirectory", pattern="\\.asc$",
                    full.names=TRUE, recursive=TRUE)
i <- lapply(files, readLines) #read data
i <- lapply(i, function(x){x[-(1:28)]}) #delete rows
i <- lapply(i, function(x){gsub('-999', ' NA ', x, fixed = TRUE)}) #convert '-999' to NA
i <- lapply(i, function(x){scan(textConnection(x), what = double(), n = 866*654)}) #convert to numeric
i <- lapply(i, function(x){matrix(x, nrow = 866, ncol = 654, byrow = TRUE)}) #convert to matrix
r <- lapply(i, function(x){raster(x)}) #rasterize data
st <- stack(r) #convert to stack-raster

I wonder if there is a better way to convert this data to raster-files. Other .asc files have got only 6 lines as an header like here: ftp://ftp.dwd.de/pub/CDC/grids_germany/monthly/precipitation/01_Jan/ . I read that data by a much simpler function which use only the stack()-function:
loadRaster <- function(directory, output, clipping){
  files <- list.files(path=directory, pattern="\\.asc$",
                     full.names=TRUE, recursive=TRUE)
  stc <- stack(files)
  crs(stc) <- gk3
  stcC <- crop(stc, extent(clipping))
  writeRaster(stcC, filename=output)
}
#You can ignore the code below "stc <-stack(files)"

A: Finally I got it by using textConnection() stepwise (opening and closing again), because – and there was maybe the cause for slowness – there is a limit for opened connections.
files <- list.files(path="mydirectory", pattern="\\.asc$",
                    full.names=TRUE, recursive=TRUE)
i <- lapply(files, readLines)
i <- lapply(i, function(x){x[-(1:28)]})
i <- lapply(i, function(x){gsub('-999', ' NA ', x, fixed = TRUE)})
names(i) <- substr(files, 92,97)
i1 <- lapply(i[1:100], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i2 <- lapply(i[101:200], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i3 <- lapply(i[201:300], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i4 <- lapply(i[301:length(i)], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i <- c(i1, i2, i3, i4)
m <- lapply(i, function(x){matrix(x, nrow = 866, ncol = 654, byrow = TRUE)})
r <- lapply(m, function(x){raster(x)})
stc <- stack(r)


text:
Q: 403 Forbidden - PortalSiteMapProvider was unable to fetch current node We have two development machines and we have a web application in the same port in both machines. We are using FBA and Windows authentication in our application with a custom login page located in "~/_layouts/Pages/Login.aspx", both machines have the same custom login page. The page is made in VS and is deployed with another features.
But here's the deal, in one of the machines the browser gets a 403 Forbidden when it tries to open the page, in the other machine it works alright and we can log both with FBA and Windows.
We have checked all the permissions for the Network Service (App Pool account) and it has the same permissions in both machines, for both "Policy for Web Application" and Content DB (db_owner). We have checked the web.config files for CA, STS and Site and they are identical in both machines. And if we change to the default login page, it works alright.
So we have no clue why it works in one machine and it doesn't work in the other.
Inspecting the Log File it shows the following error:

PortalSiteMapProvider was unable to fetch current node, request URL:
  /_layouts/Pages/Login.aspx, message: Access is denied. (Exception from
  HRESULT: 0x80070005 (E_ACCESSDENIED)), stack trace:    at
  Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception
  ex)     at Microsoft.SharePoint.Library.SPRequest.OpenWeb(String
  bstrUrl, String& pbstrServerRelativeUrl, String& pbstrTitle, String&
  pbstrDescription, String& pbstrTitleResourceId, String&
  pbstrDescriptionResourceId, Guid& pguidID, String&
  pbstrRequestAccessEmail, UInt32& pwebVersion, Guid& pguidScopeId,
  UInt32& pnAuthorID, UInt32& pnLanguage, UInt32& pnLocale, UInt16&
  pnTimeZone, Boolean& bTime24, Int16& pnCollation, UInt32&
  pnCollationLCID, Int16& pnCalendarType, Int16& pnAdjustHijriDays,
  Int16& pnAltCalendarType, Boolean& pbShowWeeks, Int16&
  pnFirstWeekOfYear, UInt32& pnFirstDayOfWeek, Int16& pnWorkDays, Int16&
  pnWorkDayStartHour, Int16& pnWorkDayEndHour, Int16& pnMeetingCount,
  Int32& plFlags, Boolean& bConnectedToPortal, String& pbstrPortalUrl,
  String& pbstrPortalName, Int32& plWebTemplateId, Int16&
  pnProvisionConfig, String& pbstrDefaultTheme, String&
  pbstrDefaultThemeCSSUrl, String& pbstrThemedCssFolderUrl, String&
  pbstrAlternateCSSUrl, String& pbstrCustomizedCssFileList, String&
  pbstrCustomJSUrl, String& pbstrAlternateHeaderUrl, String&
  pbstrMasterUrl, String& pbstrCustomMasterUrl, String&
  pbstrSiteLogoUrl, String& pbstrSiteLogoDescription, Object& pvarUser,
  Boolean& pvarIsAuditor, UInt64& ppermMask, Boolean& bUserIsSiteAdmin,
  Boolean& bHasUniquePerm, Guid& pguidUserInfoListID, Guid&
  pguidUniqueNavParent, Int32& plSiteFlags, DateTime&
  pdtLastContentChange, DateTime& pdtLastSecurityChange, String&
  pbstrWelcomePage, Boolean& pbOverwriteMUICultures, Boolean&
  pbMUIEnabled, String& pbstrAlternateMUICultures, Int32& puiVersion,
  Int16& pnClientTag)     at Microsoft.SharePoint.SPWeb.InitWeb()     at
  Microsoft.SharePoint.SPWeb.get_TitleResource()     at
  Microsoft.SharePoint.Publishing.CachedArea.CreateCachedArea(PublishingWeb
  area, CachedObjectFactory factory, String parentId)     at
  Microsoft.SharePoint.Publishing.CachedObjectFactory.CreateObject(PublishingWeb
  area, String parentUrl)     at
  Microsoft.SharePoint.Publishing.Navigation.PortalSiteMapProvider.get_CurrentNode()

Can someone help us?
Thanks in advance.

A: If you have a custom masterpage in which you have inserted a SiteMapPath control, this control will fail as files located in the /_layouts/ folder is not a part of SharePoint, thus the SiteMapPath cannot index it and therefor it fails to find a matching item in it's data source causing it to throw this error.


text:
Q: Show identity of subgroup is same as identity of group Let $H$ be a subgroup of $G$. Let $1_H$ and $1_G$ be the identities of $H$ and $G$, respectively. Show that $1_H=1_G$.
My attempt is: since we know that the identity of a group is unique, and hence $1_H=1_G$.
Is my proof correct?

A: Knowing that the identity of a group is unique is not sufficient, since being an identity of $H$ does not directly imply being an identity of $G$. Also, previous answers have overlooked how the cancellation law depends on the identity element to work. For instance, by $1_H^{-1}$ do we mean an element from $G$ such that $1_H^{-1}1_H=1_G$? Or an element from $H$ such that $1_H^{-1}1_H=1_H$?
Let $1_H^{-1}$ be an element from $G$ such that $1_H^{-1}1_H=1_G$, for then $1_H=1_G1_H=1_H^{-1}1_H1_H=1_H^{-1}1_H=1_G$, which is what we wanted to show. (We only used the operation of $G$. The first equality follows from $1_G$ being the identity of $G$; the third equality follows from $1_H$ being the identity of $H$.)

A: Hint:
Start with $1_{H}^2 = 1_{H}$.

A: The identity of $H$ is an element of $G$ satisfying $x^2 = x$, and the only such element can be $1_G$.

A: Working in $G$, we have $1_H1_H=1_H=1_H1_G$. The first equality follows from the fact that $1_H$ is the identity of $H$ and $H$ inherits its operation from $G$. The second follows from the fact that $1_G$ is the identity of $G$. Now premultiply by $1_H^{-1}$ to obtain the result.

A: Let $h_1, h_2 \in H$ where $h_2$ is the inverse of $h_1$. Note that this is allowed since $H$ itself is a group. Then $h_1h_2 = 1_H$, but $h_1, h_2$ are both elements in $G$ as well, so $h_1h_2 = 1_G$. Therefore, $1_H = 1_G$.

A: I thought I would post about something related that might interest the readers.  Let $\Bbb{Z}/n$ be a ring and take its multiplicative monoid $M$, not its unit group.
Then there are subsemigroups of $M$ that don't share $M$'s identity, but are groups with the same law as in $M$:
In $\Bbb{Z}/15$, $3$ is not a unit, however it's powers $3^k, k \geq 1$ form a group:
$$
3,3^2,3^3=12, 3^4 = 6, 3^5=3, \text{(repeat)}
$$
The group's identity is $6$!  We have $9\cdot 6 = 9$, etc.


text:
Q: I can edit Meta privilege wikis even though I don't have 20K rep I was looking through the privilege wiki for trusted users, and read at the bottom:

Meta Stack Overflow Specific: Along with the tag-wiki edit privilege, you also get the privilege to edit the Privileges entries.

I noticed something odd, though: I have the "edit wiki" link.

When I click it, it takes me to the wiki edit page.

After being asked to test the edit, I performed this edit (which has now been rolled back) without review.

A: In this case the Wiki entry appears to be wrong.
On MSO (and MSO alone), privilege wiki pages are editable by +1000 rep users.
Since these are pages that are wiki and have revisions, we can always rollback/correct them.
When we do roll out the updates to the rest of the network, we do check them...


text:
Q: Embedded systems development folder structure I'm starting a big project to run on a PIC32, and like every big project, code organization it's very important. Likewise, folder structure too.
In desktop software development I use my own folder structure (very similar to Maven), but like every applications we make, desktop and embedded implementations will have differences.
So, in your embedded systems project, what's your folder structure? Is there any "maven like standard" to embedded systems?

A: This is just "my folder structure" and by no means ultimate, but the project has a couple years, the product is already deployed and upgrades still actively developed - and I found the structure quite comfortable to use.
as separate projects:

*

*Firmware (main, monolithic app for doing The Thing)

*WWW (control over HTTP)

*misc tools

*Lang (translations of all strings)

*Common (a set of structures, defines and the likes included and shared by all).

Then, within Firmware:

*

*cpp (sources)

*

*Appmanager (central point binding them all)

*Events (event pump, task pump, also threading)

*gfx (built-in screen GUI)

*Net (TCP/IP based communication)

*Interface (all other I/O - rs232, CAN, touchscreen, LCD screen, SPI etc)

*Log

*Utils (utility classes)

*subdirectories for all major modules of the algorithm. Config file access, input processing, computation, overseer, watchdog,

*data (config files)

*[root directory] (short, trivial main.cpp and global_include.h which is included from every file - major configuration #defines.)


text:
Q: I cannot get my JavaScript REST API to return data I know there are many similar questions about this issue and most of them are already answered, but I am a beginner on this.
This code is a code from a YouTube tutorial about the basic of making REST API, as follows:
const app = require('express')();
const PORT = 8095;

app.get('/tshirt', (req, res) => {
    res.status(200).send({
        tshirt: "red white tshirt",
        size: "large"
    })
});

I tried to access get tshirt both from browser and Insomnia and it says 'could not get /tshirt', what might be wrong?

A: You also need to start the actual server.
const express = require('express');
const app = express();
const port = 8095;

app.get('/tshirt', (req, res) => {
   res.status(200).send({
        tshirt: "red white tshirt",
        size: "large"
    })
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

As per https://expressjs.com/en/starter/hello-world.html


text:
Q: AWS Lambda - different dead letter queue based on Lambda alias I've two SQS queues one for test stage and one for prod stage and a single Lambda function with test and prod aliases, each alias is triggered by a SQS event of the corresponding queue.
I was wondering if there's a way to specifcy a DLQ for each alias (I'm using a SAM template to define the Lambda function) of the Lambda or I would like to understand which is the best practice to handle such requirement.

A: It's straightforward to add your DLQs - and the test-prod alias setup you have does not complicate things at all.
Add a RedrivePolicy to your two Queue definitions.  Here's the prod half the code:
  # template.yaml

  # new: define a new queue to be the prod DLQ
  MyProdDLQ:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: this-queue-captures-errors-sent-from-the-prod-queue

  MyProdQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: this-queue-feeds-the-prod-alias-lambda
      VisibilityTimeout: 60
    # new: assign the DLQ
    RedrivePolicy:
        deadLetterTargetArn: !GetAtt MyProdDLQ.Arn
        maxReceiveCount: 5

Note:  You might be tempted to define the DLQ on the lambda function itself.  Confusingly, the DLQ on the lambda function is for asynchronous (event-driven) invocations, not SQS sources.  The docs warn about this, but it is easy to miss.


text:
Q: Mechanize how to add to a select list? I just started experimenting with submitting webforms through mechanize. On this webpage there is a list of items to select from, MASTER_MODS. These can be selected in either MODS using a butten add_MODS or in IT_MODS using a button add_IT_MODS (see figure at the bottom). In the form it looks like this (code for form at bottom):
 <<SNIP>>
<SelectControl(MODS=[*--- none selected ---])>
<IgnoreControl(add_MODS=<None>)>
<SelectControl(MASTER_MODS=[])>
<SelectControl(IT_MODS=[*--- none selected ---])>
<IgnoreControl(remove_IT_MODS=<None>)>
<IgnoreControl(add_IT_MODS=<None>)>
<<SNIP>>

So I want to add to <SelectControl(MODS=[*--- none selected ---])> and <SelectControl(IT_MODS=[*--- none selected ---])>. However, when I try to add an item directly with
br.form[ 'MODS'] = ['Acetyl (N-term)']

I get mechanize._form.ItemNotFoundError: insufficient items with name 'Acetyl (N-term)'
And when I try
br.form[ 'add_MODS'] = 'Acetyl (N-term)'

I get ValueError: control 'add_MODS' is ignored, hence read-only.
How can I add items to MODS and IT_MODS?

Figure and code

Code:
from mechanize import Browser, _http
br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = "http://www.matrixscience.com/cgi/search_form.pl?FORMVER=2&SEARCH=MIS"
br.select_form( 'mainSearch' )
br.open(url)
print br.form

A: Try this? Explanation in the comments.
from mechanize import Browser, Item
br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent',
                  'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)'
                  ' Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = 'http://www.matrixscience.com'\
      '/cgi/search_form.pl?FORMVER=2&SEARCH=MIS'
br.open(url)
br.select_form('mainSearch')

# get the actual control object instead of its contents
mods = br.find_control('MODS')
# add an item
item = Item(mods, {"contents": "Acetyl (N-term)", "value": "Acetyl (N-term)"})
# select it. if you don't, it doesn't appear in the output
# this is probably why MASTER_MODS appears empty
item.selected = True
print br['MODS']
# outputs: ['Acetyl (N-term)']

Assuming this works, I got it from the comments in the docs:

To add items to a list container, instantiate an Item with its control
  and attributes:
  Note that you are responsible for getting the attributes correct here,
  and these are not quite identical to the original HTML, due to
  defaulting rules and a few special attributes (e.g. Items that represent
  OPTIONs have a special "contents" key in their .attrs dict).  In future
  there will be an explicitly supported way of using the parsing logic to
  add items and controls from HTML strings without knowing these details.
  mechanize.Item(cheeses, {"contents": "mascarpone", "value": "mascarpone"})


text:
Q: how to combine drawRect: and ImageCache to speed up table view scrolling I need to implement my custom drawRect: method in my custom table cell in order to speed up tableview scrolling, however, there's an image the app should download from web, so I want to add image cache to my app. The origin implementation of my app is using SDWebImage library, which implement an imageView which offer download image method. If I want to add image in drawRect:, how to implement downloading image from web and cache them?

A: You need to use SDWebImage to download and cache the image. Then in delegate/completion block of that download operation, you need to assign the image to your a property and call setNeedsDisplay. setNeedsDisplay will cause your view to be redrawn. This should be called on mainQueue.
 [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:theArticle.imageURL] options:SDWebImageLowPriority progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
       dispatch_async(bakground_queue, ^{
       //Here you probably want to dispatch_async to a background queue to do all the image resizing first before drawing on main queue

           dispatch_async(dispatch_get_main_queue(), ^{
               weakSelf.thumbnailImage = image;
               [weakSelf setNeedsDisplay];
           });
       });
   }];

In your drawRect, you need to draw from that property. For e.g
[self.image drawInRect:rect]

This is just basic principle of how this can be achieved. Probably needs more work to really optimize it (e.g cancel the downloading operation when not needed)
Edited:
SDWebImageManager has a delegate method to resize/transform image before storing it to disk cache. You might want to use that method instead of dispatch_async to background queue like above.


text:
Q: Selecionar registo da base de dados para variável O código em baixo visa selecionar um registo da base de dados e guardar o mesmo numa variável para posterior utilização dos dados:
#!/bin/bash

dbName='basedados'
dbUser='utilizador'
dbPass='password'

row=$(echo "select file_id, file from catalogue__pdf_file WHERE is_converted='no' ORDER BY file_id DESC LIMIT 0,1" | mysql $dbName -u $dbUser --password=$dbPass)

arr=($row)

O código em cima seleciona um registo e passa o mesmo para a variável row que fica da seguinte forma:
echo $row
# Saída: file_id file 29 ficheiro.jpg

Depois, ao passar o valor da variável row para uma matriz via arr=($row):
echo ${arr[3]}
# Saída: ficheiro.jpg

Pergunta
Para o que foi descrito, o processo está a decorrer de forma eficiente ou o mesmo pode ser simplificado?

A: Para o objectivo que descreves está correcto. Podes no entanto fazer uma pequena alteração, removendo a utilização do echo, caso estejas a usar uma versão suficientemente actual da shell bash que suporte "here strings"
row=$(mysql $dbName -u $dbUser --password=$dbPass <<< "select file_id, file from catalogue__pdf_file WHERE is_converted='no' ORDER BY file_id DESC LIMIT 0,1")

Deixo apenas uma sugestão no que diz respeito aos dados dbName, dbUtilizador, dbPass. Normalmente o que eu faço é guardar esta informação num ficheiro de configuração, ao invés de incluir esta informação no script onde executas o comando. Isto pode ser útil caso, no futuro, tenhas vários scripts que usam as mesmas credenciais e necessites de fazer uma alteração. Desta forma apenas alteras o teu ficheiro de configuração e não um conjunto de scripts individualmente.
Eu guardo os dados no ficheiro ~/.my.cnf com a estrutura.
[client]
user = 'utilizador'
password = 'password'
database= 'basedados'

Desta forma o teu comando ficaria:
row=$(mysql <<< "select file_id, file from catalogue__pdf_file WHERE is_converted='no' ORDER BY file_id DESC LIMIT 0,1")

Caso o script seja usado por mais que um utilizador, podes centralizar esta informação num directório comum e que os vários utilizadores tenham accesso e usar a flag --defaults-file=/path1/path2/ficheiro_configuracao no teu script para indicar a sua localização.
O teu comando ficaria:
row=$(mysql --defaults-file=/path1/path2/ficheiro_configuracao <<< "select file_id, file from catalogue__pdf_file WHERE is_converted='no' ORDER BY file_id DESC LIMIT 0,1")


text:
Q: JMeter - contribute new function(s) to JMeter I want to add more functions to JMeter, for example encryption __sha512 which will encrypt string using SHA 512.
What's the process of contribute new function(s) to JMeter? can I add it as an enhancement to JMeter and create a patch or should it be added as a plugin manager?
In plugin manager there's already Function project.

A: JMeter plugins project is a 3rd party project with no relation to JMeter.
Users will have to install plugin manager and install then function plugin.
If you contribute to Core JMeter it will be available OOTB.
So if you want to contribute to JMeter:

*

*open an enhancement request

*attach you patch or point to your PR in github
See:

*

*http://jmeter.apache.org/building.html
JMeter functions are located here:

*

*https://github.com/apache/jmeter/tree/trunk/src/functions/org/apache/jmeter/functions
JUnit Tests should be provided as well:

*

*https://github.com/apache/jmeter/tree/trunk/test/src/org/apache/jmeter/functions


text:
Q: Cannot read property 'name' of undefined serverless esbuild Recently, I was going to change webpack with esbuild in aws serverless project. With webpack, everything was working fine. But, with esbuild, the following error is being shown:
× Unhandled exception in handler 'getNotification'.
× Cannot read property 'name' of undefined
× TypeError: Cannot read property 'name' of undefined
at ...\.esbuild\.build\src\functions\api\index.js:21033:22
      at __decorateClass (...\.esbuild\.build\src\functions\api\index.js:32:24)
      at Object.<anonymous> (...\.esbuild\.build\src\functions\api\index.js:703945:1)
      at Module._compile (internal/modules/cjs/loader.js:1085:14)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
      at Module.load (internal/modules/cjs/loader.js:950:32)
      at Function.Module._load (internal/modules/cjs/loader.js:790:12)
      at Module.require (internal/modules/cjs/loader.js:974:19)
      at require (internal/modules/cjs/helpers.js:101:18)
      at _tryRequireFile (...\node_modules\serverless-offline\src\lambda\handler-runner\in-process-runner\aws-lambda-ric\UserFunction.js:209:35)

Serverless.yaml:
plugins:
  - serverless-dotenv-plugin
  - serverless-offline-ssm
  - serverless-layers
  - serverless-scriptable-plugin
  - serverless-esbuild
  - serverless-offline
   ...

esbuild:
    bundle: true
    minify: false

My package versions:

*

*"serverless": "^3.22.0",

*"serverless-esbuild": "^1.32.8",

*"serverless-offline": "^9.3.1",

*"esbuild": "^0.15.7",


text:
Q: X11 forwarding request failed on channel 0 $ ssh -Xvv remote_host outputs
....
debug1: channel 0: new [client-session]
debug2: channel 0: send open
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: exec
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Remote: /home/user/.ssh/authorized_keys:8: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding
debug1: Remote: /home/user/.ssh/authorized_keys:8: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding
debug2: channel_input_open_confirmation: channel 0: callback start
debug2: x11_get_proto: /usr/bin/xauth  list unix:16.0 2>/dev/null
debug1: Requesting X11 forwarding with authentication spoofing.
debug2: channel 0: request x11-req confirm 1
debug2: fd 3 setting TCP_NODELAY
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug2: channel 0: request shell confirm 1
debug2: channel_input_open_confirmation: channel 0: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 100 id 0
X11 forwarding request failed on channel 0
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0

Tried also -Y. Doesn't work.
I confirmed that X11 forwarding is allowed on the server side. $grep X11 /etc/ssh/sshd_config gave
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes

I have searched other posts related to X11 forwarding request failed on channel 0 and found no help info.

A: I had a similar issue on Devuan (fork of Debian without systemd).
I found a solution on an Arch Wiki.
Edit /etc/ssh/sshd_config (on the server side) and set:
AddressFamily inet

The default is AddressFamily any but this does not seem to supply an inet (ipv4) socket.
On my system I noted in /var/log/auth.log:
sshd[9184]: error: Failed to allocate internet-domain X11 display socket.

After the above change to sshd_config and service ssh restart the X11 forwarding worked for me.


text:
Q: removing duplicated chars from string in C My program has to look for duplicated chars (that comes one after another) and remove them. So my program does work, but in case I put "PLLNSIS", I get "PLNSISS". I overwrite the char that I find out is duplicated, but in the end, i recieve a copy of the last char.
 void main()
    {
        int length;
        char *myString;
        printf("Enter the length of the string \n");
        scanf("%d", &length);
        myString = (char*)malloc((length+1) * sizeof(char));
        assert(myString);
        printf("Now enter the string: (max %d letters) \n", length);
        fseek(stdin, 0, SEEK_END); //flushing the buffer
        fgets(myString, length+1, stdin); //calling the input function
        no_Straight_Letters(myString);
        free(myString);
    }

       void no_Straight_Letters(char *myString)
        {
            int i, j = 0, length = strlen(myString);
            for (i = 1; i < length-1; i++)
            {
                if (myString[j] == myString[i])
                {
                    myString[j] = myString[i];
                    myString[i] = '\0';
                }
                    else myString[++j] = myString[i];
            }
            myString[length] = '\0'; //last char of the string
            printf("And the new string is.... -->  ");
            puts(myString);
        }

I found out the cause but when I fix it, I get nothing on the screen.

A: The problem is
 myString[length] = '\0';

It will be
 myString[++j] = '\0';

This works because at the end of the looping j points to the last valid character. Then if you increase it and put \0 there - it will make the string.
You can emulate the behavior of having \n with this small addition (which is not likely to be needed).
myString[++j]='\n';
myString[++j]=0;

Also as a small modification you can remove the redundant assignment in your code. it's unnecessary.
if (myString[j] == myString[i])
{
    myString[i] = '\0';
}

A: There are two issues:
First, you miss the last character; you might not have noticed it, because the last character of your fgets-input is probably a newline which you do not see. So you'd iterate like for (i = 1; i <= length-1; i++).
Second, you cut off the string at length, which is larger then the final string; use myString[j+1] = '\0' instead.
Minor issue: The code in your if is useless, you can omit it.
void no_Straight_Letters(char *myString)
{
    int i, j = 0, length = strlen(myString);
    for (i = 1; i <= length-1; i++)
    {
        if (myString[j] != myString[i])
           myString[++j] = myString[i];
    }
    myString[j+1] = '\0'; //last char of the string
    printf("And the new string is.... -->  '%s'",myString);
}

int main()
{
    char myString[] = "PLLNSISSSHERBERTTTA";
    no_Straight_Letters(myString);
}


text:
Q: Octave - find roots and count them I have the equation:
sin(x) = exp(a)+4
x = 1:.1:20
a = 0.02
I know i can use roots or fzero functions inside a loop to determine the roots.
How to use one or both of the above functions to find all the roots and them count them all in sin(x) = exp(a)-4
I wrote this code, it finds the zeros with fzero and marks them in plot. But how to modify to sin(x) = exp(a)-4 so finds all roots and then counts the number of finded roots and output the results.
x = 0:.1:20;
f = @(x) sin(x) + 4;
c = zeros(length(x),1);
for i=0:length(x)
    c = fzero(f,i);
    axis([0, 20, -2, 1])
    plot(x, f(x));
    title('Zeros de f(x) = sin(x) + 4');
    hold on
    plot(c, f(c),'-xr')
    hold on
end

EDIT
I used fzero inside a loop with the unique function to output, but it never outputs just the unique values. I outputs all duplicates. Anyone know why?
My new code:
h = @(x) cos(x);
g = @(x) exp(a*x)-1;

        f = @(x) h(x) - g(x);
        v = zeros(length(x),1);
        for i=0:length(x)
            v = fzero(f,i);
            [s] = unique(v)
        end

A: In short, you can rearrange any equation problem to a root-finding problem by subtraction:
f = @(x) (sin(x) - (exp(a) + 4));

roots would operate on polynomials only. fzero is an iterative algorithm that may converge to one root close to the initial guess i.
Afterwards, you can use the unique function to extract the distinct solutions.


text:
Q: How can I scrape data that is locked by a button? I'm trying to fetch some info from a website, without success.
The problem is that the data is shown only after clicking a certain button.

The info that I want is located in this tag:

    Ver telefone

It may have something to do with this line:
<form action="/noindex/doctor-phone" id="frmPhone" method="post"><input name="__RequestVerificationToken" type="hidden" value="3uFb11EKzbTh4TWoqXk025U7jS7QoV5-od7lSgSBzdu616u82jQAHiOTl2aB3q47aRCIg2CjVCjE6R6bUAqDplAOfeM1" /><input id="entityKey" name="entityKey" type="hidden" value="12898671" /><input id="placeType" name="placeType" type="hidden" value="" /><input id="placeKey" name="placeKey" type="hidden" value="" /></form>

But I don't know how to use this __RequestVerificationToken properly.

Do I have to send a request to the server using this info to get the phone info? If so, how?
After I click the button, this is the popup that appears (I'm interested in info1 to info4):

My code:
page = BeautifulSoup(urllib2.urlopen('http://www.doctoralia.com.br/medico/RANDOM_PROFILE'), "html.parser")
hidden_tags = page.find_all("input", type="hidden")

for tag in hidden_tags:
    print tag

Output:
<input name="__RequestVerificationToken" type="hidden" value="gPYstKvmi4xBQsV81ECf5mYe695igvq8E2QqtOgBPqtRybEP74OEbSAe8uDg8dlZCpqib94FIrUoPMnpLTC0tY7kiJE1"/>
<input id="entityKey" name="entityKey" type="hidden" value="14336768"/>
<input id="placeType" name="placeType" type="hidden" value=""/>
<input id="placeKey" name="placeKey" type="hidden" value=""/>

A: As you can see when using Google Chrome's Dev tools in the "Network" tab, it sends a a POST request to http://www.doctoralia.com.br/noindex/doctor-phone. This POST request is protected against CSRF, so it will be very hard to fake this request in order to get the data.
Since BeautifulSoup is an HTML parser. You can't really interact with the webpage. If you really want to get the data. You should use a tool like selenium, which emulates a real browser.
Keep in mind though that the data is not protected just to be bypassed. They probably don't want the data to be scraped, and it might be illegal to do so.

A: It is pretty straightforward using a requests.Session object, you just need to extract the __RequestVerificationToken token from the initial  page and a couple of pieces of form data.  I used the page of full listings to get the numbers and the link to the doctors page, the same logic applies wherever you decide to get the number from:
from bs4 import BeautifulSoup
import requests
from urlparse import urljoin

head = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"}

base = "http://www.doctoralia.com.br/"

with requests.Session() as s:
    r = s.get('http://www.doctoralia.com.br/medicos/especialidade/dermatologistas-1314')
    page = BeautifulSoup(r.content, "html.parser")
    token = page.select_one("input[name=__RequestVerificationToken]"["value"])
    hidden_tags = page.select("article.media.doctor")
    for tag in hidden_tags:
        h3 = tag.select_one("h3")
        key = h3.a["data-track-click"]
        place = tag.select_one("span[data-location]")["data-location"].split("|", 1)[0]

       data = {"__RequestVerificationToken": token,
            "entityKey": key,
            "placeKey": place}
        resp = s.post("http://www.doctoralia.com.br/noindex/doctor-phone", data=data, headers=head)
        soup = BeautifulSoup(resp.content,"html.parser")
        print(urljoin(base,h3.a["href"]))
        print(soup.select_one("li.phone").text.strip())

That gets you all the links and the phone numbers for each doctor, anything you see in the popup when you click the button will be available to parse. The essential form data is the __RequestVerificationToken and the entityKey, the placeKey does not seem to affect the post but no harm including it. The headers are also not essential in this instance but again no harm always a good idea to add a user-agent. You might want to add a sleep between requests so you don't hammer the server if you are making a lot of requests.  Also looking at the robots.txt:
User-agent: *
Disallow: /noindex/
Disallow: /usuarios/
Disallow: /users/
Disallow: /utilisateurs/
Disallow: /utenti/
Disallow: /gebruikers/
Disallow: /nutzer/
Disallow: /medical-center/m/
Disallow: /consultant/m/
Disallow: /centro-medico/m/
Disallow: /medico/m/
Disallow: /centre-medical/m/
Disallow: /medicin/m/
Disallow: /centro-medico/m/
Disallow: /medico/m/
Disallow: /centri-medici/m/
Disallow: /medecin/m/
Disallow: /healthpro/m/
Disallow: /facharzt/m/
Disallow: /sanit�tszentrum/m/
Disallow: /clickfav/
Disallow: /clicktlf/
Disallow: /reservas/
Disallow: /citas/
Disallow: /medisch-centrum/m/
Disallow: /deskundige/m/
Disallow: /arzt/m/
Disallow: /klinik/m/
Disallow: /citas/
Disallow: /turnos/
Disallow: /appuntamenti/
Disallow: /appointments/
Disallow: /consultas/
Disallow: /ws/Schedules.asmx/
Disallow: /RESOURCE NOT FOUND/
Disallow: /RESOURCE+NOT+FOUND/
Disallow: /RESOURCE%20NOT%20FOUND/
Disallow: /entities/

There is no user-agent restriction and what you are scraping is not disallowed


text:
Q: Default body behaviour in a Grails tag I'm trying to implement a tag that must render a default body if none is passed as argument. Here is my first try:
def myDiv = { attrs, body ->
  out << '
'
  if (body) //this approach doesn't work cause body is a closure that is never null
     out << body()
  else
     out << 'default content'
  out << '
'
}

Then we would have 2 simple usage scenarios.
1) <g:myDiv/> Content body NOT present, should render:

   default content

2) <g:myDiv> SPECIFIC content </g:myDiv> Content body present, should render:

   SPECIFIC content

What is the best approach to use in this case?

A: I printed out the class of "body" in the tagLib to find out more about it.
println body.getClass() // outputs: class org.codehaus.groovy.grails.web.pages.GroovyPage$ConstantClosure

this is a GroovyPage.ConstantClosure
When you check for 'body' in your condition it is a closure. If you use a single tag <g:tester/> the body will seem to not exist, and you can use ConstantClosure's asBoolean() and it will return false.
def tester = {attrs, body ->
  println body.asBoolean()  // prints: false
  if (body) {
    println "body"
  } else {
    prinltn "no body"
  }
}
// outputs : "no body"

When I use two tags <g:tester></g:tester> the output was "body" So I tried the following:
def tester = {attrs, body ->
  println "**$body**"      // prints:  **
                           //          **
  println body.asBoolean() // prints:  true
  println body().size()    // prints:  1
}

I am guessing that body contains some return character or white space.
My best solution is to invoke the method body() this returns a String and you can call trim() on it and check it in a condition with groovy truth
def tester = {attrs, body ->
  if (body().trim()) {
    println "body"
  } else {
    println "no body"
  }
}  // outputs : "no body" in all scenarios except when body contains something relevant.


text:
Q: How to implement chrome's "merge tabs and apps" feature in an android application? I want a functionality where new documents open up as separate activities but are accessible on press of a button instead of searching for them in Recents app switcher of Android.
I am able to use documentLaunchMode='always' and FLAG_ACTIVITY_MULTIPLE_TASK flag to show all the launched activities in the Recents switcher.


text:
Q: bash commands to maximize audio volume - especially equivalent to gui slider shown I'm using ffplay to play an audio file in a bash script and I need to maximize volume. I've found 2 independent commands that address some part of a chain affecting the volume:
This gets me about halfway there:
pactl set-sink-volume alsa_output.pci-0000_00_14.2.analog-stereo 200%

Adding options like this
-af "volume=1250"
to the ffplay command string didn't make any perceptible difference.
Nor did
pacmd set-source-volume I 65536
with I being 0, 1, or 2.
I need the equivalent of the 2nd slider in the playback tab in the pavucontrol, just above the arrow in this picture:

Of course it would be nice if there was one command to max out volume and I didn't have to stack them, but maybe that doesn't exist. But surely this slider has a scriptable equivalent.

A: I understand your question to be "how do I set the equivalent of the application stream volume slider in the 'Playback' tab of pavucontrol".
The total volume depends on both the application stream volume and the sink volume, and the latter should in general stay constant at 100% (or whatever value is needed to max out the soundcard amplifiers controlled by ALSA).
Have a look at pacmd list-sink-inputs. That will show all currently playing streams. Use this to find the index of the stream you want to control. A reduced output like from pacmd list-sink-inputs | egrep '(index)|(name)' is easier to read or parse if there are many streams.
Once you find the index, use
pactl set-sink-input-volume index_you_found '100%'

to set the volume to 100%. This also works with pacmd, but only with raw values and not with absolute or relative percentages, so I prefer pactl. (Don't ask me why there are two different tools ...).
Guessing indices won't work. Using set-source-volume won't work, because that sets the volume of the audio inputs.
You can't set the volume of a stream of it's not playing. With the default Pulseaudio setup on most distros, stream volumes will be saved for each application (using the application name), and restored the next time when the application is started. So unless you use different application names, you'll have to set the volume only once (and you can also do that directly in pavucontrol).

A: "I understand your question to be "how do I set the equivalent of the application stream volume slider in the 'Playback' tab of pavucontrol". "
Yes. That's the nub. The rest is context in case the question is based on erroneous assumptions or someone wants to suggest a better way.
"Have a look at pacmd list-sinks-inputs."
"Unknown command" But a little poking around in Snynaptic and I find that's part of pulseaudio-utils which I have, and a little more poking around and I tried this:
pacmd list-sink-inputs
Looked right. Furthermore:
pacmd list-sink-inputs | grep index
just returned one line, so, must BE right.
Then, as instructed:
pactl set-sink-input-volume 1 '100%'
Oh my. That's LOUD.
Interesting that it comes up with a different index every time I start ffplayer, even if it is the only audio stream playing, so I'll have to grep and do a little string manipulation to put that in my script, but that shouldn't be any problem.
Thanks, Dirkt.
BTW, I don't know where I got the impression that the command:
pactl set-sink-volume alsa_output.pci-0000_00_14.2.analog-stereo 200%
maxed out at 200%. It goes higher. Although they tell me it can damage speakers if you push it. I assume the idea is that if you don't set this  over 100% you can safely push
pactl set-sink-input-volume I 'N%'
(which also does not max out at a 100)
as high as you want, which doesn't make a heck of a lot of sense to me, so maybe it isn't true. Anyway, I now have 2 ways to wake the dead and wear out my speakers.


text:
Q: wcf client ignores derived types during deserialization I'm using a standard wsdl (located here) to communicate with a service (OpenXDS). I created a service reference from it, which generated a very large Reference.cs file. There is a type hierarchy in the file like this:
public partial class ExtrinsicObjectType : RegistryObjectType

.
.
.
[System.Xml.Serialization.XmlIncludeAttribute(typeof(ExtrinsicObjectType))]
public partial class RegistryObjectType : IdentifiableType

.
.
.
[System.Xml.Serialization.XmlIncludeAttribute(typeof(RegistryObjectType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(ExtrinsicObjectType))]
public partial class IdentifiableType : object

All three types have the same XmlType:
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0")]

There is a collection in the Response type of IdentifiableType objects:
[System.Xml.Serialization.XmlArrayAttribute(Namespace="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", Order=0)]
[System.Xml.Serialization.XmlArrayItemAttribute("Identifiable", IsNullable=false)]
public IdentifiableType[] RegistryObjectList {

When the service actually responds, it gives a collection of ExtrinsicObject elements:
<rim:RegistryObjectList xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0">
  <ns1:ExtrinsicObject xmlns:ns1="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" ...
  <ns1:ExtrinsicObject xmlns:ns1="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" ...
  <ns1:ExtrinsicObject xmlns:ns1="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" ...
  <ns1:ExtrinsicObject xmlns:ns1="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" ...
  <ns1:ExtrinsicObject xmlns:ns1="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0" ...
</rim:RegistryObjectList>

I see these elements in the trace log and I can get the same answer in SoapUI. But when I get the deserialized response back from the client proxy, the RegistryObjectList is empty. It completely ignores the ExtrinsicObject elements.
I can't change the server, and the client is generated by VS2012. It seems like this should just work and I'm missing some setting or something.
Here's the theories I have so far:

*

*There's some setting on the service reference, and if I checked it and updated the code everything would just work.

*The wsdl I'm using is different than the wsdl they have agreed to.

*I'm going to have to figure out how to manually deserialize the responses.

Any help is appreciated. I've tried to include what I thought was pertinent, but there was a lot of editing since the wsdl, xsd's, and Reference.cs are all fairly large.

A: I just got this working by passing the following XmlAttributeOverrides to the serializer:
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(SubmitObjectsRequest), "RegistryObjectList", new XmlAttributes
{
    XmlArray = new XmlArrayAttribute()
    {
        Namespace = "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0",
        Order = 0
    },
    XmlArrayItems =
    {
        new XmlArrayItemAttribute("ExtrinsicObject", typeof(ExtrinsicObjectType)) { IsNullable = false },
        new XmlArrayItemAttribute("RegistryPackage", typeof(RegistryPackageType)) { IsNullable = false }
    }
});

From what I understand, Reference.cs, as you said, gives this:
[System.Xml.Serialization.XmlArrayAttribute(Namespace="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", Order=0)]
[System.Xml.Serialization.XmlArrayItemAttribute("Identifiable", IsNullable=false)]
public IdentifiableType[] RegistryObjectList {

But since, in the XML, the RegistryObjectList element does not have Identifiable child nodes, but rather ExtrinsicObject and RegistryPackage children, what I really want is for it to look like this:
[System.Xml.Serialization.XmlArrayAttribute(Namespace="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", Order=0)]
[System.Xml.Serialization.XmlArrayItemAttribute("ExtrinsicObject", typeof(ExtrinsicObjectType), IsNullable=false)]
[System.Xml.Serialization.XmlArrayItemAttribute("RegistryPackage", typeof(RegistryPackageType), IsNullable=false)]
public IdentifiableType[] RegistryObjectList {

And including the overrides gets the serializer to ignore the original attributes and treat RegistryObjectList as if had been decorated with the latter.


text:
Q: Can't seem to get my string to iterate in my view I have a string that will have multiple values, person_ids and how many vacation days they have. I want to use this data in my view.
Here is my MyGroupAcc model:
class MyGroupAcc < ActiveRecord::Base

belongs_to :entry

def self.all_people
  where(person_id: User.all.pluck(:person_id))
end

def self.active_people
  all_people.where(is_active: 'Y')
end

def self.active_vacation_data
  active_people.select(:person_id, :accum_accrued, :taken)
end

def total_v_hours
  accum_accrued.to_d - taken.to_d
end

def total_v_days
   total_v_hours / 8
end

Here is my entry controller where my view action will be:
def my_group
  peoples_vacation_information = MyGroupAcc.active_vacation_data.all
  peoples_vacation_information.map do |person|
    @p = "person #{person.person_id} has #{person.total_v_days} vacation days"
  end
  render :my_group
end

And here is my_group view in Haml:
%table.table.table-bordered.trace-table
  %thead
    %tr.trace-table
      %th.ts.jp{:style => 'border: solid black;'} Person ID
      %th.ts.jp{:style => 'border: solid black;'} Total Vacation Days

      %tr.trace-table
      -@p.each do |r|
        %tr.trace-table
          %td.trace-table{:style => 'border: solid black;'}= r

In my view I get this error:
udefined method `each' for "person 22076 has 3.0 vacation days":String

but in my console it get this when running this code
peoples_vacation_information = MyGroupAcc.active_vacation_data.all
peoples_vacation_information.map do |person|
    @p = "person #{person.person_id} has #{person.total_v_days} vacation days"
end

Which spits out this, which is what I would like to see in my view:
["person 16016 has 7.0 vacation days", "person 16256 has 0.0 vacation days", "person 16256 has 18.5 vacation days", "person 17258 has 0.0 vacation days", "person 17258 has 5.0 vacation days", "person 17371 has 0.0 vacation days", "person 17371 has 20.0 vacation days", "person 19551 has 0.0 vacation days", "person 19551 has 26.5 vacation days", "person 20850 has 0.5 vacation days", "person 20850 has 14.0 vacation days", "person 21714 has 0.5 vacation days", "person 21714 has 1.0 vacation days", "person 22076 has 0.0 vacation days", "person 22076 has 3.0 vacation days"]

A: Do this:
def my_group
   @peoples_vacation_information = MyGroupAcc.active_vacation_data.all
end

#app/views/my_group_acc/my_group.html.erb
%table.table.table-bordered.trace-table
    %thead
      %tr.trace-table
        %th.ts.jp{:style => 'border: solid black;'} Person ID
        %th.ts.jp{:style => 'border: solid black;'} Total Vacation Days

        %tr.trace-table
     - @peoples_vacation_information.each do |person|
        %tr.trace-table
          %td.trace-table{:style => 'border: solid black;'}= "person #{person.person_id} has #{person.total_v_days} vacation days"
<% end %>

The problem is you're your @p variable as a string (which rob fixed).
Apart from the syntax problem, it's badly constructed for two reasons - first, you're splitting up a perfectly good collection (which you could just pass to your view), and secondly, you're trying to construct another piece of data only to split it up.
You'll be best setting an @instance_variable in your controller, you can then loop through in your view.

You'll also be best using scopes in your MyGroupAcc model (which can be chained, don't worry):
#app/models/my_group_acc.rb
class MyGroupAcc < ActiveRecord::Base
    belongs_to :entry

    scope :all_people,           -> { where(person_id: User.pluck(:person_id)) }
    scope :active_people,        -> { where is_active: "Y" }
    scope :active_vacation_data, -> { active_people.select(:person_id, :accum_accrued, :taken) }

    def total_v_hours
       accum_accrued.to_d - taken.to_d
    end

    def total_v_days
       total_v_hours / 8
    end
end

A: @p is here just a simple string, not an array or a collection.
you can solve this with this
@p=peoples_vacation_information.map do |person|
  "person #{person.person_id} has #{person.total_v_days} vacation days"
end


text:
Q: iterate api response into html How do I iterate API responses (50 products) into html list ? Results currently displayed automatically without styling. I just need to break all 50 products from results into seperate
* tags.
index.js

sample.html

{productname}

      {producttitle}

            ¥{productprice}

A: Good day,
To accomplish this you will need to inject html code using javascript. If your response is an array of 50 objects, you will need to iterate over every object and inject each object contents into html. To iterate you will need to use the map function.
[].map(value => {})

Please follow this guide on how to inject code into your page using javascript.
More Information
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>JS CreateElement Demo</title>

Hope this helps to guide you in the right direction.


text:
Q: Grep expression with special file names i am a real beginner in csh/tcsh scripting and that's why i need your help. The problem is I have to go through some regular files in directories and find those files, that have their own name in its content. In the following piece of script is cycle in which I am going through paths and using grep to find the file's name in its content.
What is surely correct is $something:q - is array of paths where i have to find files.
The next variable is name in which is only name of current file.
for example: /home/computer/text.txt (paths)
and: text.txt (name)
And my biggest problem is to find names of files in their content. It's quite difficult for me to write correct grep for this, cause the names of files and directories that i am passing through are mad. Here are some of them:
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/!_1
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/dam/$user/:e/'/-r
/home/OS/pocitacove/testovaci_adresar/z/test3/skusime/ taketo/   taketo
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/.a=b
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/@
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/:
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/'ano'

foreach paths ($something:q)
    set name = "$paths:t"
    @ number = (`grep -Ec "$name" "$paths"`)

    if ($number != 0) then
        echo -n "$paths "
        echo $number
    endif

    @ number = 0
end

A: Have you tried with grep -F, it assumes input to be string literals and doesn't worry about escape characters.


text:
Q: LateInitializationError in a simple Flutter's hello world code There is following code:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp();
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
          Text("Hello world")
        ]
    );
  }
}

Whenever trying to run this code, there is an error:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
LateInitializationError: _renderObject@20042623
...
E/flutter (14923): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 2734 pos 20: '_debugCurrentBuildTarget == context': is not true.
E/flutter (14923): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter (14923): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (14923): #2      BuildOwner.buildScope.<anonymous closure> (package:flutter/src/widgets/framework.dart:2734:20)
E/flutter (14923): #3      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2738:12)
E/flutter (14923): #4      RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1127:13)
E/flutter (14923): #5      WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:967:7)
E/flutter (14923): #6      WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:948:7)
E/flutter (14923): #7      _rootRun (dart:async/zone.dart:1182:47)
E/flutter (14923): #8      _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (14923): #9      _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (14923): #10     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (14923): #11     _rootRun (dart:async/zone.dart:1190:13)
E/flutter (14923): #12     _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (14923): #13     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (14923): #14     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (14923): #15     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (14923): #16     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (14923): #17     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (14923):

When the Text object is removed from the children of Column, then there is no problem. There is an option also to wrap the widgets with MaterialApp, but I was wondering why it doesn't work without that?
This is Dart 2.11.

A: Not sure why this is the error you get but the text widget is missing a Directionality ancestor widget that specifies if the text is left to right or right to left (MaterialApp also provides this)
So wrap the column in a Directionality
And file an issue (if it doesnt exist yet) on the flutter git repo for getting such an non descriptive error message

A: It is better to use MaterialApp which provides the basic settings of the app for you:
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Training(),
    );
  }
}

class Training extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
        children: <Widget>[
          Text("Hello world")
        ]
    );
  }
}


text:
Q: TFS / VS 2012 RC - where is VSSConverter.exe? I am setting up a VM with a brand new install of TFS 2012 using the RC just released. This is the first time we have tried to use TFS in my company and I need to upgrade some SourceSafe databases. I've also installed the RC for Visual Studio 2012 Ultimate Edition (everything but the MFC foundation classes) but I still can't find the VSSConverter.exe tool.
According to Google it's supposed to be in the Common7\Ide folder, but is nowhere to be seen. Admittedly the only internet links I can find at the moment are for VS2010 so they may be out of date, but I have scanned the entire C drive and still can't find VSSConverter.exe
ps. I know there is a "download and install VSS converter" link in the TFS Admin Console but that just takes me to the Microsoft home page! : http://www.microsoft.com/en-us/default.aspx

A: VSSConverter is moving away from being a standalone tool and - as you noted - moving to be a part of the TFS Admin Console.
Unfortunately, the VSS -> TFS conversion experience did not ship as part of the TFS 2012 RC.  It will instead be included in the released TFS 2012.
In the meantime, the VSSConverter that was included as part of TFS 2010 will properly migrate to a TFS 2012 instance.  You will, however, need to install a 2010 instance just to run the tool.
If you do not require the full history, you could simply check-out your VSS databases and then check them into TFS.  Another alternative is to install TFS 2010 and use VSSConverter to that database, then perform an in-place upgrade to TFS 2012.


text:
Q: VueJS throws errors because some datas are not ready yet I'm rather new to VueJS, and I would like to add a picture loaded from an API as a background image. However, the image loading eventually works.
Here is the code:
<template>

Biography

        <router-link to="/">Home</router-link>

        Biography

        <router-link to="/shop">Shop</router-link>

        <router-link to="/contact">Contact</router-link>

</template>

The image is loaded, but my console returns two errors:

Error in render: "TypeError: Cannot read property 'url' of undefined"
Cannot read property 'url' of undefined

I guess that since the Axios call is asynchronous, everything arrives after the page is done loading, but is still loaded after.
What would the proper way be to correctly wait for data to be available? I tried a few things that I know from React, but it doesn't load at all (even though the errors stop showing up)
Thank you in advance

A: Yo need to be sure that this.settings.bio_bg.url exist from the component birth, so compiler doesn't broke trying to render it. In order to do so, just setup a 'fake' url in the original data of the component:
export default {
  data () {
    return {
      settings: {
        bio_bg: {
          url: '',
        }
      },
      bio: {}
    }
  },
  created () {
    this.$http.secured.get('/settings')
      .then(response => {
        this.settings = response.data
        console.log(this.settings)
      })
      .catch(error => this.setError(error))
  }
}

This not only prevent errors, also provides better intellisense since now your code editor can now that settings has a bio_bg member which in turn has an url.
If instead of ' ', you provide a real image url with a placeholder img, probably the UI will be nicer:
  data () {
    return {
      settings: {
        bio_bg: {
          url: 'http://via.placeholder.com/350x150',
        }
      },
      bio: {}
    }
  }


text:
Q: RSpec testing redirect to URL with GET params Let's say I have a FoosController with a redirect_to_baz method.
class FoosController < ApplicationController

  def redirect_to_baz
    redirect_to 'http://example.com/?foo=1&bar=2&baz=3'
  end

end

I'm testing this with spec/controllers/foos_controller_spec.rb:
require 'spec_helper'

describe FoosController, :type => :controller do

  describe "GET redirect_to_baz" do
    it "redirects to example.com with params" do
      get :redirect_to_baz
      expect(response).to redirect_to "http://example.com/?foo=1&bar=2&baz=3"
    end
  end

end

It works. However, if someone swaps the query string parameters (e.g. http://example.com/?bar=2&baz=3&foo=1), the test fails.
What's the right way of testing this?
I would like to do something like:
expect(response).to redirect_to("http://example.com/", params: { foo: 1, bar: 2, baz: 3 })

I looked at the documentation and I tried searching for response.parameters, but I didn't find anything like that. Even Hash#to_query doesn't seem to solve this problem.
Any help would be greatly appreciated.

A: Are you able to use your route helpers rather than a plain string? If so, you can just pass hash params to a route helper and they will be converted to query string params:
root_url foo: 'bar', baz: 'quux'
=> "http://www.your-root.com/?baz=quux&foo=bar"
expect(response).to redirect_to(root_url(foo: 'bar', baz: 'quux'))

Does that help, or are you restricted to using strings rather than route helpers?
Another thought is that you could just assert directly on the values in the params hash rather than the url + query string, since the query string params will get serialized into the params hash...

A: I had a need for something similar and ended up with this:
Was able to write tests and not worry about query parameter ordering.
expect(response.location).to be_a_similar_url_to("http://example.com/?beta=gamma&alpha=delta")

Drop the following into ./spec/support/matchers/be_a_similar_url_to.rb
RSpec::Matchers.define :be_a_similar_url_to do |expected|
  match do |actual|
    expected_uri = URI.parse(expected)
    actual_uri = URI.parse(actual)

    expect(actual_uri.host).to eql(expected_uri.host)
    expect(actual_uri.port).to eql(expected_uri.port)
    expect(actual_uri.scheme).to eql(expected_uri.scheme)
    expect(Rack::Utils.parse_nested_query(actual_uri.query)).to eql(Rack::Utils.parse_nested_query(expected_uri.query))
    expect(actual_uri.fragment).to eql(expected_uri.fragment)
  end

  # optional
  failure_message do |actual|
    "expected that #{actual} would be a similar URL to #{expected}"
  end

  # optional
  failure_message_when_negated do |actual|
    "expected that #{actual} would not be a similar URL to #{expected}"
  end
end

A: From the documentation, the expected redirect path can match a regex:
expect(response).to redirect_to %r(\Ahttp://example.com)

To verify the redirect location's query string seems a little bit more convoluted. You have access to the response's location, so you should be able to do this:
response.location
# => http://example.com?foo=1&bar=2&baz=3

You should be able to extract the querystring params like this:
redirect_params = Rack::Utils.parse_query(URI.parse(response.location).query)
# => {"foo"=>"1", "bar"=>"2", "baz"=>"3"}

And from that it should be straightforward to verify that the redirect params are correct:
expect(redirect_params).to eq("foo" => "1", "baz" => "3", "bar" => "2")
# => true

If you have to do this sort of logic more than once though, it would definitely be convenient to wrap it all up into a custom rspec matcher.


text:
Q: Submit button to write on another table I'm trying to create a form by VBA. Therefore, I'm using buttons to collect information and then, when clicking in the submit button, It should write the answers on another sheet, in a specific table. The next time you will use it and submit, the excel should add an extra line.
I have wrote a code but instead of starting to write the answers on the 1st line of the table (Cell B7), it starts at the end of it (B544). Do you have any idea why?
Links to the problem:

A: Since you are counting the table rows to use that number for the position parameter in the Add() method of ListRows object, I suppose you want to add a new row at the bottom of the table
To add a new row at the bottom of a ListObject object, just omit the position parameter
Private Sub CommandButton1_Click()
    Dim row As ListRow

    Set row = ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add
        row.Range(1) = ...
        row.Range(2) = ...

        ...

End Sub

which you can also "reduce" to:
Private Sub CommandButton1_Click()

    With ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add
        .Range(1) = ...
        .Range(2) = ...
    End With

    ...

End Sub

While if you want to add the new row as the first one, then use 1 for the position parameter
Private Sub CommandButton1_Click()
    Dim row As ListRow

    Set row = ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add(1)
        row.Range(1) = ...
        row.Range(2) = ...

        ...

End Sub

or its "collapsed" twin
Private Sub CommandButton1_Click()

    With ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add(1)
        .Range(1) = ...
        .Range(2) = ...
    End With

    ...

End Sub

A: Thanks for the help, this approach worked for me:
Private Sub CommandButton1_Click()
    Dim row As ListRow

    Set row = ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add(1)
        row.Range(1) = ...
        row.Range(2) = ...

        ...

End Sub

However, I would like to know how can I add new rows one after another (if the first row has values, it should add values to the 2nd row, and so on).
For example, this first approach will add new rows at the end of the table, no matter if it has values or not (the table could be empty):
 Dim row As ListRow

    Set row = ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add

On the second approach, one row will be added on the 1st position, while the remaining rows will go down (to the 2nd, 3rd, 4th,.... row):
Dim row As ListRow

    Set row = ActiveWorkbook.Worksheets("Teste-Base de dados").ListObjects("Table1").ListRows.Add(1)


text:
Q: Try to store music for XBOX UWP on System I'm writing a UWP Music player, that syncs Music stored in your OneDrive to the local machine to play it. The User can Store it in the App folder, or his Music Folder.
I also would like that this app runs on the XBoxOne. Unfortunately Storing Data on the System will quickly throw Not Enough Disk Space Exception.
According to an MSDN Answer an app can have a maximum of 3GB and there seems to be ways to get it up to 16GB  if no other UWP app takes up that space.
A dedicated Music folder is not available on Xbox. (The method to get the StorageFolder returns null)
Is there any way to store more data on the Xbox? Some music library's exceed easily 50GB.

A: No, there is no support for apps to get additional space on the internal drive (there can be a user music folder, but space here is limited). The reason why you got a failure getting the music folder may because that you didn't declare the capability. Since given the limited storage, I'd strongly discourage you from writing files there.
You can format an external USB drive to be used for media playback and plug it in, with apps being allowed to read from it if you have the capability defined in your manifest.
https://learn.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations
See above for declaring access to removable storage if you want to read from an external drive formatted for media.
Thanks.


text:
Q: Count distinct to find records with different values in a column table I have a simple question: How can I use having Count(Distinct) in SQL (Oracle to be exact) to return only the rows where there are 2 column with same record but 1 column with different record.
Example
CA_ID   BA_ID   SA_ID
----    -----   --------
CA1     BA1     SA1
CA1     BA2     SA1
CA1     BA2     SA2
CA1     BA3     SA1
CA2     BA4     SA3
CA2     BA4     SA4
CA2     BA5     SA4
CA3     BA6     SA6

In that example, i'd like to create a query that shows 1 same CA_ID and SA_ID, but has different BA_ID. The query's result should show like this
CA_ID   BA_ID   SA_ID
----    -----   --------
CA1     BA1     SA1
CA1     BA2     SA1
CA1     BA3     SA1
CA2     BA4     SA4
CA2     BA5     SA4

A: select  CA_ID
       ,BA_ID
       ,SA_ID
from   (select  t.*
               ,count(distinct BA_ID)  over(partition by CA_ID, SA_ID) as dcount
        from    t
       ) t
where  dcount > 1

CA_ID
BA_ID
SA_ID

CA1
BA1
SA1

CA1
BA2
SA1

CA1
BA3
SA1

CA2
BA4
SA4

CA2
BA5
SA4

Fiddle

A: We can try an aggregation approach to find the matching CA_ID and SA_ID values:
WITH cte AS (
    SELECT CA_ID, SA_ID
    FROM yourTable
    GROUP BY CA_ID, SA_ID
    HAVING MIN(BA_ID) <> MAX(BA_ID)
)

SELECT t1.*
FROM yourTable t1
WHERE EXISTS (
    SELECT 1
    FROM cte t2
    WHERE t2.CA_ID = t1.CA_ID AND
          t2.SA_ID = t1.SA_ID
);


text:
Q: RegEx: Find first appearance inside quotes I have such multi line text:
sometext "F1" "some other text;" "some other text;"
sometext "1" "some other text;"
sometext "`" "some other text;"
sometext "Tab" "some other text;"
sometext "CapsLock" "some other text;" "some other text;"
sometext "Shift" "some other text;"
sometext "\" "some other text;"
sometext "K" "some other text;"
sometext "ins" "some other text;"
sometext "downarrow" "some other text;" "some other text;"
sometext "Num Lock" "some other text;"
sometext "num5" "some other text;"
sometext "numenter" "some other text;"

I need to get value inside first quotes within each line.
I've tried "(.*?)" but it finds each value inside "".

A: To get the value inside the first occurance of the double quotes, you could add an anchor to assert the start of the line ^ and then match not a " using a negated character class [^"]*. Your match will be in the first capturing group:
^[^"]*"(.*?)"
Or you could also use a negated character class to capture what is between the double quotes:
^[^"]*"([^"]+)"

A: You need to escape the quote by using a backslash \"
try
\"(.*?)\"


text:
Q: Push JavaScript in while loop with column name from JS table i have some code while loop and push in JS:
var externalDataRetrievedFromServerAreas = "";
while.....
{
externalDataRetrievedFromServerAreas.push({COLUMNNAME:
document.getElementById('table1').rows[i].cells[j].innerHTML});
}

and here i want to have column name instead of 'COLUMNNAME', for example like this:
document.getElementById('table1').rows[0].cells[j].innerHTML

but i have an error, doing this way.
Can someone please help?

A: var externalDataRetrievedFromServerAreas = [];
while.....
{
const COLUMNNAME = document.getElementById('table1').rows[0].cells[j].innerHTML
externalDataRetrievedFromServerAreas.push({ [COLUMNNAME]:
document.getElementById('table1').rows[i].cells[j].innerHTML});
}


text:
Q: Erro com List com referência nula no Java Chamar qualquer método em qualquer referência nula sempre resultará em uma exceção.
Como eu poderia resolver isso?
public class frmStatusAprovacaoGeral implements AdapterInterface{

    @Override
    public void back(EntityWrapper arg0, Activity arg1) {

    }

    @Override
    public void start(Task arg0, EntityWrapper arg1, Activity arg2) {
        // Pega Entity wrapper do Processo
        WFProcess process = arg2.getProcess();
        NeoObject obj = process.getProcessEntity();
        EntityWrapper ewobj = new EntityWrapper(obj);

        //tenha a lista de parcelas
        Long numeroParcelas;
        try {
            numeroParcelas = (Long) ewobj
                    .findValue("contratoEformPosEscolha.pagamento.nroParcelas");
        } catch (Exception e) {
            numeroParcelas = (long) 1;
        }

                //estou pegando o campo aprovacaoGerencia para saber se ela foi aprovada
                List<NeoObject> listaParcelasGerencia = (List<NeoObject>) ewobj
                .findValue("frmParcelasAprovacaoGerencia");

                //estou pegando o campo aprovacaoAprovadorExtra para saber se ela foi aprovada
                List<NeoObject> listaParcelasExtraUm = null;
                try{
                listaParcelasExtraUm = (List<NeoObject>) ewobj
                        .findValue("frmParcelasAprovadorExtraUm");
                }catch(Exception e){
                    Log.error(e);
                }

                //estou pegando o campo aprovacaoAprovadorExtra2 para saber se ela foi aprovada
                List<NeoObject> listaParcelasExtraDois = null;
                try{
                    listaParcelasExtraDois = (List<NeoObject>) ewobj
                        .findValue("frmParcelasAprovadorExtraDois");
                } catch (Exception e){
                    Log.error(e);
                }

                //estou pegando o campo aprovacaoAprovadorExtra3 para saber se ela foi aprovada
                List<NeoObject> listaParcelasExtraTres = null;
                try {
                    listaParcelasExtraTres = (List<NeoObject>) ewobj
                            .findValue("frmParcelasAprovadorExtraTres");
                } catch (Exception e) {
                    Log.error(e);
                }

                //estou adicionando as respostas na listaParcelas
                List<NeoObject> ListaParcelaAtualGeral = (List<NeoObject>) ewobj
                .findValue("contratoEformPosEscolha.listaParcelas");

        for (long i = 0; i < numeroParcelas; i++) {

            NeoObject parcelaAtualGeral = ListaParcelaAtualGeral.get((int) i);
            EntityWrapper ewParcelaAtualGeral = new EntityWrapper(parcelaAtualGeral);

            //gerência
            //----------------------------------------------------------------------
            NeoObject parcelaAtualGerencia = listaParcelasGerencia.get((int) i);
            EntityWrapper ewParcelaAtual = new EntityWrapper(parcelaAtualGerencia);

            boolean aprovacaoGerencia = (boolean) ewParcelaAtual.findValue("aprovacaoGerencia");
            ewParcelaAtualGeral.setValue("aprovacaoGerencia", aprovacaoGerencia);
            //----------------------------------------------------------------------

            //extra um
            //Chamar qualquer método em qualquer referência nula sempre resultará em uma exceção.
            //Teste se o objeto é nulo primeiro:
            //----------------------------------------------------------------------
            if ( (listaParcelasExtraUm != null) || !listaParcelasExtraUm.isEmpty()){
                NeoObject parcelaAtualExtraUm = listaParcelasExtraUm.get((int) i);
                EntityWrapper ewParcelaAtualExtraUm = new EntityWrapper(parcelaAtualExtraUm);

                boolean aprovacaoAtualExtra1 = (boolean) ewParcelaAtualExtraUm.findValue("aprovacaoAprovadorExtra");
                ewParcelaAtualGeral.setValue("aprovacaoAprovadorExtra", aprovacaoAtualExtra1);
            }
            //----------------------------------------------------------------------

            //extra dois
            //----------------------------------------------------------------------
            if ( (listaParcelasExtraDois != null) || !listaParcelasExtraDois.isEmpty()){
                NeoObject parcelaAtualExtraDois = listaParcelasExtraDois.get((int) i);
                EntityWrapper ewParcelaAtualExtraDois = new EntityWrapper(parcelaAtualExtraDois);

                boolean aprovacaoAtualExtra2 = (boolean) ewParcelaAtualExtraDois.findValue("aprovacaoAprovadorExtra2");
                ewParcelaAtualGeral.setValue("aprovacaoAprovadorExtra2", aprovacaoAtualExtra2);
            }
            //----------------------------------------------------------------------

            //extra três
            //----------------------------------------------------------------------
            if ( ( listaParcelasExtraTres != null) || !listaParcelasExtraTres.isEmpty()){
                NeoObject parcelaAtualExtraTres = listaParcelasExtraTres.get((int) i);
                EntityWrapper ewParcelaAtualExtraTres = new EntityWrapper(parcelaAtualExtraTres);

                boolean aprovacaoAtualExtra3 = (boolean) ewParcelaAtualExtraTres.findValue("aprovacaoAprovadorExtra3");
                ewParcelaAtualGeral.setValue("aprovacaoAprovadorExtra3", aprovacaoAtualExtra3);
            }
            //----------------------------------------------------------------------

            PersistEngine.persist(parcelaAtualGeral);

        }
    }
    @Nullable
    Long ValidaCampo() {
        return null;

    }

}

A:
Chamar qualquer método em qualquer referência nula sempre resultará em uma exceção. Como eu poderia resolver isso?

Checando se a lista é nula ou não antes de tentar acessar qualquer coisa nela
Ex.:
if(listaParcelasExtra != null){
    listaParcelasExtra.fazerAlgumaCoisa();
}

A: Você pode setar um valor padrão caso esteja nulo, como por exemplo:
if (listaParcelasExtraUm == null) {
  listaParcelasExtraUm = new ArrayList<>();
}

Ou simplificando usando operador ternário:
listaParcelasExtraUm = listaParcelasExtraUm == null ? new ArrayList<>() : listaParcelasExtraUm;

A: Se quiser, você pode remover todas as entradas nulas das suas listas e continuar trabalhando normalmente sem ter que verificar entrada por entrada:
suaLista.removeAll(Collections.singleton(null));
Post original


text:
Q: How to get the "path" in React... "location" not found Sorry! someone knows how to access the "context" parameters to extract the "path",
try to do it in the following way without success:

    componentDid() {
      console.log("entre")
      const item = document.querySelector(
        this.props.location.state
      );
      if (item) {
        console.log(item);
      }
    }

imports:
import React from 'react';
import axios from 'axios';
import { Link, BrowserRouter, Route } from 'react-router-dom';

Archive:
import React from 'react';
import axios from 'axios';
import { Link, BrowserRouter, Route } from 'react-router-dom'; // prueba
import '../css/LobbyStyles.css'
import '../css/styleSearch.css'

const liStyle = {
    paddingLeft: '45px',
    listStyleType: "none",
};

export default class LobbyPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            listPlayers: [],
        };
    }

    componentDid() {
        console.log("entre")
        const item = document.querySelector(
            this.props.location.state
        );
        if (item) {
            console.log(item);
        }
    }

    render() {
        return (

Lobby

                <Link to={`/game/`}>
                    <button className="buttonFound bttmodal bttLobby">Iniciar Partida</button>
                </Link>

        );
    }
}

When I try things like:
const location = useLocation();
console.log(location.pathname);
I get an error.
Thanks!

A: If you have a route like this /Lobby/:lobbyID
this.props.location.pathname will return you /Lobby/1
this.props.match.params["lobbyID"] will return you 1
Also change
 componentDid()

to componentDidMount()


text:
Q: I am having trouble while Knitting RMarkdown file I am getting following error while Knit my RMarkdown file.
Parser error: while parsing a block mapping at line 1, column 1 did not find expected key at line 2, column 11
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted*

I understand it's my yaml header which is following -
---
title: "Data Wrangling Assessment"
author: ""ABC 11111""
subtitle:
output:
  word_document: default
  html_document:
    df_print: paged
  html_notebook: default
---

Can anyone please help me to troubleshoot?

A: The issue is that you wrapped the author name in doubled double quotes. If you want to quote the author name you have to

*

*escape the inner double quotes using \", e.g. "\"ABC 11111\""

*replace the outer double quotes with single quotes, e.g. '"ABC 11111"'

---
title: "Data Wrangling Assessment"
author: "\"ABC 11111\""
subtitle:
output:
  word_document: default
  html_document:
    df_print: paged
  html_notebook: default
---


text:
Q: Alert Dialog method called on button click but can not show the dialog box I am having the issue with the alert dialog box.
When i click on the button in row, method call goes inside the method but the alert box donot appear.
this is my code.
 final AlertDialog.Builder builder = new AlertDialog.Builder(this.activity,R.style.MyAlertDialogStyle);
    ImageView img_user_delete=(ImageView)convertView.findViewById(R.id.img_user_delete);
    img_user_delete.setTag(position);
    img_user_delete.setOnClickListener(new ImageView.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
            name1_u = name_user.get(position);
            Log.e("Row_list_user", "name : " + name1_u);
            final int position = (Integer) v.getTag();
            Integer position1 = position + 1;
            builder.setMessage("Are you sure you want to delete?")
                    .setIcon(R.drawable.ic_action_warning)
                    .setTitle("Warning")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            db.deleteUserRow(name1_u);
                            name_user.remove(position);
                            notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();

                        }
                    });
        }
    });

This code works fine in one class but not working in another class.Please help.

A: You have to call create() method to create an AlertDialog with the arguments supplied to builder and show()method to show AlertDialog. See the code below:
final AlertDialog.Builder builder = new AlertDialog.Builder(this.activity, R.style.MyAlertDialogStyle);
        ImageView img_user_delete = (ImageView) convertView.findViewById(R.id.img_user_delete);
        img_user_delete.setTag(position);
        img_user_delete.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do something
                name1_u = name_user.get(position);
                Log.e("Row_list_user", "name : " + name1_u);
                final int position = (Integer) v.getTag();
                Integer position1 = position + 1;
                builder.setMessage("Are you sure you want to delete?")
                        .setIcon(R.drawable.ic_action_warning)
                        .setTitle("Warning")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                db.deleteUserRow(name1_u);
                                name_user.remove(position);
                                notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();

                            }
                        }).create().show();
            }
        });


text:
Q: How to enable horizontal mouse wheel scrolling in unity? I've read a few related questions:
Enable horizontal scrolling in Ubuntu
http://ubuntuforums.org/showthread.php?t=2097030
But hasn't given me the answer. Just plugged in a mouse in 12.04 and there's no horizontal scrolling with the mousewheel. Instead it has strange behaviour where text is changed if mousewheel is held down and moved over it. HP mouse, feature works on windows 7.

A: If you are under Ubuntu, you have to install two packages: xbindkeys and xautomation.
To enable the horizontal scroll with key combination Shift+MouseWheel, run these commands on Terminal:
$ sudo apt-get install xbindkeys xautomation
$ echo "; bind shift + vertical scroll to horizontal scroll events
>  (xbindkey '(shift \"b:4\") \"xte 'mouseclick 6'\")
>  (xbindkey '(shift \"b:5\") \"xte 'mouseclick 7'\")" >> .xbindkeysrc.scm

$ xbindkeys


text:
Q: Exclude all permission denied messages from "du" I am trying to evaluate the disk usage of a number of Unix user accounts.
Simply, I am using the following command:
du -cBM --max-depth=1 | sort -n

But I've seen many error message like below. How can I exclude all such "Permission denied" messages from display?
du: `./james/.gnome2': Permission denied

My request could be very similar to the following list, by replacing "find" to "du".
How can I exclude all "permission denied" messages from "find"?
The following thread does not work. I guess I am using bash.
Excluding hidden files from du command output with --exclude, grep -v or sed

A: I'd use something concise that excludes only the lines you don't want to see. Redirect stderr to stdout, and grep to exclude all "denied"s:
du -cBM --max-depth=1 2>&1 | grep -v 'denied' | sort -n

A: To remove all errors coming from the du command i used this:
du -sh 2>&1 | grep -v  '^du:'

A: you can pipe it to a temporary file, like -
du ...  > temp_file
Errors get printed on the terminal and only disk usage information gets printed into the temp_file.

A: If 2>/dev/null does not work, probably the shell you are using is not bash.
To check what shell you are using, you may try ps -p $$ (see https://askubuntu.com/a/590903/130162 )

A: du -cBM --max-depth=1 2>/dev/null | sort -n

or better in bash (just filter out this particular error, not all like last snippet)
du -cBM --max-depth=1 2> >(grep -v 'Permission denied') | sort -n

A: 2> /dev/nul hides only error messages.
the command du always try run over directory. Imagine that you have thousands of dirs?
du needs eval, if you have persmission run if not, follow with the next dir...


text:
Q: Unable to set tmux window title to current program I am pretty new to tmux and have been using it for now a week or so. I want the tmux window titles to be set to the current program i am running like vim/htop etc and not to the host i am connected to.
Below is my config and as per tmux man page #W is used for that however it does not seem to work in my case and my window titles are always being set as fqdn[username]
set -g status on
set -g status-interval 1
set -g status-fg colour231
set -g status-bg colour234
set -g status-left-length 20

set -g status-left '#{?client_prefix,#[fg=colour254]#[bg=colour31]#[bold],#[fg=colour16]#[bg=colour254]#[bold]} #S #{?client_prefix,#[fg=colour31]#[bg=colour234]#[nobold],#[fg=colour254]#[bg=colour234]#[nobold]}'

set -g window-status-format "#[fg=colour244,bg=colour234]#I #[fg=colour240] #[default]#W "
set -g window-status-current-format "#[fg=colour234,bg=colour31]#[fg=colour117,bg=colour31] #I  #[fg=colour231,nobold]#W #[fg=colour31,bg=colour234,nobold]"
set -g window-status-last-style fg=colour31
set-window-option -g window-status-fg colour249

set -g status-right-length 150
set -g status-right  "#[fg=colour225,bg=colour234]#[fg=colour234,bg=colour225] #(date +%a' '%b' '%d) %H:%M#[fg=colour234]#[bg=colour234]#{?pane_synchronized,#[bg=colour236]#[fg=colour160]#[fg=colour255]#[bg=colour160] PANES-ARE-SYNCED !! #[fg=colour234]#[bg=colour=234],#[fg=colour22]#[fg=colour255]#[bg=colour22] PANES-NOT-SYNCED #[fg=colour234]#[bg=colour234]}#[fg=colour255,bg=colour234]#[fg=colour234,bg=colour255,bold]#h"

So can anyone please let me know how do i do it.

A: I found that on some machines I would get a username@hostname:~ and on others I would get the name of the executable. On both machines tmux show -gw showed:
automatic-rename on
automatic-rename-format "#{?pane_in_mode,[tmux],#{pane_current_command}}#{?pane_dead,[dead],}"

So I wondered what was happening... it turns out that the option allow-rename was on where I could see username@hostname:~ and off where I saw the current executable name.
allow-rename makes it possible for your shell (in my case bash) to change the pane title with an escape sequence and in some configurations (for example if your TERM environment variable starts with screen) the title will be updated every time your prompt is shown (this is more of a shell related issue so if you are interested please look for information on PS1 and in /etc/bash/bashrc). To see the effect try this:
echo -en '\033kTMUXISCOOL\033]' ; sleep 5

When you run that command in tmux you should see the current pane title change to TMUXISCOOL for 5 seconds then back to username@hostname:~. By putting the following line into ~/.tmux.conf:
set -g allow-rename off

The pane title should display the current executable... or whatever is in automatic-rename-format.