text:
Q: What is the proper way to perform a pull request? I have branch main and branch dev.
They are on the same level.
I then go to branch dev and create another branch from its base, called feature-a.
I commit 10 commits to feature-a and push to github. Then I go to github and create a pull request from the feature-a branch to the dev.
I review, I confirm and merged to dev.
Then I go to dev on local and pull the new changes to the dev.
Then I do the same process from dev to main.
Here the problem happens: the dev is behind the main branch, since the main has extra commit - of the merged dev, for example:
commitID1 (HEAD -> main, origin/main) Merge pull request #77 from GITHUB/dev
commitID2 (origin/dev, dev) Merge pull request #76 from GITHUB/feature-a

As you can see, the dev is now just behind main, instead of being on the same level as they had been in the start.
This doesn't let me see the flow of the merges and I wonder what is the best practice in here?

A: This is all perfectly normal, and is how PRs on GitHub work.

This [output from git log --oneline] doesn't let me see the flow of the merges ...

To see that, use git log --oneline --graph, or a graphical viewer.  See also Pretty Git branch graphs.
(There are alternative methods on GitHub where you don't actually do merges at all with your pull requests, but that's another topic entirely.  You're already trying to follow an existing "do make merges" flow, where this is the result you should expect.)


text:
Q: 3d plot from two vectors and an array I have two vectors that store my X, Y values than are lengths 81, 105 and then a (81,105) array (actually a list of lists) that stores my Z values for those X, Y. What would be the best way to plot this in 3d? This is what i've tried:
Z = np.load('Z.npy')
X = np.load('X.npy')
Y = np.linspace(0, 5, 105)
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap= 'viridis')
plt.show()

I get the following error : ValueError: shape mismatch: objects cannot be broadcast to a single shape

A: OK, I got it running.  There is some tricks here. I will mention them in the codes.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from random import shuffle

# produce some data.
x = np.linspace(0,1,81)
y = np.linspace(0,1,105)
z = [[i for i in range(81)] for x in range(105)]
array_z = np.array(z)

# Make them randomized.
shuffle(x)
shuffle(y)
shuffle(z)

# Match data in x and y.
data = []
for i in range(len(x)):
    for j in range(len(y)):
        data.append([x[i], y[j], array_z[j][i]])
        # Be careful how you data is stored in your Z array.
# Stored in dataframe
results = pd.DataFrame(data, columns = ['x','y','z'])

# Plot the data.
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(results.x, results.y, results.z, cmap= 'viridis')

The picture looks weird because I produced some data.  Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get the header text at the top of the page in Java? I am testing a page with local links in it. And for example this is a "team Name" local link when I click on it the page scrolls to the team Name header, when i get header driver.findElements(By.xpath(//h1 || //h2 || h3).getText() this code give to me first header element text but I want to get the text of the header that I clicked on and that appears at the top of the page at that moment. And Sometimes these local links lead to another header of another documentation. I want to be able to get the header here with the same code. Can you help?
 List<WebElement> links = seleniumHelper.getWebElementList(contextNavigateLinks);
            for (int j = 0; j < links.size(); j++){

                String expectedHeader = links.get(j).getAttribute("href").split("#")[1];
                System.out.println(expectedHeader);
                waitHelper.waitUntilElementIsInVisiableWithLocator(contextNavigateLinks, 30);
                seleniumHelper.forceClickToElement(links.get(j));
                String actualHeader = seleniumHelper.getTextWithBy(docsPageHeaders);
                seleniumHelper.assertValueWithString(actualHeader, seleniumHelper.castAString(expectedHeader));
            }


text: Q: How can Ubuntu be installed? Can not install any version of Ubuntu on the eMachines E732 laptop after it crashed.  The error message received is: [end Kernel panic - not syncing: Attempted to kill init! ext code = 0x00000009.]


text:
Q: How to display video thumbnail in Jetpack Compose? I'm implementing a simple gallery screen using Jetpack Compose which shows all video and image thumbnails on the screen
I have displayed image from file path successfully. However, I've got trouble in showing video thumbnail. How can I do that using Coil?
Here's my code to show image thumbnails:
@Composable
fun ImageLoaderFromLocal(
    url: String,
    placeHolderResId: Int,
    modifier: Modifier,
    transformation: Transformation
) {
    val painter = rememberImagePainter(data = File(url),
        builder = {
            placeholder(placeHolderResId)
            crossfade(true)
            transformations(transformation)
        })

    Image(
        painter = painter,
        contentDescription = null,
        modifier = modifier,
        contentScale = ContentScale.Inside
    )
}

A: According to Coil documentation, you need to add following dependency:
implementation("io.coil-kt:coil-video:$coil_version")

and specify fetcher in the builder:
val context = LocalContext.current
val painter = rememberImagePainter(
    data = url,
    builder = {
        fetcher(VideoFrameUriFetcher(context))
        // optionally set frame location
        videoFrameMillis(1000)

        placeholder(placeHolderResId)
        crossfade(true)
        transformations(transformation)
    }
)

A: The other answer doesn't really work any more.
so i tried this one and it worked
val context = LocalContext.current
var visible by rememberSaveable { mutableStateOf(false) }

val imageLoader = ImageLoader.Builder(context)
    .components {
        add(VideoFrameDecoder.Factory())
    }.crossfade(true)
    .build()

val painter = rememberAsyncImagePainter(
    model = "Your file here",
    imageLoader = imageLoader,

The painter should be called in the image composable
like this
Image(
      painter = painter,
      contentDescription = "",
      contentScale = ContentScale.Crop,
      alignment = Alignment.Center,
      modifier = Modifier.fillMaxSize()
     )

i hope this help someone


text:
Q: Where are most customers located? I have a datatable of customers similar to the following
CustID    InState
===================
1         0
2         0
3         1

Where InState = 0 corresponds to the customer being out-of-state, and Instate = 1 corresponds to the customer being in-state. I want to write a stored procedure to return "Out-of-State" if there are more out-of-state customers or return "In-State" if there are more in-state customers.
I have started just working with a basic query, and this is what I have:
SELECT
        COUNT(CASE WHEN InState = 0 THEN 1 END) as 'Out-of-State',
        COUNT(CASE WHEN InState = 1 THEN 1 END) as 'In-State'
FROM Customers

This gives me the counts for each category, but I only want the answer of the greater of the two. How could I go about this?

A: I think you are pretty much there
SELECT  CASE WHEN COUNT(
                      CASE WHEN InState = 0 THEN 1 END) >
                          COUNT(CASE WHEN InState = 1 THEN 1 END)
             THEN 'Out of State'
             ELSE 'In State'
         END GreaterClassification
  FROM Customers

A:  SELECT
    COUNT(CASE WHEN InState = 0 THEN 1 END) as OutOfState,
    COUNT(CASE WHEN InState = 1 THEN 1 END) as InState,
CASE
 WHEN COUNT(CASE WHEN InState = 0 THEN 1 END)- COUNT(CASE WHEN InState = 1 THEN 1 END)>0 THEN 'OUT OF STATE'
 WHEN  COUNT(CASE WHEN InState = 0 THEN 1 END)- COUNT(CASE WHEN InState = 1 THEN 1 END)<0 THEN 'IN STATE'
 ELSE 'DAMN THEY ARE EQUAL'
 END
 FROM Customers

A: If instate only takes on the values of 0 and 1, then use sum():
select (case when sum(instate) > sum(1 - instate) then 'In State'
             when sum(instate) < sum(1 - instate) then 'Not In State'
             else 'Equal'
        end)
from customers;

A: maybe something like this can help
declare @t table (custid int, instate int)
insert into @t values (1, 0), (2, 0), (3, 1)

select case when t.instate = 1 then 'in the state' else 'not in the state' end as position
from   ( select top 1 count(instate) poscount, instate
         from  @t
         group by instate
         order by 1 desc
       ) t

the result is not in the state


text:
Q: Handling when format-date() tries to format an invalid date in XSL I need to format a date using XSL. For example:
    <xsl:choose>
        <xsl:when test="$rawdate">
            <xsl:variable name="dt" as="xs:date" select="$rawdate"/>
            <xsl:value-of select="format-date($dt, '[D01]-[MNn,*-3]-[Y0001]')"/>
        </xsl:when>
        <xsl:otherwise>
            N/A
        </xsl:otherwise>
    </xsl:choose>

This will work if $rawdate is formatted correctly (e.g. YYYY-MM-DD). However, if its formatting incorrectly (such as DD-MM-YYYY), the format-date() function fails and processing stops. $rawdate is coming from an XML file that is edited by hand, so it's possible for someone to unintentially format the date wrong.
What I want to do is catch when format-date() is going to fail (or already failed) so I can handle it gracefully instead of halting the transformation. Is that possible?

A: Use castable as xs:date
<xsl:choose>
    <xsl:when test="$rawdate castable as xs:date">
        <xsl:variable name="dt" as="xs:date" select="$rawdate"/>
        <xsl:value-of select="format-date($dt, '[D01]-[MNn,*-3]-[Y0001]')"/>
    </xsl:when>
    <xsl:otherwise>
        N/A
    </xsl:otherwise>
</xsl:choose>


text:
Q: scan arbitrary number of chars in c I want to read an unknown number of characters, which are not greater than 10.
char word[10];
for( i=0;i<10;i++){
    if( !scanf("%c",&word[i])){ //terminate with 0
        getchar();
        break;
    }
}

The problem is that  number is also an character, so the if statement won't be executed. Is there any other solution to terminate the input of characters for example with 0.

A: You can use a do..while loop. Something like (pseudo-code)
int keep_looping = 1;
int counter = 0;
do {
    ret = scanf(" %c",&word[counter]);
    if (!ret) continue;  //can use more cleanup and error check
    if (word[counter] == '0') keep_looping =0;
    counter++;
    }
while (keep_looping && counter < 10)

A: you can check the character that you just read (at word[i])  and if not valid (e.g not alpabetical) than break.

A: Suggest:
char word[10];

if( scanf("%9s",word) != 1 )
{
    fprintf( stderr, "scanf for (max 9 char word) failed\n" );
    exit( EXIT_FAILURE );
}

using %9s because the %s input format conversion specifier always appends a NUL byte to the input.
If the input is less than 9 characters, that is properly handled.
If the input is greater than 9 characters, the 9 modifier will stop the input, so the input buffer is not overflowed.  Such an overflow would result in undefined behavior.


text:
Q: Angular multiple form values in ngFor hope somebody can help me? I'm building a form in my component like this (Version not running):
<div *ngFor="let status of someService.monitoringStatus">
 <form name="form" [formGroup]="form" (ngSubmit)="updateStatus(form.value,status.id)">
  <input type="text" formControlName="next_status" value="{{status.old_status}}">
 </form>
</div>

The problem now is that I can't get {{status.old_status}} in my input as value. But why? If I am using it outside it shows me right.
Edit (my component.ts looks like this):
  form = new FormGroup({
    next_status: new FormControl('', Validators.required)
  })

  updateStatus(value,id: any){
    this.someService.updateStatus(value,id).toPromise().then((data: any) => {  console.log(data)
    }).catch((err: HttpErrorResponse) => {
      console.error('Fehler:', err.error);
    });
  }

A: So you have your forms inside an *ngFor - but they all have the same name, so how can the code distinguish between them?  They must all have unique names. If you add an index, you can give them unique names
<div *ngFor="let status of someService.monitoringStatus; let i=index;">
 <form name="form{{i}}" [formGroup]="form{{i}}" (ngSubmit)="updateStatus(form{{i}}.value,status.id)">
  <input type="text" formControlName="next_status{{i}}" value="{{status.old_status}}">
 </form>
</div>

Then you can use {{i}} to distinguish them from each other


text:
Q: Getting error while calling user validation on a clustered OpenText CS/AS Server Environment I have a clustered OpenText Content Server 10.5 Update 2015-09 installation along with a clustered Archive Server operating with Microsoft Cluster on Windows 2012R2.
The cluster mode is active/passive.
The configuration is the following:
MS Server Cluster: responding on an address ending with .99

*

*Node 1: OTCS application ON responding on a vip address ending with .47

*Node 2: OTCS application OFF

MS Server Cluster: responding on an address ending with .98

*

*Node 1: OTAS application ON responding on a vip address ending with .48

*Node 2: OTAS application OFF

I have an application that calls OT Java Web Services configured to point directly to the cluster address, not to the single servers.
The step I followed are:

*

*Authentication against OTDS mounted on the AS server first, exploting the client built using otdsws/services/Authentication wsdl. This returns an OTDSSO token for the user.

*User validation against CS using ValidateUser method and the OTDSSO as parameter, built by the cws/Authentication.svc wsdl
The problem is:
when the application starts it can correctly communicate with the CS server using WS but when the cluster switches on the other node the url build in order to call the ValidateUser method corresponds to the MS cluster vip (.99) instead of OTCS application vip (.47).
As long as these applications are on different nodes I get the following error:

Could not access server. No connection could be made because
  the target machine actively refused it 172.30.136.99:2099
                 at OpenText.Livelink.Service.Core.ExceptionUtil.handleException(Exception
  ex)    at
  OpenText.Livelink.Service.Core.Authentication.ValidateUser(String
  capToken)    at
  OpenText.Livelink.Service.Core.Authentication_WCF.ValidateUser(ValidateUserRequest
  request)    at SyncInvokeValidateUser(Object , Object[] , Object[] )
  at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
  instance, Object[] inputs, Object[]& outputs)    at
  System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
  rpc)    at
  System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
  rpc)    at
  System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
  rpc)    at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
  isOperationContextSet)
                 OpenText.Livelink.Service.Core.ServiceException

I performed the same test using SoapUI getting the same error.
I'm wondering why the call is routed to the cluster application vip instead of the OTCS application vip.
Update 2015-12-15
Also verified the security parameters configuration settings as suggested by @Matthew Barben, but with no success.
It seems that every IP is allowed to call the OTCS system by default, in fact reading from the help page:

Content Server Client Hosts
The Content Server Client Hosts field contains the IP addresses of
  servers from which requests are to be accepted. By default, the field
  is blank, and all client connections are accepted.

A: Check the web.xml (Tomcat side) or web.config (IIS side) file for the deployed CWS web service. On the very first lines check the livelink.host value and modify it to reflect your system configuration
?xml version="1.0" encoding="utf-8"?> <configuration>   <appSettings>
    <add key="livelink.host" value="yourContentServerHost.yourdomain.com" />
    <add key="livelink.port" value="2099" />

This parameter handles the connection between the web service and CS
Restart web services and test your custom app.

A: Do you have any entries listed in CGI hosts parameter on OTCS?
(You can check by going to http://your_installation_hostname/otcs/cs.exe?func=admin.securityvars).
If you happen to have CGI hosts listed you will need to lists both the 172.30.136.99 and 172.30.136.98 servers.


text:
Q: On click - open a popup from different website I have 2 websites . in one website i will give a link "request info" on clicking this link it should open a popup   which is implemented it another website.
is it possible?
code in site1.com

Request Info

A: There is one other problem you have two id attributes in the a element requestPopupD and iframe_form_request_info
You can
$('#iframe_form_request_info').click(function(){
    window.open(this.href); // also pass any other properties you want
    return false;
})

A: To open a link as a pop up:

HTML
Open a popup window

A: You can open a window with pure JS like this:
function openWindow() {
    var win = window.open('http://google.com','','width=200,height=100');

    //manipulate win if you want to (eg. win.write("text");)

    win.focus();
}

And to call it on your button click:

Request Info


text:
Q: Interpretation of Elastic net having too low or high value of alpha Often I found the situation that the elastic model what I fitted has optimal alpha value at 0 or 1. Or not only that situation, but also there some alphas go near to 0 or 1.(ex. 0.1 or 0.9)
My Question is : Is there anything to mean that the alphas tends to go to 0 or 1?
(Added for more clarification)
If in my dataset the ratio of the number of predictors highly correlated with dependent variable is high, the Elastic net model remains more predictors. Then the model is more appropriate to ridge model than lasso.
Does my guess make sense logically?


text:
Q: bash script for comparing I am trying to write a bash script.
I am on Amazon-s3. I have a bucket1, which contains bucket2, bucket3, bucket4. The bucket 2 has b1, b2, b3, b4, b5 - in which each of them contain tar files being created with    nd the file name.
When I do a s3cmd --recursive ls s3://bucket1/bucket2/ | awk '{print$1}' I print the date of all the tar files which are generated.
I want the date on the computer to compare it with that list and print the last 1 week of the files which have been created.
Format of date on s3 : year/month/date
Thank you.

A: You can use gnu date with the +%s option to get seconds, and then easily compare dates in whatever format, i.e.
> (( ( $(date +%s) - $(date -d "2014/03/08" +%s) ) < (7*24*60*60) )) \
&& echo "Less than week ago" \
|| echo "More than week ago"
More than week ago

> (( ( $(date +%s) - $(date -d "2014/04/03" +%s) ) < (7*24*60*60) )) \
&& echo "Less than week ago" \
|| echo "More than week ago"
Less than week ago


text:
Q: AS3 : Accessing Array Name Through For Loop with counters? I do not know what you would call or define this type of issue with AS3.
I have 2 For Loops that look like this:
// Here I would have 5 arrays naming from NDW1 to NDW5
var NDW1:Array = new Array();

for(var a:int = 1; a < 6; a++){
    for(var b:int = 0; b < 14; b++){
       // Here I want to call a function and assign it to a textfield
       this["DifferenceW"+a+"_"+b].text = CalculateDifference(Number("NDW"+a+"["+b+"]"), Number("NDW"+a+"["+b+"]")).toString();
    }
}

My problem when I am trying to access the actual array of NDW while using counters to increment that actual array and array element.
But when I type "NDW"+a+"["+b+"]" it will only return a string value. How do I actually get it to return the array with that current element?
So for example if NDW1[0] = 2 instead of just a string of NDW1[0]?

A: 5 arrays and you want to loop through each array? Put those 5 arrays in 1 array.
private var _allArr:Array = [NDW1, NDW2, NDW3, NDW4, NDW5];

Now you can easily access everything without silly string concatenation.
for each (var a:Array in _allArr){
    for each (var b:Number in a){
        this["DifferenceW"+a+"_"+b].text = (CalculateDifference(a[b], a[b])).toString();
    }
}

What does CalculateDifference do? You are feeding it two identical numbers so I hope it isn't calculating the difference between those numbers (will always be 0).
Anyway. The other way to loop through them is this:
for (var i:int = 0; i < _allArr.length; i++){
    for (var j:int = 0; j < _allArr[i].length; j++){
        this["DifferenceW"+a+"_"+b].text = (CalculateDifference(_allArr[i][j], _allArr[i][j])).toString();
    }
}

update
I'm going to guess that you want to find the difference between NDW1[0] and NDW2[0], etc. If so, your CalculateDifference function should be passed those two values. This is a bit trickier. Do this:
for (var i:int = 0; i < _allArr.length; i++){
    for (var j:int = 0; j < _allArr[i].length - 1; j++){
        this["DifferenceW"+a+"_"+b].text = (CalculateDifference(_allArr[i][j], _allArr[i+1][j])).toString();
    }
}

A: After trying multiple combinations with the keyword this
it can be used to access variables that you created which I never knew, but for future reference to access any variable you would use:
this["variableName"]
in my case for the for loop to access the elements you would use
this["NDW"+a][b]

A: As others have already said, it's not very clear what you're trying to do and it looks like you're really over-complicating something that should be very simple.
To answer your question though, with "NDW"+a+"["+b+"]", your mistake is in thinking that you can concatenate a string to create a variable name. You can't. That will always return a string because it is a string that you are creating.
You could access it by using this["NDW"+a+"["+b+"]"] which evaluates to a property called "NDW"+a+"["+b+"]" on 'this' object, but that really isn't a very nice thing to do.
Neal's solutions look good but don't evaluate the length of the arrays on each iteration as that's very inefficient.


text:
Q: Link domain branch.io On the dashboard, I have two domains: "Default Link Domain" and "Alternative Link Domain", but when I create a new link using the API, I get a link without this domain, something like this "app.test-app ". It's very important for me that my link is without a "test". And also I don't understand how it works, how this domain appears in my link. Could you please explain it to me?
Here is my branch.json
{
    "debugMode": false,
    "liveKey": "key_live_****",
    "testKey": "key_test_****",
    "useTestInstance": false,
    "delayInitToCheckForSearchAds": true,
    "appleSearchAdsDebugMode": true
}
When I set up my application, I added a test key to info.plist and forgot about it. After I changed it to a live key, everything worked perfectly!

A: A Branchster here -
By default your Branch app has two modes - Live and Test. When you are using the API to generate a new link make sure you are passing in your Live API key. If you use your Test Mode API key then you'll get corresponding test link like "yourapp-app.app.link/xxxx"
You can read more about it here - https://help.branch.io/using-branch/docs/advanced-settings-configuration


text:
Q: Paragraph inside Anchor cannot be formated while working i messed HTML because i did not knew that
 tag within  tag does not get formated .
Like if i had :

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

where  parent width is 200px; text goes through 200px; instead of putting New Lines to fit the text inside .

A: try to make
a {
display: block;
}

A: Adding the display: block; to the a element fixes it. The a tag is an inline element by default. It was not meant to hold other elements and so the width property does not affect it. Using CSS to make it display like a block element should make properties like width work correctly. I've got a working demo on jsfiddle here.

A: Your markup is just missing the compulsory anchor href attribute. The following would render properly:

Lorem Ipsum is simply dummy text... ever since the 1500s,

Check it out


text:
Q: Is this an acceptable way of writing the count of items in a sentence? My father served in the logistics branch of Indian armed forces and he had a very particular style of representing the number of items of a certain object. For example, he would use this sentence:
Confirming the receipt of footballs (20 nos) and volleyballs (10 nos).
OR
Confirming the receipt of footballs (20 numbers) and volleyballs (10 numbers).

Of course I can also say, "Confirming the receipt of 20 footballs and 10 volleyballs", but it changes the emphasis that the sentence puts on the numbers.
I haven't seen this format used outside his military communication, though if I use it, people seem to understand it fine. Is there an internationally accepted way of writing numbers like this?

A: Guides often don't talk about parenthetical numbers. One military guide omits this concern entirely. So do more and less formal writing guides available online. They focus instead on when you spell numbers out. I could only find mention of this practice in an APS (American Physiological Association) Style Guide, which specifies writing units after a noun in parentheses in response to a concern about starting a sentence with a number:

You can rearrange a sentence so that the numbers do not appear first or insert a semicolon to connect it to the preceding sentence. For example, you can change:
…for five ocelots. 100-ml aliquots were then added to their cages.
to
…for five ocelots. Aliquots (100 ml) were then added to their cages.

More generally, shifting the number to a parenthesis after the noun rather than placing it before the noun feels fine. (I know I've seen it before without giving it much thought.) In the case of raw numbers rather than units like ml, saying "number" feels redundant: I would read "footballs (20)" as 20 footballs. However, it's possible that within your father's branch that they valued the redundant clarity of adding a unit (numbers or nos for short) for every number.
There's no international standard here. Instead, set a practice within a document and be consistent.


text:
Q: Maintaining jobs history in apscheduler I am using apscheduler to schedule my scrapy spiders. I need to maintain history of all the jobs executed. I am using mongodb jobstore. By default, apscheduler maintains only the details of the currently running job. How can I make it to store all instances of a particular job?

A: If you want such extra functionality, add the appropriate event listeners to the scheduler to detect the adding and any modifications to a job. In the event listener, get the job from the scheduler and store it wherever you want. They are serializable btw.


text:
Q: If $x^x y^y z^z = c$, then the value of $\frac{\partial^2z}{\partial x \partial y}$ at $x = y = z$ is?
If $x^x y^y z^z = c$, then the value of $\frac{\partial^2z}{\partial x \partial y}$ at $x = y = z$ is?

I found a similar question on this site (If $x^y y^x z^z=c$, then find $\frac {\partial^2z}{\partial x \,\partial y}$ at $x=y=z$.). But the problem is, when I solve for Z , and take log both sides I get this $zln(z) = ln(c) - xln(x) - yln(y)$ Now if I partially differentiate it w.r.t. x, then y term vanishes (constant when differentiating w.r.t. x), and now again I partially differentiate w.r.t. y, then I get 0. Please help me to solve this question.


text:
Q: Laravel Carbon::today() method return previous day I have written a function to filter user and agent booked tickets based on date. This is basically an ticket booking application. In this user and agent can book different tickets, so in admin dashboard I am displaying the count of total number of tickets booked by user by today and vice versa for agents. Thus I do this using Carbon to verify with today date. But I am getting different kind of output !
Controller :
$ticketsTodayUsers = Booking::with('users')->where("createdAt", ">=", Carbon::today())->whereHas("users", function($subQuery){
    $subQuery->where("usertype", "=", "normal");
    })->get();

So in this I have two tables, booking and user table by which I am verifying tickets created today using carbon::today() with usertype as normal or agent.
But when I check today (19-sep-2018), I am getting counting result of yesterday (18-sep-2018 ). I am not getting the count of today, which is zero instead the count comes from yesterday or long back like 14-sep-2018. I don't know where I am doing wrong !
The main condition is that I need to separate user and agent bookings counts for each day , so by using createdAt filed from db and carbon today function I tried to match both. But I am not getting expected answer !

A: Try to use $tz parameter - TimeZone.
Carbon::today('Asia/Calcutta');

And try to use WhereData(), WhereDay():
->whereDay('createdAt', '=', date('d'))

or
->whereDate('createdAt', Carbon::today())

Of course with appropriate timezone
Booking::with('users')->whereDate('createdAt', Carbon::today('Asia/Calcutta')->toDateString())->whereHas("users", function($subQuery){
            $subQuery->where("usertype", "=", "normal");
        })->get();

A: Try with this:
$ticketsTodayUsers = Booking::with('users')
     ->whereDate("createdAt", ">=", Carbon::now()->toDateString())
     ->whereHas("users", function($subQuery){
         $subQuery->where("usertype", "=", "normal");
     })->get();

A: This helped me
$ticketsTodayUsers = Booking::with('users')->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->addHour()])->get();


text:
Q: Update column using Subquery I am trying to update eid of the pay table with  eid of payc table by joining payid .In the PayC table there are duplicate eid s' for matched payid s',Need to get only one EID for every  matched PAYID
update PAY
SET eid = (select t.EID from (select a.EID,a.PAYID, count(a.EID) as cnt
                                                       from PAYC a,PAYC b
                                                            where a.payid = b.payid
                                                            group by a.PAYID,a.eid
                                                            having count( a.eid) > 1) t
                                                            where  T.payid = PAYID)
WHERE EXISTS (select 'X' from (select a.EID,a.PAYID, count(a.EID) as cnt
                                                       from PAYC a,PAYC b
                                                            where a.payid = b.payid
                                                            group by a.PAYID,a.eid
                                                            having count( a.eid) > 1) t
                                                            where  T.payid = PAYID)

Error:Subquery returned more than 1 value.
This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
we can find duplicate EID by this query BUT NEED TO FETCH ONLY ONE EID
select a.EID,COUNT(a.PAYID), count(a.EID) as cnt
 from PAYC a,PAYC b
 where a.payid = b.payid
 group by a.PAYID,a.eid
 having count( a.eid) > 1 AND
 COUNT(a.PAYID) >1

sample data
paycid payid  eid  amount year  quarter
1       101  1000   2000  2001   1
2       101  1000   3000  2001   2

Need to fetch
eid
1000

for the matched payid

A: select top 1 * from stuff

may do.

A: Something like this might help?
WITH Duplicates AS (
    SELECT
        a.EID,
        a.PAYID,
        ROW_NUMBER() OVER (PARTITION BY a.PAYID ORDER BY a.EID) AS ROWID
    FROM
        PAYC a
        INNER JOIN PAYC b ON b.PAYID = a.PAYID
    GROUP BY
        a.EID,
        a.PAYID
    HAVING
        COUNT(a.EID) > 1)
UPDATE
    p
SET
    EID = d.EID
FROM
    PAY p
    INNER JOIN Duplicates d ON d.PAYID = p.PAYID AND d.ROWID = 1;

Although I have to admit that I don't understand the logic of your self-join from PAYC to PAYC.  Surely you don't need to do this to find cases where there are multiple EIDs per PAYID?  In which case you could just remove the INNER JOIN PAYC b line entirely?
After thinking about this some more, could you not simply do this?
WITH Duplicates AS (
    SELECT
        PAYID,
        MAX(EID) AS EID
    FROM
        PAYC
    GROUP BY
        PAYID
    HAVING
        COUNT(DISTINCT EID) > 1)
UPDATE
    p
SET
    EID = d.EID
FROM
    PAY p
    INNER JOIN Duplicates d ON d.PAYID = p.PAYID;

Then use MAX, MIN or whatever aggregation your require to pick the EID you want to use to update your PAY table (my example uses MAX).  This is why your original query didn't work, you didn't tell it which EID to use, and it was returning multiple values.


text:
Q: Samba server won't let other people modify file attributes I added this to /etc/samba/smb.conf.
[iTunes]
path = /home/myusername/iTunes
valid users = myusername
writable = yes

This has the desired effect, except that for some reason I can't edit file attributes:

I'm assuming this is because I need to add a certain setting to my configuration. How do I grant the necessary permissions to myusername?

A: I found the solution to my problem. It turns out the problem isn't related to Samba after all. Sorry. :)
How to Fix a Locked iTunes Library File
-- http://www.ihackintosh.com/2010/01/how-to-fix-a-locked-itunes-library-file-2/
I've paraphrased the answer here by request:

*

*Make sure iTunes is closed.

*Go to your iTunes folder and move the iTunes Library file to your desktop. (You might want to create a backup of all the files in the main folder if you're worried you're gonna lose data.)

*Launch iTunes. Your library should be empty.

*Restore your library by dragging the iTunes Library file from your desktop into the iTunes window. In the iTunes window that pops up, click Replace.

A: Why don't you try from nautilus graphical interface for sharing? You can found sharing option to right click on an item in nautilus.

When you check on "Allow others to create and delete files in this folder" then anyone can edit and delete files in network but they need to know your samba username and password.
When anyone try to access your content he/she will be asked for your samba username and password. If he/she know the authentication information then he/she can see,edit and delete your content you share.
If you uncheck "Allow others....." then other (who knows authentication info) only see and copy the content but can not create or delete content.
If you want that Any one in the network can  see your content the check the "Guest access ..." option. Where anyone can see the file without knowing your authentication information.
Add samba user in this file:
sudo gedit /etc/samba/smbusers

Format is  = . So you can map your ubuntu username with different username for samba but this is not necessary. Example: say, your username is abc then add this line to /etc/samba/smbusers
<abc> = "<abc>"

Thats means anyone can access with abc username. you can use different name on right side.
Now set password for samba abc user (not your ubuntu user) password.
sudo smbpasswd -a username  [abc]

A: The writeable attributes are ReadOnly, Hidden, System and Archive.
Remember that these attributes are exclusive to Windows partitions (NTFS and maybe FAT). Because of this, as far as I know, it's not possible to store this attributes on a Linux server running Samba.
In Linux (ext2, ext3 and ext4 filesystems), the nearest equivalent to each property is:
ReadOnly: file permissions
Hidden: files that start with a period (.)
System: there is no near equivalent to this one. In Linux, the system files usually reside on specific folders (/bin, /etc, /usr, etc.) and have root as owner. So, there is no such concept of system attribute.
Archive: this attribute is used by backup software to make incremental backups and indicates that the file changed since last backup. In Linux, the change time can be used to this purpose (it can be checked using stat program)


text:
Q: Use artifact from my local maven repo I have installed an artifact successfully into my local maven repository.
How do I add a dependency to this artifact in a second client maven project?
What would the POM file of the client look like?

A: It would be same as other dependency you are providing.
Let say you first project groupId is A.B.C.D ,artifactId is XYZ and version is 1.0,Then you just need to declare below line in the dependencies section of your second maven project,Maven will automatically find it from local repository.
   <dependency>
      <groupId>A.B.C.D</groupId>
      <artifactId>XYZ</artifactId>
      <version>1.0</version>
   </dependency>


text:
Q: Iterate Foregin key options and assign it to each row in inlineformset I have an inline formset where I need to assign the values of a ForeignKey field sequencially and univocally to each row of the inline formset. With the select default widget of a modelchoicefield everything works but I do not want the user to select any options but to be provided with a list of the options available in the foreignfield.
My inlineformset is the following:
class ResultadoForm(forms.ModelForm):
    frequencia = forms.CharField(max_length=50)
    tolerancia = forms.CharField(max_length=255)
    def __init__(self, *args, **kwargs):
        equipamento_id = kwargs.pop('equipamento_id', None)
        super (ResultadoForm, self).__init__(*args, **kwargs)
        self.fields['teste'].queryset = Teste.objects.filter(equipamento=equipamento_id).order_by('grupoteste', 'numeracao')

    class Meta:
        model = Resultado
        exclude = ['actividade']

My view that renders the form:
@login_required()
def QAView(request, equipamento_id):

    form = ActividadeForm()
    form1 = ResultadoForm(equipamento_id)
    equipamento = Equipamento.objects.get(id=equipamento_id)
    testes_list = Teste.objects.filter(equipamento=equipamento_id)
    FormSet = inlineformset_factory(Actividade, Resultado, form=ResultadoForm, fields='__all__', extra=len(testes_list))
    formset = FormSet(form_kwargs={'equipamento_id': equipamento_id})
    context = {'equipamento_id': equipamento_id, 'data':datetime.now(), 'equipamento': equipamento, 'form': form, 'testes_list': testes_list, 'formset': formset}
    template = 'SFM/Equipamento/QA.html'

return render(request, template, context)

And in my template:
{% for r in formset %}
{{ r.id }}
{% for t in r.teste.field.queryset %}

        {{ t}}
        {{ t.frequencia }}
        {{ t.tolerancia }}
        {{ r.conforme }}

{% endfor %}
{% endfor %}

My Resultado Model:
class Resultado(models.Model):
    CONFORME_CHOICES = (
    ("Sim", "Sim"),
    ("Não", "Não"),
    )

    teste = models.ForeignKey(Teste, null=True, blank=True, on_delete=models.CASCADE)
    conforme = models.CharField(max_length=30, choices=CONFORME_CHOICES)
    actividade = models.ForeignKey(Actividade, null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
    return str(self.id)

With this template I get 4 rows. I should only get two. But I have two foreign key options so I am getting the two foreign options repeated.
Is it possible to assign one and only one foreign key to each row of this inlineformset? For example for the first row automatically assign the first foreign value and to the second row the second foreign value. Please help.


text:
Q: How to remove the list of values from JSON object to another JSON object using jQuery I have two JSON Objects:
var A = { 'Header','Quotes','Returns','Indent','Basic',...,'Placing' }
var B = { 'Header','Quotes','Returns','Indent',... }

A and B share the same elements, Header, Quotes, Returns and Indent and so I need to remove them using jQuery.
A's Final Output should be:
A = { 'Basic','Placing',... }

A: You can use merge function:
var A={'Header','Quotes','Returns','indent','Basic','Placing'}
Var B={'Header','Quotes','Returns','indent'}
var C = $.merge(A, B);
Regards


text:
Q: Am programming in angularJs what ever data entered in text box it bind till service .JS file but it binding at controller.cs file Cotroller.cs    file code
public string AddCategory(Category category)
        {
            if (category != null)
            {
                category.Active = true;
                db.Categories.Add(category);
                db.SaveChanges();
                return "Category Added";
            }
            else
            {
                return "Invalid Record";
            }
        }

Service.js   file code
this.addCategory = function (category) {
    var response = $http({
        methode: "POST",
        url: "AddCategory",
        data: JSON.stringify(category),
        dateType: "json"

    });
    return response;
}

Controller.js   file code
$scope.AddUpdateCategory = function () {
    var category = {
        CategoryID: $scope.CategoryID,
        CategoryName: $scope.CategoryName,
        BusinessTypeId: $scope.BusinessTypeId,
        CategoryDesc: $scope.CategoryDesc,
        CompanyId: $scope.CompanyId
    };
    var getAction = $scope.Action;

    if (getAction == "Update") {
        category.CategoryID = $scope.CategoryID;
        var getData = angularService.updateCategory(category);
        getData.then(function (msg) {
            //GetAllCategory();
            $('#AddCategoryDiv').hide();
            $('.modal-backdrop').hide();
            swal("Success!", msg.data, "success");

        }, function () {
            sweetAlert("Oops...", "Error in Updating Category!", "error");
        });
    }
    else {
        var getData = angularService.addCategory(category);
        getData.then(function (msg) {
            //GetAllCategory();
            $('#AddCategoryDiv').hide();
            $('.modal-backdrop').hide();
            swal("Success!", msg.data, "success");

        }, function () {
            sweetAlert("Oops...", "Error in Adding Category!", "error");
        });
    }
}
$scope.AddCategoryDiv = function () {
    clearFields();
    $scope.Action = "Add";

}
function clearFields() {
    $scope.CategoryID ="";
    $scope.CategoryName = "";
    $scope.BusinessTypeId = "";
    $scope.CategoryDesc = "";
    $scope.CompanyId = "";
}

please suggest solution ,
the data is not updated in database.
what ever data entred in text box that not saved in database.
i need to store the category in database


text:
Q: Ubuntu 20.04 syslog warnings on suspend Recently I've noticed that when I suspend my laptop it shows what I think to be a systemd window (could be a TTY, I'm not sure)- juts a black screen with a coursor flickering. The problem is that after returning from suspend mode it shows there some warnings related to wifi. The wifi itself is working fine and the warning is not important one. However this is a little annoying as if you suspend it several times per day you can see a column of text before the login screen pops-up.
I've never see that behavior before with 18.04. Does someone know if this is normal? Is it possible to "skip" this screen?
Thank you.

A: That actually was syslog kernel messages and there's a deafult way to disable them to prevent spamming your console and apearing each time before you login, for example.
You just need to modify this file /etc/sysctl.confdoing the following:
    # Uncomment the following to stop low-level messages on console
      kernel.printk = 3 4 1 3

The line is commented by default. Removing the comment stops low-level messages from appearing in the console, e.g. console blinking before login screen appears as happens when laptop returns from suspend mode.
The message are perfectly available via dmesg or logged in journalctl so you can check them late if you need. The high-level messages will still appear.
That makes it estetically better as I do not want to see a lot of warning spam from my wifi each time I suspend my laptop. Besides I have a habit to check error log from tiem to time, so it works fine for me.
Found the solution there How to stop kernel messages from flooding my console?


text:
Q: Shopify Liquid: output variable to a .js file I have a custom.js.liquid file under my assets folder, and I have added this line to theme.liquid.
<script src="{{ 'custom.js' | asset_url }}" defer="defer"></script>

I am trying to output a product's title to javascript, in custom.js.liquid, I put
console.log({{ all_products['absolut-vodka'] | json }});

This line can't be recognized by the .js.liquid file. In frontend, in the custom.js file it becomes
console.log(null);

On the other hand, if I put
<script>console.log({{ all_products['absolut-vodka'] | json}});</script>

in the theme.liquid file, it can output the correct object.
What did I do wrong?

A: Asset files are resources that Shopify strongly caches. This means that you cannot access any Liquid variables that might be change from page to page, customer to customer, etc.  Product details can be updated at any arbitrary time by yourself or an app, so this also falls under the category of things that are not available in your asset files.
Inside your .js.liquid file, the main things you have access to are:

*

*Translation settings

*Theme settings

... and that's about it. It may be worth noting that theme and language settings are both located with your theme files, and this may have something to do with Shopify's decisions around these Liquid restrictions
If you want to get the product details for your absolut-vodka product, you can use Shopify's storefront API to get the details you need. (eg: by fetching /products/some-product-handle.js). For example:
function getProductThenDoStuff(productHandle, callbackFunction){
  fetch('/products/' + productHandle + '.js')
    .then(function(response){ return response.json() })
    .then(callbackFunction)
}


text:
Q: Sharing data between two instances in a load balanced java web application I want to cache data in a java web application deployed on multiple instances. We are using spring 2.5.6. What is the easiest caching library to configure and use with spring? I have heard of EH Cache, but the configuration is too cumbersome.
The requirement is that a spring scheduler will run and set some flags. These flags are accessible from all load balanced instances. But since the scheduler runs only on one instance the flag is set only on that jvm. So how do i make these updated flag values available to all load balanced instances?

A: We went from EHCache to Memcached. It's much easier to both configure and implement.


text:
Q: Backward Converting SQL Databases Does anyone know of any free tools that can assist in converting an SQL2005 database back to SQL2000 format?  I know that you can script all the objects and then do a dump of the data, but this is a lot of work to do manually.

A: Reviewing some other related questions I just found Microsoft's Database Publishing Wizard.  It does most of what I need, although I have used nVarChar(max) in a couple of places and it simply fails to handle those cases and bombs out without generating anything.

A: Have you considered using DTS to transfer the data across? It should be independant of the version.


text:
Q: Run a python file using another Note:- Wait before you mark my question as duplicate please read it completely.
I wan't to run a python file using another.
I have tried using runpy,os.system & subprocess. The problem with subprocess and os.system command is that it fails for systems which have python2 and python3 both installed if i just run with python. If i run it with python3 i fails for people having single installation.
The problem with runpy is that it does not work according to my needs.
The following is run my directory structure
test\
   average\
       average.py
       average_test.py
   many similar directories like average...
   run_tests.py

The content of average is
def average(...args):
     # Do something

The content of average_test.py
from average import average
def average_test():
    assert average(1,2,3) == 2

Now if i use runpy.run_path it throws a ImportError saying average is not a module. The os.system and subprocess.call works perfectly but I hope my "testing_framework" will be used by many so I can't use the above two functions. Isn't there any other way to do it. I have researched the whole of SO and google but didn't find a solutions.
Also sys.path.append/insert will not help as I can't tell my "users" to add this to every file of theirs.
Is there no easy way to do it? I mean like pytest accomplishes this so there must be a way.
Thank you moderators for reading my question.
EDIT I forgot to mention that I wan't the code to be run in if __name__ == '__main__' block too and I have also tried using a snippet from another SO answer which fails too. The snippet was
def exec_full(filepath):
    global_namespace = {
        "__file__": filepath,
        "__name__": "__main__",
    }
    with open(filepath, 'rb') as file:
        exec(compile(file.read(), filepath, 'exec'), global_namespace)

Please note that the directory structure was just an example the user may have a different code/directory structure.
NOTE:- I found the answer. I needed to do subprocess.call([sys.executable,file_path]). sys.executable returns the path for the python executable file for the current version.

A:

    Create an empty __init__.py in average folder
    And then try to import

    from average import average

    it would work like charm :)

    test\
       average\
           average.py
           average_test.py
           __init__.py
       many similar directories like average...
       run_tests.py


text:
Q: github-like svn checkout from git GitHub provide an svn interface to git, explained here:
https://github.com/blog/966-improved-subversion-client-support
Is there a similar solution I can deploy on my self-hosted repositories? Is it open source?

A: Have a look at SubGit.
One can install SubGit into Subversion repository and use both Subversion and Git. Note that since version 2.0 SubGit is able to synchronize SVN and Git repositories that reside on different hosts.
SubGit is a commercial tool; it's free for open source, academic and small projects. SubGit 2.0 is free as long as it's in EAP stage.
Disclaimer: I'm one of SubGit developers.


text:
Q: What is the meaning of the error rate in Neural networks? I'm a beginner with neural networks. I get that the error should be low. But what does that number really mean?
I created a simple neural network which has a error of 1.5. Is that too high? What are the consequences?

A: The error basically signifies how well your network is performing on a certain (training/testing/validation) set. Having a low error is good, will having a higher error is certainly bad. The error is calculated through a loss function, of which there are several.
One of these for example is the Mean Squared Error, which will calculate the distance between the wanted input and the real input, and squaring this value.
So if your network is outputting [0.5] for example, but you want it to output [0]. Your error will be (0.5 - 0)^2 = 0.25. But this error is just used to signify how well the network is performing.
During backpropagation, the network uses something called error responsibility through which it calculates how much it should change connection weights and biases.
About your 1.5 error: this is fairly high! Normally, your error should be between 0 and 1. A 'good' error is anywhere between 0 and 0.05.

A: The error is a measure of the difference between what the ANN predicts and the real Label of data.
for example for a simple "And" inputs and label(output) is like:
input1-input2-output
  0          0          0
  0          1          0
  1          0          0
  1          1          1
if for example, the network predicts 1 for inputs 0 and 0 it's wrong and it will be added to the Error.
so basically Error is a measure showing how much the network is Wrong!


text:
Q: How can we get sockets list from select() function? I'm working on a network project and I know select() function (with FD_XXX) returns the total number of socket handles that are ready and contained in the fd_set structures but do we know these sockets (as SOCKET or INT)? There is only way to get sockets list with a FOR LOOP-CHECK FD_ISSET, Am I right? else how?

A: Despite what others say about the return value of select(), I use it this way when dealing with a lot of sockets, it does not guarantee that you don't have to process all the list in case the only one socket happens to be the last one but would save some code if it's the first one.
int i;
int biggest=0;
fd_set sfds;
struct timeval timeout={0, 0};

FD_ZERO(&sfds);
for (i=0; i < NumberOfsockets; i++)
{
    FD_SET(SocktList[i], &sfds);
    if (SocktList[i] > biggest) biggest=SocktList[i];
}

timeout.tv_sec=30;
timeout.tv_usec=0;

// biggest is only necessary when dealing with Berkeley sockets,
// Visual Studio C++ (and others) ignore this parameter.
if ((nReady=select((biggest+1), &sfds, NULL, NULL, TimeOut)) > 0)
{
   for (i=0; i < NumerbsOfSocket && nReady > 0; i++)
   {
      if (FD_ISSET(SocketList[i], &sfds)) {
         // SocketList[i] got data to be read
         ... your code to process the socket when it's readable...
         nReady--;
      }
   }
}


text:
Q: Scrapy creating XML feed wraps content in "value" tags I've had a bit of help on here by my code pretty much works. The only issue is that in the process of generating an XML, it wraps the content in "value" tags when I don't want it to. According to the doc's this is due to this:

Unless overriden in the :meth:serialize_field method, multi-valued
  fields are    exported by serializing each value inside a <value>
  element. This is for    convenience, as multi-valued fields are very
  common.

This is my output:
<?xml version="1.0" encoding="UTF-8"?>
<items>
   <item>
      <body>
         <value>Don't forget me this weekend!</value>
      </body>
      <to>
         <value>Tove</value>
      </to>
      <who>
         <value>Jani</value>
      </who>
      <heading>
         <value>Reminder</value>
      </heading>
   </item>
</items>

What I send it to the XML exporter seems to be this, so I don't know why it think's it's multivalue?
{'body': [u"Don't forget me this weekend!"],
 'heading': [u'Reminder'],
 'to': [u'Tove'],
 'who': [u'Jani']}

pipeline.py
from scrapy import signals
from scrapy.contrib.exporter import XmlItemExporter

class XmlExportPipeline(object):

    def __init__(self):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
         pipeline = cls()
         crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
         crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
         return pipeline

    def spider_opened(self, spider):
        file = open('%s_products.xml' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = XmlItemExporter(file)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

spider.py
from scrapy.contrib.spiders import XMLFeedSpider
from crawler.items import CrawlerItem

class SiteSpider(XMLFeedSpider):
    name = 'site'
    allowed_domains = ['www.w3schools.com']
    start_urls = ['http://www.w3schools.com/xml/note.xml']
    itertag = 'note'

    def parse_node(self, response, selector):
        item = CrawlerItem()
        item['to'] = selector.xpath('//to/text()').extract()
        item['who'] = selector.xpath('//from/text()').extract()
        item['heading'] = selector.xpath('//heading/text()').extract()
        item['body'] = selector.xpath('//body/text()').extract()
        return item

Any help would be really appreciated. I just want the same output without the redundant  tags.

A: The extract() method will always return a list of values, even if there is only a single value as a result, for example: [4], [3,4,5] or None.
To avoid this, if you know there is only one value, you can select it like:
item['to'] = selector.xpath('//to/text()').extract()[0]

Note:
Be aware that this can result in an exception thrown in case extract() returns None and you are trying to index that. In such uncertain cases, this is a good trick to use:
item['to'] = (selector.xpath('...').extract() or [''])[0]

Or you could write your custom function to get the first element:
def extract_first(selector, default=None):
    val = selector.extract()
    return val[0] if val else default

This way you can have a default value in case your desired value is not found:
item['to'] = extract_first(selector.xpath(...))  # First or none
item['to'] = extract_first(selector.xpath(...), 'not-found')  # First of 'not-found'

A: The above answer is correct regarding why this is happening, but I'd like to add that there is now out of the box support for this, and no need to write a helper method.
item['to'] = selector.xpath('//to/text()').extract_first()

and
item['to'] = selector.xpath('//to/text()').extract_first(default='spam')


text:
Q: Angular 2: show/hide div on app's main template from different components I have an Angular 2 app with several components:
- app
  - sidebar-panel
  - main-panel
     - obj-container (1)
     - obj-container (2)
     - (etc)
  - footer-panel

Basically, what I'd like is to show/hide the footer panel dinamically:

*

*When I double click on any of the objects inside 'obj-container' it should become visible. I want to do it from the handler of the Angular 'dblclick' event, inside each 'obj-container' component code.

*Inside its HTML template, the footer panel should have a close button to hide it.

*It'd be nice if both show/hide actions had an animation effect like jÇuery 'slideToggle' method.

In the template of 'app' component', the footer panel is inserted like this:

  <app-footer-panel></app-footer-panel>

For now, the only way I think I can do this is by creating a variable on 'app' component and bind an *ngIf in the footer div to hide it or show it depending on its value. And, on each 'obj-container' component, create an @Output event that fires each time the user clicks on the close button and is captured by the parent 'app' component to modify the div visibility.
But, I think that this solution is too complicated, and also I miss the jQuery animation effect (although is not necessary, I'd like to know if I can get it).
Any ideas? Thanks,

A: You are already on a good track with *ngIf. You can show and hide your footer with *ngIf. Like:

and toggle showFooter value on dblclick on other components' buttons and footer closing button. To pass it from parent component to the footer(child) component, look Angular sources here. Hint : @Input() is what you will need.
And for the animations, Angular has all you need : here


text:
Q: How to match on multiple fields per array item in elastic search I am trying to create an elastic search query to match multiple fields inside of an object inside of an array.
For example, the Elastic Search structure I am querying against is similar to the following:
"hits": [
            {
                "_index": "titles",
                "_type": "title",
                ...
                "_source": {
                    ...
                    "genres": [
                        {
                            "code": "adventure",
                            "priority": 1
                        },
                        {
                            "code": "action",
                            "priority": 2
                        },
                        {
                            "code": "horror",
                            "priority": 3
                        }
                    ],
                    ...
                },
                ...
        ]

And what I am trying to do is match on titles with specific genre/priority pairings. For example, I am trying to match all titles with code=action and priority=1, but my query is returning too many results. The above title is hit during this example due to the fact that the genre list contains both a genre with code=action AND another genre that matches priority=1. My query is similar to the following:
    "query": {
        "bool": {
            "filter": [
                {
                    "bool": {
                        "must":[
                            {"term": {
                                    "genres.code": {
                                        "value": "action",
                                        "boost": 1.0
                                    }
                            }},
                            {"term": {
                                    "genres.priority": {
                                        "value": 1,
                                        "boost": 1.0
                                    }
                            }}
                        ]
                    }
                },
                ...
            }

Is there any way to form the query in order to match a title with a single genre containing both priority=1 AND code=action?

A: I have recreated your problem. I added the following mapping
PUT titles
{
  "mappings": {
    "title": {
      "properties": {
        "author": {
          "type": "text"
        },
        "genres": {
          "type": "nested"
        }
      }
    }
  }
}

Then I added values to the index. This was what was inserted
  "hits": {
    "total": 3,
    "max_score": 1,
    "hits": [
      {
        "_index": "titles",
        "_type": "title",
        "_id": "2",
        "_score": 1,
        "_source": {
          "author": "Author 1",
          "genres": [
            {
              "code": "adventure",
              "priority": 2
            },
            {
              "code": "action",
              "priority": 3
            },
            {
              "code": "horror",
              "priority": 1
            }
          ]
        }
      },
      {
        "_index": "titles",
        "_type": "title",
        "_id": "1",
        "_score": 1,
        "_source": {
          "author": "Author 2",
          "genres": [
            {
              "code": "adventure",
              "priority": 3
            },
            {
              "code": "action",
              "priority": 1
            },
            {
              "code": "horror",
              "priority": 2
            }
          ]
        }
      },
      {
        "_index": "titles",
        "_type": "title",
        "_id": "3",
        "_score": 1,
        "_source": {
          "author": "Author 3",
          "genres": [
            {
              "code": "adventure",
              "priority": 3
            },
            {
              "code": "action",
              "priority": 1
            },
            {
              "code": "horror",
              "priority": 2
            }
          ]
        }
      }
    ]
  }

My query is:
GET titles/title/_search
{
  "query": {
    "nested": {
      "path": "genres",
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "genres.code": {
                  "value": "horror"
                }
              }
            },
            {
              "term": {
                "genres.priority": {
                  "value": 1
                }
              }
            }
          ]
        }
      }
    }
  }
}

The query returns
        "_source": {
          "author": "Author 1",
          "genres": [
            {
              "code": "adventure",
              "priority": 2
            },
            {
              "code": "action",
              "priority": 3
            },
            {
              "code": "horror",
              "priority": 1
            }
          ]
        }

This title is the only one that has code = 'horror' and priority = 1.


text:
Q: BASH Curl - "bash: !: event not found" I have a curl command as follows which can contain a password. The password can contain special characters. !£$%^&#-~@ etc.
curl d "valuea=1234&password=1234@!&valuec=87979&submit=Set" -XPOST "http://$ipa/school.cgi"

When this is run I get:    bash: !: event not found
How do I escape the special characters in the URL string ?
Thanks


text:
Q: How can i show my own Google map with placemark labels? I created a map with Google Maps, for my guests.
I need to show road names and directions. Google maps shows it well.
But i also need to show the labels of placemarks.
So they can know the name of the places.
Google Earth can show it.
But (even i only select Roads as layer), it is not readable for a street walker.
How can i combine street names (map view) + placemark labels?
Thank you

A: Google Maps itself, cant do it.
http://www.gpsvisualizer.com/ might help - that can plot a Google based Map, and plot labels.


text:
Q: Can I add a process to every component's ngOnInit and OnDestroy? I have an observable that I need to bind and remove on every component.
Is it possible to write the subscribe/unsubscribe logic somewhere and have it implicitly included in every component?
Like a middleware on the creation/destruction of a component
Here is an example of what I'd like to see:
https://i.imgur.com/K8XtaFv.png
edit: yurzui gave me the idea to use super.ngOnInit()
Not as clean as I'd like, but hey - it works.
import { Component, OnInit, OnDestroy } from '@angular/core';

export class ExtendHooks {
  ngOnDestroy() {
    console.log("Want this to fire first")
  }

  ngOnInit() {
    console.log('Want to fire first')
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends ExtendHooks implements OnInit, OnDestroy {

  constructor(){
    super()
  }

  ngOnDestroy() {
    super.ngOnDestroy()
    console.log("Want this to fire second")
  }

  ngOnInit() {
    super.ngOnInit()
    console.log("Want to fire second")
  }
}

A: Try router lifecycle hooks navigationstart and navigationend


text:
Q: How can I change non-numerical data to numerical values by using "if condition"? I would like to change non-numerical data to numerical values in one column. I tried to use factorize; pd.factorize(df['Class'])[0] + 1. However, it separates the 'Class' column from the actual matrix (y1 matrix). Then, I also used pd.get_dummies(). But, it gave only 1 and 0 value for each different non-numerical value.
My question is, is there any way to change non-numerical data to numerical values starting from 1 to 4 in my case, for the data in one column? or any other suggestions that you would like to give.
In the 'Class' data, I have one column. 356 rows. The cells contain N, O, P and S letters.
Thank you very much for any help.
def my_function(y1):
    if y1 == "N":
        convert = 1,
    elif y1 == "A":
            convert = 2,
        elif y1 == "O":
                convert = 3,
                else:
                    convert = 4
    return convert

A: Something like the following can be easily extended by changing the dict A.
I've defined A outside of the function my_function() to prevent a static array to be created over and over again.
A = { 'N' : 1, 'A' : 2, 'O' : 3 }

def my_function(y1):
    global A
    if (y1 in A):
        return A[y1]
    return 4

print(str(my_function('N')))
print(str(my_function('X')))
print(str(my_function('A')))

But maybe I'm missing the question all together.
It works both for Python2 and Python3

A: I think what you want is Label Encoding,
So,
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(["N", "O", "P", "S"])
>>> LabelEncoder()

le.transform(["N", "N", "P", "O", "S", "O"]) + 1
>>> array([1, 1, 3, 2, 4, 2])

For a column in a dataframe,
df['Class'] = le.fit_transform(df['Class']) + 1

Note, fit_transform is used for fitting and transform at the same time, if the data can have missing classes, then a separate fit is required specifying the actual classes.


text:
Q: pass the password as an argument in pssh I am trying to write a script which will run commands on multiple machines with pssh.
Is there any way to pass the password also in the same command line like below:
$ pssh -h pssh-host.txt -l root -A "pswd" echo "hi"
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
Password:

Tried following solution:
sshpass -pabc pssh -h pssh-host.txt -l root -A echo "hi"
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
[1] 13:55:56 [SUCCESS] x
[2] 13:55:56 [SUCCESS] y

I do not want this Password: prompt. Can someone suggest a way for this?

A: Crossposting an answer by user568109 on Unix SE as Community Wiki:

Found the solution on net not long after posting the question.
The solution is:

*

*Install and use sshpass

*Use interactive mode to force the password which is just an empty string

*Used command cat local | sshpass -ppassword parallel-ssh -I -h new_hosts -l root -A 'cat >> remote'
Original solution at:
  http://www.getreu.net/public/downloads/doc/Secure_Computer_Cluster_Administration_with_SSH/


text:
Q: Error installing llvm and clang from source in Linux I am trying to  install clang from source following the instructions as given in http://clang.llvm.org/get_started.html ( Steps 1-4 and 7) in Ubuntu 14.04
Inside the build directory , I ran make which succeeded. I wasn't sure what to do after that , so I ran make install inside the build directory, following which I got this cmake error:

There is no executable named clang in /build/bin folder anyway, but I can find others like clang-check, clang-query, etc. What's going wrong?
PS: My main requirment is to experiment with alpha security checkers of clang analyzer and also write my own checker later.


text:
Q: how to find the number of different arrangements when a coin is thrown 12 times and gets 5 heads Suppose a fair coin which has 2 faces-Head(H) and Tail(T) is thrown 12 times and
we get exactly 5 heads:
  $$H,H,H,H,H,T,T,T,T,T,T,T$$
How can I find the number of different arrangements it can have?
One possible arrangement:
$$H,T,T,H,T,T,H,H,T,T,T,H$$
Another possible arrangement:
$$ H,H,H,T,T,T,T,T,T,T,H,H$$
I can find the probability of getting exactly 5 heads by using binomial distribution but i cannot find the actual number of arrangements.

A: It is the binomial coefficient $\binom{12}{5}$, i.e., $\dfrac{12!}{5!(12-5)!}$.  This corresponds to the number of different ways of placing the $5$ heads in the $12$ positions.


text:
Q: Making full use of memory on graphic cards Onboard graphics cards often reserve some of the system main memory for their own use.
For a computer with a separate graphics card which has its own memory, is this possible that some of it be borrowed and used like system main memory?
Running typical desktop applications normally require much more system main memory than memory on the graphics card. If the OS is smart enough to dynamically allocate some of it when it's low on main memory and release it back to the graphics card when necessary, this will be great.

A: It is possible to use some of it as swap or ramdisk under Linux, but most operating systems do not allow this.


text:
Q: Trouble getting user data inside vue-router from composition I'm very new to vue.js, I am currently working on my final assignment for university.
I'm trying to get information of my user into my router, this works fine on my usual pages/components, but the techniques used on those files don't seem to work here. I've tried reading through some of the documention for router and composition, but I can't seem to figure out where I'm going wrong. This is my latest attempt as earlier I was not using setup() and getting the error; inject() can only be used inside setup() or functional components.
The problem is occuring with "useAuth," I'm not getting any data, my console.log(isAdmin) is displaying 'undefined,' this should be a boolean true/false.
Router code:
import { createWebHistory, createRouter } from "vue-router";
import Dashboard from "../pages/DashboardSDT.vue";
import Events from "../pages/EventsSDT.vue";
import Results from "../pages/ResultsSDT.vue";
import Admin from "../pages/AdminSDT.vue";
import Settings from "../pages/SettingsSDT.vue";
import Login from "../pages/LoginSDT.vue";
import Register from "../pages/RegisterSDT.vue";
import { getAuth } from "firebase/auth";
import useAuth from "../composition/useAuth";

const routes = [
    {
        path: "/",
        name: "Dashboard",
        component: Dashboard
    },
    {
        path: "/Events",
        name: "Events",
        component: Events
    },
    {
        path: "/Results",
        name: "Results",
        component: Results
    },
    {
        path: "/Admin",
        name: "Admin",
        component: Admin,
        meta: { onlyAdminUser: true }
    },
    {
        path: "/Settings",
        name: "Settings",
        component: Settings,
        meta: { onlyAuthUser: true }
    },
    {
        path: "/Login",
        name: "Login",
        component: Login,
        meta: { onlyGuestUser: true }
    },
    {
        path: "/Register",
        name: "Register",
        component: Register,
        meta: { onlyGuestUser: true }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, _, next) => {
    const isAuth = !!getAuth().currentUser;
    const isAdmin = useAuth.admin;
    console.log(isAdmin)

    if (to.meta.onlyAuthUser) {
        if (isAuth) {
            next()
        } else {
            next({ name: "Login" })
        }
        // } else if(to.meta.onlyAdminUser) {
        //     if(isAdmin) {
        //         next()
        //     }
        //     else {
        //         next({name: "BasicUser"})
        //     }
    } else if (to.meta.onlyGuestUser) {
        if (isAuth) {
            next({ name: "Dashboard" })
        } else {
            next()
        }
    } else {
        next()
    }
})

export default {
    setup() {
        return {
            ...useAuth()
        }
    },
    ...router
}

useAuth code:
import { useStore } from 'vuex'
import { computed } from 'vue'

export default function useAuth() {
    const store = useStore();
    const { state } = store;

    const error = computed(() => state.user.auth.error);
    const isProcessing = computed(() => state.user.auth.isProcessing);
    const isAuthenticated = computed(() => store.getters["user/isAuthenticated"]);
    const user = computed(() => state.user.data);
    const admin = computed(() => state.user.data.admin);

    return {
        error,
        isProcessing,
        isAuthenticated,
        user,
        admin
    }
}

A: vue-router's index file is not like a vue component file and does not have a setup() function.  I've never tried but it's unlikely you can use composable functions either, especially when using vue composition API functions like computed()
You can however import the vuex store and access all it's state, getters, etc. like you want.
import store from '/store/index.js'; // or wherever your store lives

Then inside your router guard
const isAuthenticated = store.getters["user/isAuthenticated"];
const isProcessing = store.state.user.auth.isProcessing
// ...etc


text:
Q: How to inject Angular 2 components at different DOM nodes on a plain JavaScript page? Use-case: A client wants to build a library that consist of Angular 2 components but exposes abstracted, technology-agnostic interface to the end user (developer) of that library, so that those users might be using plain JavaScript and not be aware of the internals of the library.
The difficulty comes from the following:

*

*There is a page, which uses plain JavaScript. This page is developed by third-party.

*The third-party should be able to insert given Angular 2 component at specific places (DOM nodes) on the page.

*Let's say the component is <mg-input> and it should be shown in the header of the plain JavaScript page, but not only there - also in a form down the page. Two different places, two different DOM nodes which have between them plain html.

The question: How do we bootstrap component at specific DOM node and how do we pass configuration (not primitives but a complex object) to those components?
In the React world this is done simply by running ReactDom.render(domEl, <CustomInput nonPrimitiveConfig={config}/>) and depending on what domEl и config is, the component will be rendered in different places with different config.
How to do this in Angular 2?

A: You should be able to use Angular Elements to accomplish this. Angular Elements allows you to create a class that can be registered with most popular browsers as a custom element. The custom element can then be used just like any other DOM element, and includes Angular binding and change detection.
Check this out for more details:
https://angular.io/guide/elements
Edit:
This functionality only exists for Angular 6+. If you are required to use Angular 2, this is not an option.

A: Maybe ask why they want Angular 2 components specifically?
We've coded a standalone "widget" consisting of a javascript API, UI and styling. The developer of an app calls a javascript function to trigger it.
Everything the dev needs is packaged with zero library dependencies.
Your alternative is to rather develop the components minus the UI (e.g. closures/SEF). The client app can then use whatever tech they want for the UI.

A: This is not possible with Angular until Custom Elements is added (which was announced Q4 2017 but the github repo has been archived for some reason, so I'm not sure if CE will continue to be developed).
What you could do is use Stencil to build your components. They are very similar (use typescript) to how you build components in Angular - such components can then be loaded by Angular itself (with some basic config) or any other framework or even in just a plain vanilla HTML/JS setup.
For example, here is a basic Stencil component.
The major difference to angular is that there is no separate template HTML file, but instead it uses JSX to render the template.
The 3rd party would be able to insert these components at a specific place.
Your developers could add the components to an Angular project for whatever purpose you need them to be in Angular.


text:
Q: Conditional formatting of .xlsx by 'Does not contain [text]' in R-package "openxlsx" I want to use the R-package 'openxlsx' to do conditional formatting of a .xlsx file, but I can't figure out how to format a cell if the value does NOT contain a certain textstring.
In the following example (which works perfectly) i am formatting the cells which contains the string "OK" (but my goal is to format everything else):
library(openxlsx)

style <- createStyle(fontColour = '#9C0006', bgFill = '#FFC7CE')
wb    <- openxlsx::loadWorkbook('myFile.xlsx')
openxlsx::conditionalFormatting(wb, 'Sheet1', cols = 3:7, rows=1:100, type = 'contains', rule= 'OK', style = style)
openxlsx::saveWorkbook(wb, 'myFile.xlsx')

When looking at the documentation for openxlsx i see that operators are allowed in the rule-argument, so i tried the following:
openxlsx::conditionalFormatting(wb, 'Sheet1', cols = 3:7, rows=1:100, type = 'contains', rule= '!=OK', style = style)

This still does not work, as it seems the operators are only usable when type is set to 'expression'.
It seems to me that I might be missing something very small and easy, but I have had no luck figurering out what that might be, so hopefully someone has an idea (or can tell me that it just isn't possible to do it the way I intend to)

A: The new development version has the listed features implemented. I hope it works for you. Added features for conditionalFormatting to support also 'contains not', 'begins with' and 'ends with'

A: Since r2evans so kindly explained to me that the function I was seeking was not available I created a workaround. It might not be pretty but it did the simple job I was trying to do.
What I did was I formatted the entire workbook the way I wanted the cells NOT containing "OK" to be formatted,  and then "unformatted" (formatted back to the standard format) all the cells containing "OK".


text:
Q: Android multiple dialogs to one OnClickListener Is it possible to assign a single OnClickListener to one AlertDialog?
Here is the dialogs itself:
        AlertDialog.Builder dialog1 = new AlertDialog.Builder(PrefActivity.this);
        dialog1.setTitle("Dialog 1");
        dialog1.setPositiveButton("ok" , myListener);

        AlertDialog.Builder dialog2 = new AlertDialog.Builder(PrefActivity.this);
        dialog2.setTitle("Dialog 2");
        dialog2.setPositiveButton("ok" , myListener);

And here is the listener:
        DialogInterface.OnClickListener myListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (???){
                    case dialog1:
                    break;

                    case dialog2:
                    break;
                }
            }
        };

What should I write in those switch-case statement to correctly determine which dialog was picked?

A: Don't show the dialog directly, build a dialog and assign it to a variable like:
dialog1 = new AlertDialog.Builder(PrefActivity.this);
dialog1 = builder1.create();
dialog2 = new AlertDialog.Builder(PrefActivity.this);
dialog2 = builder2.create();

set the same listners
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
      if(dialog == dialog1){
            //Dialog 1
      } else if(dialog == dialog2) {
            //Dialog 2
      }
 }

A: 1.Simply create a new class i.e myListener and implement  DialogInterface.OnClickListener interface
2.Create constructor with int argument
3.Pass reference of a new  class instead of interface and pass int argument which will be later use in switch statemnt i.e dialog.setPositiveButton("OK",new myListener(int))
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static int dialog1 = 1;
static int dialog2 = 2;
Button button, button2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener(this);
    button2.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    if (view == button) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Dialog 1");
        builder.setMessage("this is first dialog");
        builder.setPositiveButton("ok", new myListener(dialog1));
        builder.show();
    }
    if (view == button2) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Dialog 2");
        builder.setMessage("this is second dialog");
        builder.setPositiveButton("ok", new myListener(dialog2));
        builder.show();
    }
}

class myListener implements DialogInterface.OnClickListener {
    int dialogNo;

    public myListener(int dialogNo) {
        this.dialogNo = dialogNo;

    }

    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        switch (dialogNo) {
            case 1:
                Toast.makeText(MainActivity.this, "Dialog first", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(MainActivity.this, "Dialog second ", Toast.LENGTH_SHORT).show();
                break;
        }

    }
}
}


text:
Q: Use data from .txt and then applicate calculation with a function, and then plotting the results I am trying to extract data from a .txt file (Aperture, ShutterSpeed) and then apply some calculations with a function I already created, and have the results plotted in a certain way.
What is the best way to do it in Python?
I have already read the data:
#!/usr/bin/python
import math

filename='/home/stagiaire/Bureau/derr.txt'
with open(filename) as f:
    data = f.read()
data = data.split('\n')
Fnumber = [row.split(' ')[0] for row in data]
ShutterSpeed = [row.split(' ')[1] for row in data]

But it is not accepted in my function that calculates the Lux value,
def Calcul_Lux(Fnumber,ShutterSpeed):
    x=math.pow(Fnumber,2)/(ShutterSpeed)
    IL=math.log(x,2)
    lux = math.pow(2,IL) * 2.5
    return lux

The idea is to have my data as a list I guess (two columns Fnumber and ShutterSpeed), but I don't know how to do it.

A: Input from string to float
When reading the data, it will be read as a string, this means that the values you obtain in Fnumber and ShutterSpeed are also of type string. As the Calcul_Lux function expects numbers, you need to typecast the string values as numbers.
To typecast a string into a floating point number you can use float(<object>), if you prefer to have an integer you can use int(<object>)
To solve your problem you can change the assignment of Fnumber and ShutterSpeed like this:
Fnumber      = [float(row.split(' ')[0]) for row in data]
ShutterSpeed = [float(row.split(' ')[1]) for row in data]

Call function in one go
To call the function for each value and return it as a list, we first need to pack the Fnumber and ShutterSpeed into a single list of tuples. We can do this using the zip() function:
tuples = zip(Fnumber, ShutterSpeed)

Next we can call the function Calcul_Lux for each item in the list using the map() function, which basically executes the given lambda function on each item in the list:
output = map(lambda tup: Calcul_Lux(tup[0], tup[1]), tuples)

This will return all you values as a list.
Plotting values
To plot the output and compare them with a constant line we can use the matplotlib library. We can use its plot() function to plot our output as points and we can draw a comparison line using the axhline() function. In the end the code to plot would look something like this.
import matplotlib.pyplot as plt # To import the matplotlib library

plt.plot(range(len(output)), output, 'ro')          # To draw the points from the output
plt.axhline(y=48000)            # To draw the 48.000 comparison line
plt.show()                      # To show the plot

The ValueError: ordinal must be >= 1 is caused because we only provided the y values, without any x values. To plot the output according to index we can change the plt.plot(output, 'ro') to include an x value like this:
plt.plot(range(len(output)), output, 'ro')

A: with open(filename) as f:
    pairs = ((float(x) for x in line.split()) for line in f)
    luxes = [Calcul_Lux(fnum, speed) for fnum, speed in pairs]

Here's how I would do it.  pairs is a generator that yields a generator of floats for each line.  The list comprehension accepts that generator, pulls out the two values and passes them to Calcul_Lux

A: Your Calcul_Lux funtion is expecting to be passed two values (f-number and shutterspeed), but you have your values in two lists. You can zip the lists together, which looks like this:
>>> one = [1,2,3]
>>> two = ['a', 'b', 'c']
>>> zip(one, two)
[(1, 'a'), (2, 'b'), (3, 'c')]

And then pass the values one at a time to your function, so:
for fn, ss in zip(Fnumber, ShutterSpeed):
    Calcul_Lux(fn,ss)

A: You may be better off extracting the data like this:
import math

def Calcul_Lux(Fnumber,ShutterSpeed):
    x=math.pow(Fnumber,2)/(ShutterSpeed)
    IL=math.log(x,2)
    lux = math.pow(2,IL) * 2.5
    return lux

filename='/home/stagiaire/Bureau/derr.txt'
with open(filename) as f:
    data = f.read()
data = data.split('\n')
cameraData = [(float(row.split(' ')[0]),float(row.split(' ')[1])) for row in data]

luxes=[Calcul_Lux(Fnumber,ShutterSpeed) for Fnumber,ShutterSpeed in cameraData]


text:
Q: calling method with Optional parameter in Java 8 I have the following method
public static Boolean test(String str, Optional<Boolean> test) {

}

but if I try to call it like
test("hello")

I get an error that the method requires two parameters.
Shouldn't the Optional parameter allow to me call the test method without providing the Optional parameter?

A: Optional is not a optional parameter as var-args is.
Optional is a container object which may or may not contain a non-null value.
So you could invoke the method as  :
test("...", Optional.of(true));

or
test("...", Optional.empty());

Note that with var-args :
public static Boolean test(String str, Boolean... test) {
 //...
}

this would be valid :
test("hello")

But var-args is not the correct way to pass an optional parameter as it conveys 0 or more objects and not 0 or 1 object.
Method overload is better :
public static Boolean test(String str, Boolean test) {
 // ...
}

public static Boolean test(String str) {
 // ...
}

In some other cases, the @Nullable constraints (JSR-380)  may also be interesting.

A: In short, no.
Optional is a class and in Java you must pass the exact number of parameters to a method just like it is defined.
The only exception is when you put ... after the class object name in the method declaration.
public String test (String X, String... Y) { }

Which makes the second parameter be either zero or more.

A: Try this
public static Boolean test(String str, Boolean ... test) {}

it will work with you


text:
Q: How to write test case for Threading in rails? In my rails application (rails version is 2.3.12), i am using thread for sending mails like below
Thread.new{SomeMailer.deliver_method(stuff)}

How to test this thread in rails. Actually i wrote this line in model.
Thanks in advance,
Jak.

A: In general, don't use threads in Rails. Use a single thread per process and use background workers to do stuff like this. Popular workers include delayed_job and resque.
In delayed_job:
SomeMailer.delay.deliver_method(stuff)

In Resque:
class DeliverStuff
  @queue = :mail

  def self.perform(stuff)
    SomeMailer.deliver_method(stuff)
  end
end

# elsewhere
Resque.enqueue(DeliverStuff, stuff)


text:
Q: Преобразовать список с вложенными словарями в JSON Имеется следующая запись:
r = [{'aa': '"yes": 51', 'ab': '"no": 22',
      'bb': '"yes": 56', 'ba': '"no": 60'},
     {'aa': '"yes": 39', 'ab': '"no": 10',
      'bb': '"yes": 59', 'ba': '"no": 30'},
     {'aa': '"yes": 30', 'ab': '"no": 31',
      'bb': '"yes": 54', 'ba': '"no": 73'}]

необходимо преобразовать в JSON типа:
[
    [
        {
            "yes": 51,
            "no": 22
        },
        {
            "yes": 22,
            "no": 60
        }
    ],
    [
        {
            "yes": 39,
            "no": 10
        },
        {
            "yes": 59,
            "no": 30
        }
    ],
    [
        {
            "yes": 30,
            "no": 31
        },
        {
            "yes": 54,
            "no": 73
        }
    ]
]

К сожалению сам одолеть не смог =(

A: Вот вам заготовка для разбора.
from ast import literal_eval

ll = []
for d in r:
    for v in d.values():
        x,y = v.split(':')
        ll.append({literal_eval(x): int(y)})

В результате получается такой список:
[{'yes': 51},
 {'no': 22},
 {'yes': 56},
 {'no': 60},
 {'yes': 39},
 {'no': 10},
 {'yes': 59},
 {'no': 30},
 {'yes': 30},
 {'no': 31},
 {'yes': 54},
 {'no': 73}]

Осталось только в JSON это собственно разместить попарно, пока мне лень дальше разбираться.


text:
Q: Which approach to storing items in a linked-list is faster? There's a question in my algorithm textbook for practice that I'm not sure of, and was hoping someone can elaborate / explain:
When you design a divide and conquer algorithm to store items in a linked list of size n, would dividing the problem in half be asymptotically faster in the worst case scenario than the algorithm dividing the list into a single subproblem of size 1 and another of size n-1?

A: regard the process as a tree structure, like:
          [1,          n]
         /               \
 [1,     n/2]             [n/2,       n]
 /           \             /            \
[1, n/4] [n/4, n/2]  [n/2, n*3/4] [n*3/4, n]

the time cost depends on how much calculation you do on each level.
e.g. find the maximum number in an array.
int f1(int a[], int n){
    if (n == 1) return a[0];
    return max(a[0], f1(a + 1, n - 1));
}

int f2(int a[], int n){
    if (n == 1) return a[0];
    return max(f2(a, n / 2), f2(a + n / 2, n - n / 2));
}

the calculation you do on each level is O(1), so both f1 and f2 is O(n) in total.
or as you mentioned, the quicksort algorithm, the calculation you do on each level is O(n), so the total cost depends on how many levels there are.
if we divide it into [1, n/2] and [n/2, n], there would be O(logn) levels and total time cost is O(nlogn).
and if we divide it into [1, 1] and [2, n], there would be O(n) levels, so the total time cost would be O(n^2)


text:
Q: Lift existentials in Coq Can this lemma be proven in Coq ?
Lemma liftExists : forall (P : nat -> nat -> Prop),
  (forall n:nat, exists p:nat, P n p)
  -> exists (f : nat -> nat), forall n:nat, P n (f n).

The simple destruct does not compile, because we cannot eliminate the object exists p:nat, P n p in sort Prop, to produce the function f in sort Set.
If Coq cannot prove this lemma, then what is the meaning of forall n:nat, exists p:nat, P n p ? In constructive mathematics it would mean the existence of the function f, but I have the impression that we will never see this function f in Coq, not even in sort Prop as expressed above.

A: It is not provable in Coq because of the restriction on eliminating Prop into Set. As for the philosophical "meaning", I'm not sure if anyone has a very good story about this. The inhabitants of forall n:nat, exists p:nat, P n p are functions returning a pair of p and a proof, but in addition they a functions that can be ignored when compiling programs because you know that nothing will look at the value that was returned.
So partly this system of Prop versus Set is a way to compile programs more efficiently, but actually this is also used for logical properties. In Coq the Prop type is impredicative and the Set type is not, and even so it's consistent to assume the law of exluded middle for Props as an axiom, and to prove that this is consistent you can appeal to a "proof-irrelevant model", where you interpret types in Props as sets by ignoring all information except whether they are inhabited or not. From a classical logic perspective (where all you care about are truth values) that makes sense, but if you are interested in constructive mathematics it's a bit weird!


text: Q: How do I edit the xfce4.12 Whisker Menu globally for all users on Ubuntu Studio 18.04.4 LTS via a root file manager or terminal? I want to edit the Xfce4.12 Whisker Menu running on Ubuntu Studio 18.04.4 LTS in "/". I want to edit the categories like: "All", "Audio Production", etc using either the XML files or whatever files are needed to edit the menu and I also want to create new entries. I want to do it in the root directory because I want the changes to take global effect for all users and new users created in the OS. I also want to change and/or create new entries in the left column of the menu where the entries are "Web Browser", "File Manager", etc. The next thing I would like to change is the column width between the two columns. The last thing I would like to change and/or create new entries for is the bar at the bottom of the menu where it has the "All Settings", "Lock Screen", and the "Log Out" buttons. I want to edit these files from a root file manager or from a text based terminal only. I don't want to do it from the GUI. Where are the file locations I need and which/what ways do I do all this? Thanks for your help everyone.


text:
Q: Button link to facebook application I have a button link to facebook account but it connect to Google browser in my mobile (as shown) but I don't want that, I want it to take me to facebook application in my mobile and if it doesn't exist, it takes me to Google play application to download/install facebook, does anybody know how?
package com.el.dom;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class PageAb extends Activity {

    Button dclink;

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

    public void addListenerOnButton() {

        dclink= (Button) findViewById(R.id.dctec);

        dclink.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

              Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/blah"));
                startActivity(browserIntent);

            }
        });
    }
}

A: use android facebook sdk create an app at http://developers.facebook.com/ and proceed

A:     try {
  //try to open page in facebook native app.
  String uri = "fb://page/" + yourFBpageId;    //Cutsom URL
  Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
  startActivity(intent);
  }
  catch (ActivityNotFoundException ex){
  //facebook native app isn't available, use browser.
  String uri = "http://touch.facebook.com/pages/x/" + yourFBpageId;  //Normal URL
  Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uriMobile));
  startActivity(i);
  }

copied from How to navigate user to a facebook page via Android's facebook api?