text:
Q: How to open .RAW file with bizarre custom header I have a bizarre .raw file in the following format, that I need to open for a class project. It has the following structure using the example of a 487x414 photo:

*

*The number of rows is two un-signed bytes (01E7)

*The number of columns is two un-signed bytes (019E)

*The number of bits representing each pixel (this will always be 8)

*The actual picture data

The project is to run edge detection on the .raw file, but the professor said I should be able to open it with any old image editing software (apparently, he expects me to be prompted with a window where I set the number of bytes in the header), so I tried the following to no avail:

*

*Paint.net

*Photoshop Elements

*Adobe Lightroom

*ImageMagick

*Gimp

*DCRaw

I'm dual booting Ubuntu and Windows, so if anyone has any ideas on how I could get this file displayed, (I'm currently trying to load it into OpenCV as a histogram, but I would like to have something to check my result against), it would be greatly appreciated.

A: I ended up having to write a custom Python script which you can find here. Here's the important part.
#Load the raw file
f = open(filename,'rb') # switch to command line args later
#Because the byte order is weird
a = f.read(1)
b = f.read(1)
#First line is rows
rows = int((b+a).encode('hex'), 16)
a = f.read(1)
b = f.read(1)
#Second line is columns
cols = int((b+a).encode('hex'), 16)
#Last byte is encoding, but we're just going to ignore it
f.read(1)
#And everything else is 8 bit encoded, so let's load it into numpy and display it with matplotlib
bin_image = np.fromstring(f.read(), dtype=np.uint8)
#Change the shape of the array to the actual shape of the picture
bin_image.shape = (cols, rows)

fig = pylab.figure()
#Display the original image
fig.add_subplot(1,4,1)
pylab.imshow(bin_image, cmap=cm.gray)


text:
Q: HttpStatus with ResponseEntity and pdf I have a spring mvc controller which produces an "application/pdf" to download a generated pdf. I want to return always the pdf and also return different HTTP codes depending on certain conditions.
I tried to return a ResponseEntity<> object but always response is 200 with the PDF (always the pdf is generated, but I need different status responses).
@RequestMapping(value = "/obtain/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
@ResponseBody
public ResponseEntity<?> getPdfFile(HttpServletResponse response,HttpServletRequest request) throws IOException{

    response.setHeader("Content-disposition", "inline; filename=\"" +"file.pdf" +"\"");
    String error = getPDF(response, request);
    logger.debug("PDF error : " + StringUtils.defaultIfEmpty(error,"null") );
    return new ResponseEntity<>("",HttpStatus.INTERNAL_SERVER_ERROR);
}

Note : Inside getPDF method, is just the code which generates the pdf and write it to the response.getOutputStream().
The idea behing is that I want to return ALWAYS the pdf in the outputstream, but different result codes (200, 500, etc). Event when I return 500, I want to return a PDF. Is it possible?
Any help will be appreciated.

A: I am not 100% sure about this, but I think the method is returning whatever is in the HttpServletResponse, rather that the object you are returning.
I think you should experiment with HttpServletResponse.getWriter().write(responseEntity.getBody()) and HttpServletResponse.setHttpStatus(responseEntity.getHttpStatus()), or just the equivalent hard-coded values...
Also, are you seeing the errors and the 200 status alongside each other? If so, try parameterizing the entity as a String - whatever Throwable you put in there should still work fine.
Please let me know if you try that and it doesn't work so I can edit or remove this answer - I haven't actually tried this yet, but interested to find out why that code is not working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can i still get the stone of Barenziah in astrid's room? Can you still get the one in Astrid's room after you have completed the final dark brotherhood quest? because I have already completed it and i didn't notice a stone.

A: You can still get the Stone of Barenziah from Astrid's room even after the DB sanctuary has burned down.
Here is a screenshot of the same.

If you are having trouble locating the stones, there is a mod that gives quest marker type arrows to the stones available on PC, XBox One and PS4.


text:
Q: Cordova plugin: danwilson/google-analytics-plugin not working on android device I'm trying to use the google analytics on Cordova  app,
I've followed the instruction on the the repository , and all works well on the chrome android emulator .
I see live activity on google analytics site.
but when i log into the app from the device , it seems the analytics is not recognizing the the app.
in my config.xml I have :
 < access origin="*" >

In the android manifest I have the permissions :
android.permission.INTERNET

android.permission.ACCESS_NETWORK_STATE

When running in debug mode , i see the app is indeed going into the
cordova.exec(success, error, 'UniversalAnalytics', 'trackView', [screen]);

function , but it doesn't display any data on the google analytics view
any ideas?

A: well, it seems Google analytics is updated after 24 hours or so when using the mobile Api.
Although I don't see any activity in the 'live-view' section
I can see a log of my activities on the site from previous days (eCommerce analytics)


text:
Q: How to get the selected count, in the template, of selected items from select element in angular? I have the following markup in my template:
Cuisine

{{ getCount(selected) }} selected
<nb-select
    multiple
    [(selected)]="selected"
    formControlName="restCuisine"
    id="restCuisine">
    <nb-option value="International">International</nb-option>
    <nb-option value="Chinese">Chinese</nb-option>
    <nb-option value="Greek">Greek</nb-option>
    <nb-option value="Middle Eastern">Middle Eastern</nb-option>
    <nb-option value="Caribbean">Caribbean</nb-option>
    <nb-option value="Asian">Asian</nb-option>
    <nb-option value="Local">Local</nb-option>
    <nb-option value="Japanese">Japanese</nb-option>
    <nb-option value="Mexican">Mexican</nb-option>
    <nb-option value="Indian">Indian</nb-option>
    <nb-option value="British">British</nb-option>
    <nb-option value="European">European</nb-option>
    <nb-option value="Italian">Italian</nb-option>
    <nb-option value="French">French</nb-option>
    <nb-option value="Spanish">Spanish</nb-option>
    <nb-option value="Cajun">Cajun</nb-option>
    <nb-option value="Thai">Thai</nb-option>
    <nb-option value="Mediterranean">Mediterranean</nb-option>
</nb-select>

I'm trying to the get the selected items count like so:
selected;

getCount(selected: any) {
    return selected.length();
}

but it doesn't work. I tried different examples from the web but it's not what I'm looking for. I was thinking of referencing the element using ViewChild and overriding the change event of the element then counting the items in selected but that's too much code. I'm looking for a one or two liner.
How do I get the number of selected items of the select element? The real challenge is to do this only in the template but typescript will be fine too.

A: The answer is pretty simple with selectedChange and interpolation. Find below the answer:
Cuisine

{{ restCuisineCount }} selected

<nb-select
    multiple
    fullWidth
    (selectedChange)="onChangeRestCuisine($event)"
    formControlName="restCuisine"
    id="restCuisine">
    <nb-option value="International">International</nb-option>
    <nb-option value="Chinese">Chinese</nb-option>
    <nb-option value="Greek">Greek</nb-option>
    <nb-option value="Middle Eastern">Middle Eastern</nb-option>
    <nb-option value="Caribbean">Caribbean</nb-option>
    <nb-option value="Asian">Asian</nb-option>
    <nb-option value="Local">Local</nb-option>
    <nb-option value="Japanese">Japanese</nb-option>
    <nb-option value="Mexican">Mexican</nb-option>
    <nb-option value="Indian">Indian</nb-option>
    <nb-option value="British">British</nb-option>
    <nb-option value="European">European</nb-option>
    <nb-option value="Italian">Italian</nb-option>
    <nb-option value="French">French</nb-option>
    <nb-option value="Spanish">Spanish</nb-option>
    <nb-option value="Cajun">Cajun</nb-option>
    <nb-option value="Thai">Thai</nb-option>
    <nb-option value="Mediterranean">Mediterranean</nb-option>
</nb-select>

and typescript:
restCuisineCount = 0;

onChangeRestCuisine(event: any) {
    this.restCuisineCount = event.length;
}


text:
Q: .Flac files on Ipod Classic? I'm super new to Linux, being a Windows user my whole life, and I'm really trying to learn as much as I can.  When I made the switch, I took my 42+ GB collection of music (Previously handled in Itunes) with me, with over 500 songs in .wav format.  Wanting tag support, I've converted all of these files to .flac successfully through Soundconverter, but just now found out that my Ipod Classic won't play .flac files!
So, now I'm looking for a way to get these files onto my Ipod and play them.  I don't care if I have to update its firmware, convert these .flac files to Apple Lossless or any other method, whether through a program or the terminal, all I care about is I want to retain tag support and have them in a lossless format.  Any suggestions??

A: I think you'll have to convert your .flac files to apple loseless format (ALAC) to be able to play them with your ipod. You'll also be able to play your alac files using music player available on Ubuntu.
Here is explanations to convert flac files to alac files.
If you've a lot of files to convert, it can be a good idea to write a script that will convert your files. If you need help for that, ask a new question.


text:
Q: how to touch nginx cache file via php Usually to flush nginx cache, I use the unix command :
touch /var/ngx_pagespeed_cache/cache.flush

I'd like to know if I can do the same with php in order not to log on SSH to do it.
If yes, would this code work ? :
<?php

    $flush_file = "/var/ngx_pagespeed_cache/cache.flush";
    touch($flush_file);

?>

If not, could you point me on how to please ?
Many thanks in advance.

A: Reposted my own comment above for better formatting.
Well, I guess it would be safe enough to chown this file to user which run php/webserver ex. www-data. Then give him write permission on this file.
On Debian server it would be somethings like this:
sudo chown www-data /var/ngx_pagespeed_cache/cache.flush
sudo chmod +w /var/ngx_pagespeed_cache/cache.flush


text:
Q: User to start Passenger (with Nginx) I have Nginx with Passenger.  In nginx.conf I have line:
user pass users;

and Nginx process works on 'pass' user, but Passenger* processes work on 'nobody' user.
I can run Passenger standalone:
sudo passanger start -e production -p 80 --user=pass

How can I run Passenger with Nginx with my custom user?

A: At one point the user and group were determined by the owners of the config.ru file. I'm pretty sure this is still the case.

A: Put the following into your nginx.conf in the http block:
passenger_default_user custom_username;
passenger_default_group custom_group;

You can find more configuration options here:
http://modrails.com/documentation/Users%20guide%20Nginx.html#PassengerDefaultUser

A: You can pass a user line into your nginx conf.
http://wiki.nginx.org/CoreModule#user
I suggest that in the future you ask server questions on ServerFault, they usually know a lot more about nginx and passenger.


text:
Q: the error about transplantation VXL to android I want to transplant the VXL(the Vision-something-Libraries) to android platform.the crosscompiler I used is  android-cmake.
you can get the VXL from the url http://vxl.sourceforge.net/  .the version i used is vxl-1.14.0
you can get the android-camke from the url http://code.google.com/p/android-cmake/
when I properly setup my NDK for cmake,and specify the Standalone Toolchain  as the introduction of android-camke.Then,I use andriod-camke to compile the VXL.But I encounter many error.it can't produce the Makefile . somebody know why?
Next is the error log.
l00138375@l00138375:/home/hm/build-vxl$ android-cmake ../vxl-1.14.0
CMake Warning at /home/hm/android/android-cmake/toolchain/android.toolchain.cmake:281 (message):
  Using value of obsolete variable ANDROID_NDK_TOOLCHAIN_ROOT as initial
  value for ANDROID_STANDALONE_TOOLCHAIN.  Please note, that
  ANDROID_NDK_TOOLCHAIN_ROOT can be completely removed in future versions of
  the toolchain.
Call Stack (most recent call first):
  /home/hm/android/android-cmake/toolchain/android.toolchain.cmake:376 (__INIT_VARIABLE)
  /usr/share/cmake-2.8/Modules/CMakeDetermineSystem.cmake:89 (INCLUDE)
  CMakeLists.txt:13 (PROJECT)

........

-- Check if the system is big endian - little endian
-- Performing Test VCL_CHAR_IS_SIGNED
CMake Error: TRY_RUN() invoked in cross-compiling mode, please set the following cache variables appropriately:
   VCL_CHAR_IS_SIGNED (advanced)
   VCL_CHAR_IS_SIGNED__TRYRUN_OUTPUT (advanced)
For details see /home/hm/build-vxl/TryRunResults.cmake
-- Performing Test VCL_CHAR_IS_SIGNED - Failed
-- Looking for 8-bit int. [Checking char...]
CMake Error: TRY_RUN() invoked in cross-compiling mode, please set the following cache variables appropriately:
   RUN_RESULT (advanced)
   RUN_RESULT__TRYRUN_OUTPUT (advanced)
For details see /home/hm/build-vxl/TryRunResults.cmake
.........
-- Performing Test VCL_NUMERIC_LIMITS_HAS_INFINITY
CMake Error: TRY_RUN() invoked in cross-compiling mode, please set the following cache variables appropriately:
   VCL_NUMERIC_LIMITS_HAS_INFINITY (advanced)
   VCL_NUMERIC_LIMITS_HAS_INFINITY__TRYRUN_OUTPUT (advanced)
For details see /home/hm/build-vxl/TryRunResults.cmake
-- Performing Test VCL_NUMERIC_LIMITS_HAS_INFINITY - Failed
-- Performing Test VCL_PROCESSOR_HAS_INFINITY
CMake Error: TRY_RUN() invoked in cross-compiling mode, please set the following cache variables appropriately:
   VCL_PROCESSOR_HAS_INFINITY (advanced)
   VCL_PROCESSOR_HAS_INFINITY__TRYRUN_OUTPUT (advanced)
For details see /home/hm/build-vxl/TryRunResults.cmake
-- Performing Test VCL_PROCESSOR_HAS_INFINITY - Failed
-- Looking for C++ include inttypes.h
-- Looking for C++ include inttypes.h - found
-- Looking for memalign
-- Looking for memalign - found
-- Could NOT find DC1394 (missing:  DC1394_LIBRARIES DC1394_INCLUDE_DIR)
-- Performing Test DIRECTSHOW_SOURCE_COMPILES
-- Performing Test DIRECTSHOW_SOURCE_COMPILES - Failed
CMake Error at config/cmake/Modules/NewCMake/FindDirectShow.cmake:101 (MESSAGE):
  Uncomment code below: FindPackageHandleStandardArgs is now available.
Call Stack (most recent call first):
  core/vidl/CMakeLists.txt:13 (INCLUDE)

A: As Andrey's comment mentions, the way VXL uses CMake, prevents cross-compilation. However there is an alternative. One of the maintainers maintains branches containing alternative build systems for the core libraries. The vxl-build-makefiles branch ought to be a good starting point to modify to work with a cross-compiler.
http://sourceforge.net/p/vxl/svn/36716/tree/branches/vxl-build-makefiles/
If you have any questions about using the branch, or indeed anything else about VXL - the vxl mailing lists are probably more use. vxl-users@lists.sourceforge.net


text:
Q: How to fit the frames onto the Swiss QR invoice I'm implementing the software to produce the payment slip with the new QR code for our company's invoicing (according to the new Swiss payment standard) and I have troubles fitting the frames where the payer can fill in his address and the exact amount himself.
In particular on the right side, I'm running out of space. We have a creditor address and a final creditor address. So we have at least 13 lines of text plus the frame, which is rather big. The standard says hardly anything about the exact layout.
Is there any sample code available for implementing the QR invoice (preferably for Java)? Or have I missed a standard document that describes the layout of the payment part in more detail?

A: Yes, the standard is rather open about the layout. But it seems to be possible to fit your information on the payment part. You can try it yourself in this Swiss QR Bill web site. Just delete the amount and all debtor fields and you end up with this:

It's indeed a very tight fit. But you might not need the reference number, the additional information and the due date. That could free up some space.
The web site seems to be related to an open-source Java library for the Swiss QR bill. Why not use that library?
There are further (commercial) libraries. Have a look at the (German) web page https://www.moneytoday.ch/lexikon/qr-rechnung/


text:
Q: How would you write jest Tests for these React function assignments? I'm fairly new to React apps (and thereby jest), and I get the basics, but my code coverage is highlighting these lines where functions are assigned to a child component of my outer component - what would be the best practice for testing these lines of code?

A: You have 2 main options:
Make a test where you render the  component and pass some mock functions instead of real functions. Then make sure that the mocks are being called when you take the action that you want.
Or you can test at the parent level so you don't mock the function. You use userEvent to take the action that you want and you make sure you get the expected results display.
It is hard to go into more detail with this little info.
If this component is from MaterialUI it is a little bit more challenging because being able in the test to mimic the user action can be challenging because material UI components are very complex...


text:
Q: Break loop on null value I have one source Google Sheet that copies to a number of different Google Sheets for different students. The information copied is for different subjects, each a different sheet on the student's personal Sheets file.
The source sheet is set up to cope with differently sized classes, but my problem is trying to break the code when it reaches a section with no information. I don't know why my break statement is not working, since I know that copysheet is null as it results in an error every time the code runs.
function cloneGoogleSheet() {
  //select source sheet
  var sourcesheet = SpreadsheetApp.openById('some id');

  var j;
  for (var j = 1; j < 36; j++) {
    //select student sheets to copy to
    var studentid = sourcesheet.getSheetByName("Sheet11")
        .getRange(j, 2).getValue();

    var i;
    for (var i = 1; i < 14; i++) {
      //select subject name for referencing different sheets
      var subject = sourcesheet.getSheetByName("Sheet6")
          .getRange(i + 1, 7 * j - 5).getValue();

      //find correct subject sheet on student sheet
      var copysheet = SpreadsheetApp.openById(studentid).getSheetByName(subject);

      if (copysheet != null) {break;}
      else {
        //copy "importrange" formula from sourcesheet
        var info = sourcesheet.getSheetByName("Sheet6")
            .getRange(i + 1, 7 * j).getValue();

        //copy teacher name from sourcesheet
        var teachername = sourcesheet.getSheetByName("Sheet6")
            .getRange(i + 1, 7 * j - 4).getValue();

        //copy student name
        var studentname = sourcesheet.getSheetByName("Sheet6")
            .getRange(2, 7 * j - 6).getValue();

        //paste "importrange" formula into student sheet
        copysheet.getRange(6, 2).setValue(info);

        //paste teacher name into student sheet
        copysheet.getRange(3, 2).setValue(teachername);

        //paste student name into student sheet
        copysheet.getRange(1, 2).setValue(studentname);
      }
    }
  }
}

A: Change
if (copysheet != null) {break;}

to
if (copysheet == null) {break;}


text:
Q: How do you get the groupUniqueId for the Google Group Settings API? I am looking at this API: https://developers.google.com/admin-sdk/groups-settings/v1/reference/groups/get
However, when I try the test at the bottom, it always returns 400 Bad request. I have tried using the Google group email address (without the @gmail.com and with the @gmail.com) for several groups I am in.
How do you find the groupUniqueId for a Google group?

A: I had the problem yesterday and 'think' I undertood it:
I use the PHP SDK and had to use groupssettings API.
When I executed my query, the PHP answer was something such: "incorrect json format".
Still in my API, I had to FORCE the JSON to be used, by adding optional parameter: alt=json
Then, The query worked.
Until now, this is the only Google API where I had to specify this.
What I suspect is the "Try It" feature to use json, and because the API does NOT returns json by default, it just fails. Too bad there is no way to force json there.


text:
Q: New Mac User needs help installing Picasa and then importing all i photos into picasa with correct titles Have i photo with pictures in named folders. Want to install Picasa. When I did this picasa imported all the iphotos with goofy names, not like the iphoto names. would like to install picassa then put the iphotos into picasa the same as it looks in i photo. BTW, i am a new mac user, and recently copied all my photos from picasa to i photo. now i want to put picassa back on new mac. I prpbably should have installed picassa first on to the mac and put the photos from thePC to picassa on the mac. Now iam stuck. So, how to put picassa on mac and then put all (4,000 pictures in named files)from the iphot back into picassa for mac. Help

A: *

*Delete the photos from Picassa

*Export the photos from iPhoto to a folder named by titles (or as you like)

*Import from the filesystem to Picasa


text:
Q: rdfs:domain error when validating RDF with RDFS in RDFUnit I tried to validate my RDF with RDFS in RDFUnit online demo (http://rdfunit.aksw.org/demo/). Result of validation is:

Fail ERROR http://example.org/cim#IdentifiedObject.mRID has
  rdfs:domain different from: http://example.org/cim#IdentifiedObject

RDF:
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:cim="http://example.org/cim#" >
  <rdf:Description  rdf:about="1">
    <rdf:type rdf:resource="cim:IdentifiedObject" />
    <cim:IdentifiedObject.mRID>1</cim:IdentifiedObject.mRID>
  </rdf:Description>
</rdf:RDF>

RDFS:
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="http://example.org/cim#" >
  <rdfs:Class rdf:ID="IdentifiedObject" />
  <rdf:Property rdf:ID="IdentifiedObject.mRID">
    <rdfs:domain rdf:resource="#IdentifiedObject" />
  </rdf:Property>
</rdf:RDF>

What is a proper way of declaring domains in rdf:Propery?

A: The error is a little cryptic, but at a guess the problem is this line in your data:
<rdf:type rdf:resource="cim:IdentifiedObject" />

You are using a prefixed name as the value of rdf:resource here, but that is not allowed in RDF/XML*. This value needs to be the full URI: http://example.org/cim#IdentifiedObject. The result of the current situation is probably that RDFUnit doesn't recognize that the class used in your data and the class your schema uses in the domain statement are the same thing.
Protip: don't use RDF/XML. Like, ever. It's a terrible syntax to have to manually write/debug. Switch to something like Turtle or N-Triples, much easier to read and edit.
* The reason this doesn't work is that RDF/XML is, well, XML, and it uses the XML namespace mechanism for denoting prefixed names - which is only for element and attribute names, not for attribute values.


text:
Q: Django - Update a model field through a form I have this model which represents the values users submit through a form when making an applying for sponsorship.
class ApplicationData(models.Model) :
class Status(models.TextChoices):
    REJECTED = 'Rejected'
    PENDING = 'Pending'
    ACCEPTED = 'Accepted'

"""Define table for Applications in database"""
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
organisationName = models.CharField(max_length=200, null=True, blank=True)
projectTitle = models.CharField(max_length=200, null=True, blank=True)
CH_OSCR_number = models.CharField(max_length=20, unique=True, blank=True, null=True, )
projectDesc = models.TextField(max_length=300, null=True, blank=True)
userGroupDesc = models.TextField(max_length=300, null=True, blank=True)
learningOpp = models.TextField(max_length=300, null=True, blank=True)
keyPartnersWork = models.TextField(max_length=300, null=True, blank=True)
projImpactClimate = models.TextField(max_length=300, null=True, blank=True)
projSupportLocBus = models.TextField(max_length=300, null=True, blank=True)
proContribution = models.TextField(max_length=300, null=True, blank=True)

length = models.IntegerField(null=True, blank=True)
application_complete = models.BooleanField(default=False)
date_of_application = models.DateField(null=True, blank=True)
reviewed = models.BooleanField(default=False)
app_status = models.TextField(choices = Status.choices, default = Status.PENDING)

On the system there are 3 different user types. Once an applicant submits an application the staff users can view the submitted application details on a dedicated page. What I'm trying to do is to add a form on that page where the staff will have the ability to change the status of the application (app_status on the model).
Here are my efforts:
Here the is the form to update the field.
class UpdateAppStatus(forms.ModelForm):

class Meta:
    model = ApplicationData
    fields = ('app_status',)
    labels = {'app_status':'Change application status?'}

This is the view - it displays the application details and im also trying to add this functionality to update the status.
def view_application_status(request, id):
admin = True if request.user.is_superuser else False
application = ApplicationData.objects.get(id = id)
application_form = ApplicationForm(instance=application)
comments = Comments.objects.filter(application = application)
if request.user.is_staff:
    statusform = UpdateAppStatus()
    if request.method == 'POST':
        satusform = UpdateAppStatus(request.POST)
        if satusform.is_valid():
            statusform.save()
        else:
            print(satusform.errors)

    return render(request, 'fund/application_view.html', {'application':application, 'application_form' :application_form, 'comments':comments, 'admin':admin,'statusform':statusform})
print(comments)
for comment in comments:
    print(comment.comment)
else:
    return render(request, 'fund/application_view.html', {'application':application, 'application_form' :application_form, 'comments':comments, 'admin':admin})

And here the is html part:

Application Status

          {% if request.user.is_staff %}
          <form id = "ReviewForm" method="post" action="" enctype="multipart/form-data">
            {% csrf_token %}
            {{statusform.app_status.label}}
            {{ statusform.app_status }}
            <input type="submit" value="Submit" class="btn btn-primary" onclick="">
          </form>
          {% endif %}

So what I'm trying to achieve is for the staff to change the value of the field app_status using this form that is visible on the view application status page.
I believe the issue is in the view function but I did not manage to find a solution.


text:
Q: How to run Node.js CLI REPL with history saving disabled? I like to test JS/ES APIs that I am/became less familiar with in the Node.js REPL, but most times I don't want anything saved to the REPL history file for later reference or study.
Also the Node CLI REPL, unlike most shells, even when you prefix the command with a space it saves it to history.
I checked Node's manual page with man node and node --help, there's nothing like --no-save that most other CLI REPLs have, the only thing close to it is:
Environment variables:
     NODE_REPL_HISTORY file
             Path to the file used to store persistent REPL history.  The default path is ~/.node_repl_history, which is overridden by this variable.  Setting the value to an empty string
             ("" or " ") will disable persistent REPL history.

A: you can, before starting node, temporarily set NODE_REPL_HISTORY to something else (e.g /dev/null), so the Node.js cli repl doesn't default to saving to the default ~/.node_repl_history:
export NODE_REPL_HISTORY="/dev/null" && node
but don't forget to unset NODE_REPL_HISTORY after Node exits so that next time you start Node normally NODE_REPL_HISTORY defaults to default configs:
export NODE_REPL_HISTORY="/dev/null" && node && unset NODE_REPL_HISTORY
if you would like not type that every time, you can set the line above an alias (command) e.g nonode, in your shell's rc file:
alias nonode="export NODE_REPL_HISTORY="/dev/null" && node && unset NODE_REPL_HISTORY"


text:
Q: Как найти координаты прямоугольного параллелепипеда Как решить вот такую задачу

Есть координаты baseCornerPoint есть height, length, width
Нужно найти
1) Координаты лежащей по диагонали точки от baseCornerPoint
2) Центр этого параллелепипеда
Я знаю, что это материал школы, но это было давно.
P.S.
Я пытался решить эту задачу, просто не стал излагать все не верные решения тут.
Вот ссылки которые смотрел и пытался делать по ним
https://multiurok.ru/files/rasstoianiie-ot-tochki-do-ploskosti-mietod-koordin.html
https://www.fxyz.ru/формулы_по_геометрии/формулы_объема/объем_параллелепипеда/
https://ege.sdamgia.ru/problem?id=505871
Но чет не сильно получилось
Если кто то учиться сейчас то подскажите

A: Судя по изображению, вторая точка может быть найдена арифметически вот так
vec3 p2 = vec3(p1.x - length, p1.y + width, p1.z + height);

При этом центральная получается полусуммой координат начала и конца диагонали
vec3 pCenter = vec3((p1.x+p2.x)/2, (p1.y+p2.y)/2, (p1.z+p2.z)/2);


text:
Q: ZMQ vs FTP for file transfer Here is the challenge :

many (sender) servers must send files to many (receiver) servers. And
  when a file is received on a server, then the receiver must trigger an
  action. And I must add : the file transfer is really a big deal.

One solution has been suggested :

developing a program in C, which uses ZMQ for everything

Personally, I am not sure that this is a good solution.
Why should it be necessary to develop a custom file transfer protocol on top of ZMQ, knowing that FTP exists and client/server FTP libraries are available in many programming languages ? It seems to me that it is like reinventing the wheel.
One argument has been advanced : FTP is "heavy". Well, I don't see why FTP is particularly "heavy", and I am not that we can do better (or, at least, significantly better - to justify the cost) with an implementation of a custom file transfer protocol on top of ZMQ.
Secondly, I am not sure that using C is a good idea either knowing that the file transfer software is IO bound : the performances essentially depend on the network bandwidth and, to a lesser extent on the disks performances. Using assembly language to write a file transfer program won't do better than using C, which won't do better than using Python or GO (for example) : the program essentially waits for the IOs to terminate. Using C only makes the code longer (in terms of length and complexity), knowing that we have to take care of all the low-level details (thread-safe programming with sockets, timeout management...).
I would advocate another approach :

*

*using a high-level programming language that takes care of many low-level details (ex : Python, GO).

*using FTP for the file transfers, through a client/server FTP library. Reinventing the wheel is not a good idea.

*using ZMQ for exchanging messages. When an FTP receiver receives a file, it triggers an action through the sending of a message through a ZMQ channel. And, for that, using C is like using a sledgehammer to crack a nut.

Do you see any good reason to use ZMQ+C for everything ?


text:
Q: Prove that extension of a function is a surjection? I am doing work with model theory and came across the following exercise:
"Consider a set $Y$ in some structure $\mathcal{M}$. Let $f:Y\to C$ be a definable map to a compact space $C$, with dense image. Suppose $Y\subseteq Y^{*}$. Then there is a unique extension of $f$ to $Y^{*}$, called $f^{*}$, that is M-definable. $f^{*}(a) = \cap_{\alpha \in p} \overline{f(\alpha(M))}$ where $p = tp(a/\mathcal{M})$.
Prove that this extension is surjective. "
So my thought to use the dense image of $f$ since we know that the preimage of dense set under an onto map will be dense also. But I was unable to show that this would be the case.
Outline of my unsuccessful attempt. I don't know if this can work, or whether need to start over:
I try to use the definable map and $\mathcal{M}$-definable map properties.
So if $f$ is definable, we can find a definable set $Y_{0}\subseteq Y$ such that for disjoint closed sets $C_{1},C_{2}\subseteq C$ (which will also be compact) $C_{1}\subseteq Y_{0}$ and $C_{2}\cap Y_{0} = \emptyset.$
For an $\mathcal{M}$ definable map, like our $f^{*}$, preimage of closed set is type definable.
So maybe I show that the whole of $Y^{*}$ is dense?
Thank you for help.


text:
Q: Find textarea and replace with something else <html>
<head><title>Example page</title></head>
<body>
<textarea name="description">This is some text</textarea>
<input type='text' name='bla' value='a textinput' />
<textarea name="interests">What i like to do</textarea>
</body>
</html>

The above html code is the value of a variable. I want to grab all the textareas and replace them by something. What would be the way to get following array from the string:
1: <textarea name="description">This is some text</textarea>
2: <textarea name="interests">What i like to do</textarea>

A: *

*Use DOMDocument->loadHTML() to load the HTML as a DOM tree,

*Find the textarea elements (and their text nodes)

*Replace with relevant element.

Cf. Robust, Mature HTML Parser for PHP

In essence: avoid regular expressions for this kind of tasks. If you insist (and the HTML is guaranteed to be as simple as indicated), try:
preg_replace('/<textarea name="([^"]+)">([^<]+)<\/textarea>/', '<input type="text" name="\\1" value="\\2">', $yourHtmlString);

(demo)


text:
Q: How to Use Google Fitness Api to build sample Step Counter? Today, I was starting to deal with google fitness API to complete my smartwatch application that record heart rates and send data to cloud to do some processing on this data but if I want to go with traditional way to program PPG heart rate sensor it will be difficult to do signal Processing on PPG signal because that I switched from traditional way to program sensor to use Google API because it has everything I need from it. However, When I started to learn how to use Google Fitness API from api website, I didn't understand how to Use Google Api because I felt examples that given from api website was not clear to me because there is many deprecated methods from google and new methods revel. Therefore, I want now to program sample step counter by using Google Fitness api as first stage to understanding how to use this api until I reach heart rate sensor, and now I already connected google fitness api with android studio and what is next step to program sample step counter application.
In general, I have some Ideas how build this application but in coding part I don't know how to program by api methods.
Thanks


text:
Q: RSpec - Dependant objects I'm fairly new to testing with RSpec, and have been on this problem for a while.
I have the following test for a user to delete their account.
require 'rails_helper'

feature 'delete account' do
  let!(:user) {create :user, :basic}

  scenario 'successfully' do

    login_as(user)
    visit dashboard_path
    click_link 'Settings'
    click_link 'Cancel my account'

    expect(page).to have_content("Your account has been cancelled.")
  end
end

When running the test, I get the following error;
1) delete account successfully
 Failure/Error: <%= account.radio_button :plan_id, @plan.id, data: { name: @plan.name, amount: @plan.amount}, checked: true, class: 'hidden' %>

 ActionView::Template::Error:
   undefined method `id' for nil:NilClass

Here is the controller code. When the test clicks 'Settings' the show page is rendered. The issue is that no plans exist, but they are irrelevant to what I am testing.
def show
  @plan = Plan.find_by(name: 'Premium')
  @subscription_pending_cancel =
  Account.check_subscription_status(@account)
end

I could create the plan before the test runs, which passes the test.
 before do
   Plan.create(name: 'Premium')
 end

However having to create objects like this doesn't seem sustainable as the test suite grows - particularly in relation to speed and keeping the test DB clean.
The question is - does a real object (being a plan in my case) need to be created/persisted to the db for a test such as the above, or is there another way?

A: Testing can be done on several levels on "reality", and each of them have their purposes.
You have written an rspec feature spec. These are in the category of so called "acceptance" tests.
The RSpec documentation says:

Feature specs are high-level tests meant to exercise slices of functionality
  through an application. They should drive the application only via its external
  interface, usually web pages.

So point of these test are to be as real as possible, and this also means having as objects as real as possible.
Your observation is correct, there is a lot of setup to be done for these kinds of tests, and they do get quite slow quite fast. And that's why you don't usually write too many of these.
The fast test are in separate category. These are called "unit" test. The point of them is to test only a single class of method, and if there are any dependencies to other classes you should stub them.
These are the kind of tests you should having a lot. And you should drive to write those classes in such a manner that you can easily stub out all the external dependencies (db for example).
This concept is called the testing pyramid. https://martinfowler.com/bliki/TestPyramid.html


text:
Q: The Electorate badge's description is unclear I was recently awarded the Electorate badge, so I took a look at its description:

Electorate: Voted on 600 questions and 25% or more of total votes are on questions.

It sounds, at first glance, like the system is awarding 25% of question votes which are votes on questions. What?

A: Is this more clear?

Electorate: 25-100% of total votes are on 600+ questions.


text:
Q: Alterar link do botao de acordo com um radio Pessoal é uma coisa besta eu sei, mas estou quebrando a cabeça, preciso de ajuda quem puder agradeço.
.
estou fazendo um simples formulário, preciso que tenha uma pergunta de classificação, se a pessoa escolher a opção a o link muda exemplo pro google.com.br, se a pessoa escolher a opção b o link muda exemplo pro yahoo.com.br e se a pessoa escolher a opção c o link muda exemplo pro terra.com.br
.
cheguei a isso, mas não funciona:

  jQuery(function($){
        $('#male, #female, #other').change(function(){
  var volume = $('#male').val();
    var volume = $('#female').val();
    var volume = $('#other').val();

  if (other == "other") {
             $('.LinkBotao').attr('href', 'http://www.google.com.br');
  }
  else if (male == "male") {
      $('.Linkbotao').attr('href', 'http://www.uol.com.br');
  }
  else if (female == "female") {
      $('.Linkbotao').attr('href', 'http://www.yahoo.com.br');
  }
 });
});
// JavaScript Document

<form action="">

  <input type="radio" name="gender" value="male"> Male

  <input type="radio" name="gender" value="female"> Female

  <input type="radio" name="gender" value="other"> Other

       <input type="button" name="aderir" id="aderir" value="aderir">

</form>

A: Você precisa tratar o change pelo name
 $('input[type=radio][name=gender]').change(function() {
        if (this.value == 'male') {
            $('.LinkBotao').attr('href', 'http://www.google.com.br');
        }else if (this.value == 'female') {
            $('.LinkBotao').attr('href', 'http://www.uol.com.br');
        }else if (this.value == 'other') {
            $('.LinkBotao').attr('href', 'http://www.yahoo.com.br');
        }
 });

A: Fiz algumas pequenas alterações mas tentei deixar o máximo possível parecido com o seu código.

<form action="">

  <input type="radio" name="gender" value="male" class="gender"> Male

  <input type="radio" name="gender" value="female" class="gender"> Female

  <input type="radio" name="gender" value="other" class="gender"> Other

       <input type="button" name="aderir" id="aderir" value="aderir">

</form>


text:
Q: what is "struct* struct newStruct(int somedata) { } " syntax in c++ I was trying to make a tree in c++ and came across this code which is really confusing me.
struct node
{
    int data;
    struct node* left;
    struct node* right;
};

// The code bellow this is the part i dont understand
struct node* newNode(int idata)
{
    node* node = new struct node;
    node->data = idata;
    node->left = NULL;
    node->right = NULL;
    return node;
}

what is struct node* ? Some kind of a structure, but a pointer? Also shouldn't structs have ; at the end? For example, node has ; at the end of the body but not node* ?

A: struct node* is the return type of function newNode() and not a definition in itself. The line you are referring to is the signature of the function newNode. It is followed by the function definition between the two curly braces {}. A function definition does not need a ; at the end.


text:
Q: websocket - Error in connection establishment: net::ERR_INSECURE_RESPONSE Can't connect to websocket server..
I use the exact same private.key and public.crt that I use with nginx
The cert is self-signed but works fine with the rest of the website over HTTPS via nginx
The websocket server works when using ws:// when the line with http.ListenAndServe() is uncommented
package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

const PORT uint = 8000

func main(){
    host := parse_flags()

    hub := newHub()
    go hub.run()

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        serve(hub, w, r)
    })

    server_host := fmt.Sprintf("%s:%d", host, PORT)

    log.Println("Server listening on:", server_host)

    err := http.ListenAndServeTLS(server_host, fmt.Sprintf("/var/ini/ssl/%s/public.crt", host), fmt.Sprintf("/var/ini/ssl/%s/private.key", host), nil)
    //err := http.ListenAndServe(server_host, nil)
    if err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

A: I had the same error, but I don't know your urls.
I used https://localhost:port for HTTPS and wss://127.0.0.1:port for WS.
So I had to accept the cert for https://localhost and https://127.0.0.1 (only in Chrome).

A: It looks like newest version of Chrome now rejects SHA-1 certs as being insecure. You probably need to move to SHA-2 certs.

A: I was struggling with this issue and many others until I realized I was looking in the wrong place for my key files all together!
First off, the cert and key both need to be .PEM files. I'm using Let's Encrypt, so it was a little easier for me to find the right place (which was /etc/letsencrypt/live/domainName).
If you used a wizard to install your SSL certificate like I did, then you'll need to do a little research on the certificate provider. Just look up where your keys are installed by them and find the .PEM files that seem appropriate for a "cert" and "key".


text:
Q: MPI partition a matrix into smaller matrices The situation is this:
I have an array of dimensions 4x4 and what I have to do is partition this matrix into "blocks"(aka smaller matrices) and distribute them to the "slave-processes". More specifically, suppose the total amount of processes is 4(1 master, 3 slaves and all will calculate what is to be calculated) which makes the partitioning of the 4x4 matrix into four 2x2 matrices. However besides making "buffers" of size 2x2 should be avoid(actually I want to avoid it).
The question is: is there any "clever", more "painless" way to do manage it?
PS: I have to manage this problem http://www.cas.usf.edu/~cconnor/parallel/2dheat/2dheat.html meaning that a Cartesian Communicator will be created.

A: This is essentially how (plain) MPI works. The 2×2 matrices constitute a distributed data structure. Together, they comprise the actual 4×4 matrix. You could of course also use four 1×4 or 4×1 matrices, that does have some advantages (easier programming) and disadvantages (more communication needed when scaling).
In actual problems, such as a 2D heat equation, you often need to consider the halo around each local matrix. This halo is then exchanged during simulation step.
Note that the code you linked uses full sized matrices on each worker rank. This is a simplification, but wastes resources and is thus not scalable.
MPI gives you some help to manage those distributed data, for instance via Cartesian communicators, or one-sided communication for easier halo-exchange, but essentially you have to manage the distributed data structure.
There are parallel paradigms that provide higher level abstractions of distributed data structures, but even an overview would IMHO bee too broad for this format. Many of those are related to the Partitioned Global Address Space (PGAS) concept. Implementations can range from new languages, language extensions (Co-array Fortran) to libraries and frameworks. Some use MPI internally.


text:
Q: Python scraping problem "TypeError: can only concatenate str (not "ResultSet") to str" I am fresh noobster who tries to learn python as well as use it for webscraping.
So I watched a few videos to learn the basics on youtube, followed the tutorial, however I cannot figure it out why my code does not work.
Here is the code:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.newegg.com/global/lt-en/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphic%20card'

#opening up the connection grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#HTML parser
page_soup = soup(page_html, "html.parser")

#grabs all containers
containers = page_soup.findAll("div",{"class":"item-container"})

filename= "123.csv"
f = open(filename, "w")

headers = "brand, product_name, product_price\n"

f.write(headers)

for container in containers:
    brand = container.findAll("a",{"class":"title"})

    title_container = container.findAll("a",{"class":"item-title"})
    product_name = title_container[0].text

    price_container = container.findAll("li",{"class":"price-current"})
    product_price = price_container[0].text.strip()

print("brand: " + brand)
print("product_name: " + product_name)
print("product_price: " + product_price)

f.write(brand + "," + product_name.replace(",", "|") + "," + product_price + "\n")

f.close()

Here is the error I get:
(base) C:\Windows\system32>firstwebscrape.py
Traceback (most recent call last):
  File "C:\Users\31947\Documents\Python\firstwebscrape.py", line 34, in <module>
    print("brand: " + brand)
TypeError: can only concatenate str (not "ResultSet") to str

How to solve this problem?

A: Your error is due to the type of brand, and I think you have an answer in the comments.
But, you have an issue when you get the brand name. Check in the following the solution. I get the brand name from the img tag:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.newegg.com/global/lt-en/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphic%20card'

# opening up the connection grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# HTML parser
page_soup = soup(page_html, "html.parser")

# grabs all containers
containers = page_soup.findAll("div", {"class": "item-container"})

filename = "123.csv"
f = open(filename, "w")

headers = "brand, product_name, product_price\n"

f.write(headers)

for container in containers:
    brand = container.findAll("img", {"class": " lazy-img"})[1]['title']

    title_container = container.findAll("a", {"class": "item-title"})
    product_name = title_container[0].text

    price_container = container.findAll("li", {"class": "price-current"})
    product_price = price_container[0].text.strip()

    print("brand: " + brand)
    print("product_name: " + product_name)
    print("product_price: " + product_price)

    f.write(brand + "," + product_name.replace(",", "|") + "," + product_price + "\n")

f.close()

Output:
brand: ASUS
product_name: ASUS ROG Strix GeForce RTX 2080 Ti DirectX 12 ROG-STRIX-RTX2080TI-11G-GAMING Video Card
product_price: €1.171,99

–
brand: Sapphire Tech
product_name: Sapphire PULSE Radeon RX 570 4GB GDDR5 PCI-E Dual HDMI / DVI-D / Dual DP OC w/ Backplate (UEFI), 100412P4GOCL
product_price: €120,99

–
brand: GIGABYTE
product_name: GIGABYTE GeForce RTX 2070 Super WINDFORCE OC 3X 8G Graphics Card, GV-N207SWF3OC-8GD
product_price: €468,99 (3 Offers)

–
brand: ASUS
product_name: ASUS ROG Strix GeForce RTX 2080 Ti DirectX 12 ROG-STRIX-RTX2080TI-O11G-GAMING Video Card
product_price: €1.159,99 (2 Offers)

–
brand: MSI
product_name: MSI GeForce GTX 1660 DirectX 12 GTX 1660 VENTUS XS 6G OC Video Card
product_price: €200,99 (3 Offers)

–
brand: GIGABYTE
product_name: GIGABYTE Radeon RX 570 DirectX 12 GV-RX570GAMING-4GD REV2.0 Video Card
product_price: €113,99 (2 Offers)

–
brand: EVGA
product_name: EVGA GeForce RTX 2060 SC Ultra GAMING, 06G-P4-2067-KR, 6GB GDDR6, Dual HDB Fans
product_price: €334,99 (3 Offers)

–
brand: ASUS
product_name: ASUS Dual GeForce RTX 2080 Ti DirectX 12 DUAL-RTX2080TI-O11G Video Card
product_price: €1.096,99 (2 Offers)

–
brand: EVGA
product_name: EVGA GeForce RTX 2070 SUPER XC GAMING, 08G-P4-3172-KR
product_price: €510,99 (3 Offers)

–
brand: ASUS
product_name: ASUS ROG Strix Radeon RX 570 O4G Gaming OC Edition GDDR5 DP HDMI DVI VR Ready AMD Graphics Card (ROG-STRIX-RX570-O4G-GAMING)
product_price: €132,99

–
brand: ZOTAC
product_name: ZOTAC GeForce GTX 1060 DirectX 12 ZT-P10620A-10M Video Card
product_price: €199,99

–
brand: ASUS
product_name: ASUS ROG STRIX GeForce RTX 2060 SUPER DirectX 12 ROG-STRIX-RTX2060S-A8G-GAMING Video Card
product_price: €403,99 (2 Offers)

A: Hi In the above code You are trying to concatenate a "string" with a "list" using "+" symbol
print("brand: " + brand)

Change the above line to
print("brand: " + str(brand))
#or
print("brand: " , brand)

Also Change
   f.write(str(brand) + "," + product_name.replace(",", "|") + "," + product_price + "\n") # convert brand to string here

So The complete code will be like this
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.newegg.com/global/lt-en/Video-Cards-Video-
Devices/Category/ID-38?Tpk=graphic%20card'

#opening up the connection grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#HTML parser
page_soup = soup(page_html, "html.parser")

#grabs all containers
containers = page_soup.findAll("div",{"class":"item-container"})

filename= "123.csv"
f = open(filename, "w")

headers = "brand, product_name, product_price\n"

f.write(headers)

for container in containers:
    brand = container.findAll("a",{"class":"title"})

    title_container = container.findAll("a",{"class":"item-title"})
    product_name = title_container[0].text

    price_container = container.findAll("li",{"class":"price-current"})
    product_price = price_container[0].text.strip()

print("brand: " + str(brand))
print("product_name: " + product_name)
print("product_price: " + product_price)

f.write(str(brand) + "," + product_name.replace(",", "|") + "," + product_price + "\n")

f.close()


text:
Q: Why does sha1sum act differently with the same input? I'm trying to replicate the behavior of the sha1sum executable in some java code, however, in the process I've discovered that sha1sum appears to behave differently given the same input in two scenarios.
Assume input of '12345' without the single quotes and with no newline.
If I put this data into a file (file1) and run sha1sum from the command line:
$ sha1sum file1
8cb2237d0679ca88db6464eac60da96345513964  file1

However, if I do this, I get a different result:
$ cat file1 | grep -vi foo | grep -vi bar | sha1sum
2672275fe0c456fb671e4f417fb2f9892c7573ba  -

Using the apache commons-codec jar, I'm able to read in file1, get it's contents, and perform a .shahex() on the content and get the first result.  However, I need to get the second result (due to legacy code) and I can't figure out why sha1sum is behaving differently, or what grep is doing to the input.
The system is running CentOS 5.4 with sha1sum 5.97
Any pointers?

A: Confirm the sequences are identical, first:
$ cat file1 | grep -vi foo | grep -vi bar > /tmp/junk
$ cmp file1 /tmp/junk

otherwise you'll just be chasing your tail.

A: grep adds a newline.
$ hd file1
00000000  31 32 33 34 35                                    |12345|
00000005
$ grep -vi test <file1 | hd
00000000  31 32 33 34 35 0a                                 |12345.|
00000006

To get the same result you should add a single \n  at end of input if it is not present.

A: Is your grep aliased to have --color? Have you checked the output of your pipeline without sha1sum in it?


text:
Q: Volume estimation with differential equations The problem reads:
"Using differential equations, estimate the volume necessary to build a tube that is 12m long and has an inner diameter of 25cm and an outer diameter of 25,2 cm."
Unfortunately I couldn't find any similar problems online so I'm at a dead end.

A: The volume of a cylinder is given by:$$
V = \pi r^2h
$$Since the inner and outer diameter can be seen as a change in radius, we could differentiate with respect to the radius to get:$$
dV = 2\pi rh~dr
$$We only want the outer shell of our growing cylinder, since it will have the shape of a tube. The volume of this outer shell is given by $\Delta V$:$$
\Delta V \approx 2\pi rh~\Delta r
$$We can use $r=25/2$, $h=12$ and $\Delta r = (25-25.2)/2$.
Just make sure you convert units to be consistent.

A: you can approximate the volume by the formula $ volume \simeq surface \space area \times height. $ approximate volume is $$\text{volume} \simeq 1200 \times (\pi 25) \times 0.1 \text{cm}^3. $$


text:
Q: Decision function uncountable, why? Good morning guys,
I'm a new user of StackExchange, and I have already found here:
Set of decision functions are uncountable
However, I do not really understand the answer. I'm a student of Computer Science, so my math is not really good :)
I'm studing the subject computability, in particular, I understand that there are more decision functions than the Turing Machines (TM), thus there are decision functions that cannot be solved by a TM.
However, my notes say:
$\text{LEMMA:}$
The set of decision functions $ f:\mathbb{N} \rightarrow\{0,1\}$ is uncountable.
Can I ask why? as far as I understand countable means that in some way I can associate al the functions an integer. For example, $\mathbb{N}$ is countable, because I can associate each element to  $\mathbb{N}$, something like:
1 associated to 1
2 associated to 2
3 associated to 3
etc etc etc ....
Thanks in advance :)

A: Let's assume that you could associate (list) all the decision functions to the natural numbers. Let's call the decision function that you associate with $n$ simply $f_n$.
Let's construct a special decision function $f_C$. We set
$$f_C(n)=\left\{\begin{matrix} 0, & \text{if} f_n(n)=1 \\ 1, & \text{if} f_n(n)=0\end{matrix}\right.$$
This is a decision function, and it has the property that it cannot be found in your list, because for any $n$ it differs from $f_n$ at least for the argumnent $n$. So your assumption that you could list all decison functions is impossible.
That proof idea is the famous Cantor diagonal argument, and you can see it referenced on the wikipedia page about the power set, which explains this and more: https://en.wikipedia.org/wiki/Power_set


text:
Q: How to compute a summary by group with dplyr with a function that takes a matrix as argument I'm evaluating the test-retest reliability of a questionnaire.
I've got more than 200 pairs of variables (nominal, ordinal, or numeric), each measured at test and retest, for whom I compute a concordance statistic and its bootstrapped confidence interval.
I managed to create a function to obtain the 3 computations (estimation, lower and upper bound) for each pairs in a single step but I struggle to creating one allowing me to group the results by supplementary variables.
Because I'll need to plot the results, I would like eventually a dataframe output.
For simplicity, I made a toy example of 8 variables in a dataframe called dfSO
dput(dfSO)
structure(list(qordi1T = structure(c(5L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 4L, 5L, 5L, 4L, 2L, 5L, 5L, 3L), .Label = c("Je n'ai pas de médecin de médecin généraliste attitré",
"Moins d'un an", "1 à 2 ans", "2 à 5 ans", "Plus de 5 ans"), class = c("ordered",
"factor")), qordi2T = structure(c(3L, 3L, 2L, 4L, 4L, 4L, 1L,
2L, 1L, 3L, 4L, 5L, 3L, 3L, 5L, 2L), .Label = c("Mauvaise", "Passable",
"Bonne", "Très bonne", "Excellente"), class = c("ordered", "factor"
)), qnum1T = c(70L, 90L, 90L, 100L, 100L, 70L, 80L, 100L, 50L,
40L, 100L, 100L, 75L, 75L, 95L, 40L), qnum2T = c(100L, 85L, 100L,
100L, 100L, 100L, 100L, 85L, 100L, 70L, 100L, 100L, 95L, 75L,
100L, 80L), qnomi1T = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L,
2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L), .Label = c("Oui", "Non"), class = "factor"),
    qnomi2T = structure(c(1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L,
    2L, 1L, 1L, 1L, 2L, 1L, 2L), .Label = c("Oui", "Non"), class = "factor"),
    proT = structure(c(7L, 7L, 5L, 7L, 5L, 7L, 4L, 7L, 1L, 6L,
    7L, 1L, 1L, 5L, 4L, 5L), .Label = c("Agriculteur exploitant",
    "Artisan, commerçant, chef d'entreprise", "Cadre ou profession intellectuelle supérieure :- Profession libérale et assimilée- Cadre de la fonction publique- Profession intellectuelle et artistique- Cadre d'entreprise et ingénieur",
    "Employé :- de la fonction publique- administratif d'entreprise- de commerce- Personnel de services directs aux particuliers",
    "Ouvrier :- qualifié de type industriel, artisanal, de la manutention, du magasinage et du transport, chauffeurs- non qualifié de type industriel et artisanal- agricole",
    "Profession intermédiaire :- de l'enseignement, de la santé, de la fonction publique et assimilés- administrative et commerciales des entreprises- Technicien- Contremaître, agent de maîtrise",
    "N/A"), class = "factor"), sexT = structure(c(1L, 1L, 1L,
    2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("Femme",
    "Homme"), class = "factor"), qordi1RT = structure(c(5L, 3L,
    4L, 5L, 5L, 5L, 5L, 5L, 4L, 4L, 5L, 4L, 2L, 5L, 5L, 2L), .Label = c("Je n'ai pas de médecin de médecin généraliste attitré",
    "Moins d'un an", "1 à 2 ans", "2 à 5 ans", "Plus de 5 ans"
    ), class = c("ordered", "factor")), qordi2RT = structure(c(3L,
    4L, 1L, 4L, 4L, 5L, 2L, 2L, 2L, 3L, 4L, 5L, 3L, 3L, 5L, 2L
    ), .Label = c("Mauvaise", "Passable", "Bonne", "Très bonne",
    "Excellente"), class = c("ordered", "factor")), qnum1RT = c(67L,
    87L, 88L, 100L, 94L, 79L, 100L, 100L, 50L, 55L, 100L, 99L,
    88L, 70L, 89L, 18L), qnum2RT = c(98L, 89L, 99L, 100L, 81L,
    100L, 100L, 100L, 100L, 77L, 63L, 99L, 98L, 71L, 100L, 100L
    ), qnomi1RT = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L,
    2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L), .Label = c("Oui", "Non"), class = "factor"),
    qnomi2RT = structure(c(1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L,
    2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Oui", "Non"), class = "factor"),
    proRT = structure(c(7L, 7L, 5L, 4L, 7L, 7L, 4L, 7L, 1L, 6L,
    4L, 1L, 1L, 5L, 4L, 7L), .Label = c("Agriculteur exploitant",
    "Artisan, commerçant, chef d'entreprise", "Cadre ou profession intellectuelle supérieure :- Profession libérale et assimilée- Cadre de la fonction publique- Profession intellectuelle et artistique- Cadre d'entreprise et ingénieur",
    "Employé :- de la fonction publique- administratif d'entreprise- de commerce- Personnel de services directs aux particuliers",
    "Ouvrier :- qualifié de type industriel, artisanal, de la manutention, du magasinage et du transport, chauffeurs- non qualifié de type industriel et artisanal- agricole",
    "Profession intermédiaire :- de l'enseignement, de la santé, de la fonction publique et assimilés- administrative et commerciales des entreprises- Technicien- Contremaître, agent de maîtrise",
    "N/A"), class = "factor"), sexRT = structure(c(1L, 1L, 1L,
    2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("Femme",
    "Homme"), class = "factor")), row.names = c(NA, -16L), class = "data.frame")

There are 2 ordinal variables, 4 nominal  and 2 numeric, each measured at test (T) and retest (RT)
> str(dfSO)
'data.frame':   16 obs. of  16 variables:
 $ qordi1T : Ord.factor w/ 5 levels "Je n'ai pas de médecin de médecin généraliste attitré"<..: 5 4 4 5 5 5 5 5 4 5 ...
 $ qordi2T : Ord.factor w/ 5 levels "Mauvaise"<"Passable"<..: 3 3 2 4 4 4 1 2 1 3 ...
 $ qnum1T  : int  70 90 90 100 100 70 80 100 50 40 ...
 $ qnum2T  : int  100 85 100 100 100 100 100 85 100 70 ...
 $ qnomi1T : Factor w/ 2 levels "Oui","Non": 2 2 2 1 1 1 2 2 2 1 ...
 $ qnomi2T : Factor w/ 2 levels "Oui","Non": 1 2 2 1 2 1 2 2 2 2 ...
 $ proT    : Factor w/ 7 levels "Agriculteur exploitant",..: 7 7 5 7 5 7 4 7 1 6 ...
 $ sexT    : Factor w/ 2 levels "Femme","Homme": 1 1 1 2 2 1 1 1 1 2 ...
 $ qordi1RT: Ord.factor w/ 5 levels "Je n'ai pas de médecin de médecin généraliste attitré"<..: 5 3 4 5 5 5 5 5 4 4 ...
 $ qordi2RT: Ord.factor w/ 5 levels "Mauvaise"<"Passable"<..: 3 4 1 4 4 5 2 2 2 3 ...
 $ qnum1RT : int  67 87 88 100 94 79 100 100 50 55 ...
 $ qnum2RT : int  98 89 99 100 81 100 100 100 100 77 ...
 $ qnomi1RT: Factor w/ 2 levels "Oui","Non": 2 2 2 2 1 1 2 2 2 1 ...
 $ qnomi2RT: Factor w/ 2 levels "Oui","Non": 1 2 2 1 2 1 2 2 1 2 ...
 $ proRT   : Factor w/ 7 levels "Agriculteur exploitant",..: 7 7 5 4 7 7 4 7 1 6 ...
 $ sexRT   : Factor w/ 2 levels "Femme","Homme": 1 1 1 2 2 1 1 1 1 2 ...

To compute the concordance statistic on qualitative variable, the rel::gac function takes as input a matrix with n subjects and two observations (n*2 matrix)
I made the following function to extract Gwet AC2 (quadratic ponderation) estimations and its bootstrapped CI for ordered variables
library("rel")
library("boot")

ordiTF <- sapply(dfSO[, 1:8], is.ordered)
ordi <- which(ordiTF == TRUE)

g <- function(data, x)
  gac(data[x, c(1, 2)], weight = "quadratic", conf.level = 1-(0.05/8))[[5]]

offset <- 8
B <- 500
item <- c()
est <- c()
lci <- c()
uci <- c()
for (i in ordi) {
  item <- c(item, i)
  est <- c(est, gac(data = dfSO[ , c(i, i + offset)], weight = "quadratic", conf.level = 1-(0.05/8))[[5]])
  b <- boot(dfSO[ ,c(i, i + offset)], g, B)
  lci <- c(lci, boot.ci(b, type = "bca")$bca[4])
  uci <- c(uci, boot.ci(b, type = "bca")$bca[5])
}
data.frame(item = item, est = est, lci = lci, uci = uci)

What I would like now, is to compute this statistic for each pairs by a third variable, say 'sex'.
I'll begin with grouping by this variable, but then I'm not able anymore to specify the columns adequately.
For example, if I want to compute AC2 between ordi1 at test and retest by sex with dplyr, I don't know anymore how to specify these variables.
I tried different options, among which:
dfSO %>%
  group_by(sexT) %>%
  select(sexT, qordi1T, qordi1RT) %$%
  gac(as.matrix(qordi1T, qordi1RT), weight = "quadratic")[[5]]

But none of them did the job
As a non-english native speaker, my first limitation to answer this pb is my difficulty to google it, and I'm aware that this question might have been already asked, but if so, I wasn't able to find it.
Thanks for your time and for your help
Folowing @42 remarks, I made several edits
Regarding the boot issue, I'm not sure to understand what's wrong with my syntax, so I'll begin with my initial problem

*

*Error output

Here is the error output I obtained
    > dfSO %>%
    +     group_by(sexT) %>%
    +     select(sexT, qordi1T, qordi1RT) %$%
    +     gac(as.matrix(qordi1T, qordi1RT), weight = "quadratic")[[5]]

    Error in gac(as.matrix(qordi1T, qordi1RT), weight = "quadratic") :
      The data frame needs to be formatted as a n*2 matrix!

*I made a wrong copy-paste in my initial code, copying a desperate attempt to use %$% instead of %>% (that's what I meant saying "none of them did the job"). It should have been

    dfSO %>%
        group_by(sexT) %>%
        select(sexT, qordi1T, qordi1RT) %>%
        gac(as.matrix(qordi1T, qordi1RT), weight = "quadratic")

with the same error
    Error in gac(., as.matrix(qordi1T, qordi1RT), weight = "quadratic") :
      The data frame needs to be formatted as a n*2 matrix!

Note that the quoting in gac() doesn't suppress the error
    dfSO %>%
        group_by(sexT) %>%
        select(sexT, qordi1T, qordi1RT) %>%
        gac(as.matrix('qordi1T', 'qordi1RT'), weight = "quadratic")

Error in gac(., as.matrix("qordi1T", "qordi1RT"), weight = "quadratic") :
  The data frame needs to be formatted as a n*2 matrix!

*While everything goes find without grouping

    dfSO %>%
        select(qordi1T, qordi1RT) %>%
        gac(as.matrix('qordi1T', 'qordi1RT'), weight = "quadratic")

    Call:
    gac(data = ., kat = as.matrix("qordi1T", "qordi1RT"), weight = "quadratic")

          Estimate   StdErr  LowerCB UpperCB
    Const 0.860780 0.097708 0.652520   1.069

    Confidence level = 95%
    Sample size = 16

*Finally, using magrittr::extract2() allows one to extract the estimation (replace the [[5]] part of the g function)

    dfSO %>%
      select(qordi1T, qordi1RT) %>%
      gac(as.matrix('qordi1T', 'qordi1RT'), weight = "quadratic") %>%
      extract2('est')

        Const
    0.8607799

*Now, back to my grouping issue. As I group by a third variable, I'm not able to compute the coefficient for each of its level (see edit #2). I believe that the problem lies in the fact that gac() takes as input a matrix and not a dataframe.

Ideally, I would like to obtain a dataframe like this
    > AC2_ordi_bySexT
      item  SexT       AC2    AC2_lci   AC2_uci
    1    1 Homme 0.6551724  0.4182536 0.9832149
    2    2 Homme 1.0000000 -0.4163015 0.9023788
    3    1 Femme 0.8734663  0.5308729 0.9780148
    4    2 Femme 0.4605954 -0.3208255 0.9073359

*So what I would like is to adapt my g function in order to obtain a dataframe like this for each grouping variable (sex, age, ...)

*Finally, I edited my title question. I hope it now fits better its content.


text:
Q: Android BitmapFactory.decodeFile on jpeg file returns null My app calls the camera to take a picture and save it into my app local directory (getApplicationContext().getFilesDir()) which works fine.
When I try to convert the picture into a bitmap using BitmapFactory the result is null. This the code I use :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;

String picturePath = pictureFile.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);

Note that pictureFile was created as follows :
pictureFile = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    foodwarnDir      /* directory */
            );

A: Didn't you forget add permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?
File locationOfFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File destination= new File(locationOfFile , fileName + ".JPG");
FileInputStream fileInputStream;
fileInputStream= new FileInputStream(destination);
Bitmap img = BitmapFactory.decodeStream(fileInputStream);

OR
This is my working code in my project here:
            View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
            ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);

            try {

                String path = uri.getPath();
                Bitmap bmImg = BitmapFactory.decodeFile(path);

                Point p = new Point();
                p.set(100, 100);
                Bitmap bitmapp = waterMark(bmImg, mRefNo, p, Color.RED, 90, 60, true);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmapp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                Glide.with(this)
                        .load(stream.toByteArray())
                        .asBitmap()
                        .error(R.mipmap.ic_launcher)
                        .into(thumbnail);

                mSelectedImagesContainer.addView(imageHolder);
                thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
            } catch (Exception e) {
                e.printStackTrace();
            }

Hope this helps you
other helpful Links1 Link2

A: Create temp file:
File tempFile = File.createTempFile("temp_file, ".jpg", this.getExternalCacheDir());

get path created:
String mPath = tempFile.getAbsolutePath();

now in you activityResult
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);

A: Assuming you're using java.io.File class. According to Java docs function .createTempFile creates empty file on the System.
As such, this file will have only meta info without any content, with zero length, and this is probably a reason why it is not possible to extract Bitmap.
So you need to  Create File Object instance instead of actual file, using new File()
You can also use WeakReference and similar to Bitmap you create if you're looking to decrease  chance of memory leaks in early implementation.

A: use
data.getExtras().get("data");//for getting bitmap
Uri u = intent.getData();// for getting the Uri and get the path from uri

for getting data from your camera


text:
Q: trapping shell exit code I am working on a shell script, and want to handle various exit codes that I might come across. To try things out, I am using this script:
#!/bin/sh
echo "Starting"
trap "echo \"first one\"; echo \"second one\"; " 1
exit 1;

I suppose I am missing something, but it seems I can't trap my own "exit 1". If I try to trap 0 everything works out:
#!/bin/sh
echo "Starting"
trap "echo \"first one\"; echo \"second one\"; " 0
exit

Is there anything I should know about trapping HUP (1) exit code?

A: trap dispatches on signals the process receives (e.g., from a kill), not on exit codes, with trap ... 0 being reserved for process ending.  trap /blah/blah 0 will dispatch on either exit 0 or exit 1

A: That's just an exit code, it doesn't mean HUP. So your trap ... 1 is looking for HUP, but the exit is just an exit.
In addition to the system signals which you can list by doing trap -l, you can use some special Bash sigspecs: ERR, EXIT, RETURN and DEBUG. In all cases, you should use the name of the signal rather than the number for readability.

A: You can also use || operator, with a || b, b gets executed when a failed
#!/bin/sh

failed
{
    echo "Failed $*"
    exit 1
}

dosomething arg1 || failed "some comments"


text:
Q: Having trouble with Android recyclerview with GridLayoutManager in Marshmallow Hi I'm having trouble using recyclerview with GridLayoutManager in Marshmallow. I use a fragment to make a list and here is the code
private RecyclerView mRecyclerView;
private RecyclerCategoryAdapter mListAdapter;
private GridLayoutManager mLayoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_category, container, false);
    mSwipeLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_container);
    mRecyclerView = (RecyclerView) v.findViewById(R.id.category_recyclerview);
    mRecyclerView.setHasFixedSize(true);

    mLayoutManager = new GridLayoutManager(container.getContext(), 2);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if ( mListAdapter != null && mListAdapter.isPositionFooter(position) || mListAdapter.isPositionHeader(position)) {
                return mLayoutManager.getSpanCount();
            } else {
                return 1;
            }
        }
    });
    mRecyclerView.setLayoutManager(mLayoutManager);

    return v;
}

so in case there is header or footer in the list I tried to make the content to fill the width of the screen otherwise it should be 2 column grid layout. The app crashes on the first if statement right after the getSpanSize(int position) is called.
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.memebox.us.adapter.recycler.RecyclerCategoryAdapter.isPositionHeader(int)' on a null object reference
   at com.memebox.us.fragment.CategoryFragment$1.getSpanSize(CategoryFragment.java:96)
   at android.support.v7.widget.GridLayoutManager$SpanSizeLookup.getSpanGroupIndex(GridLayoutManager.java:804)
   at android.support.v7.widget.GridLayoutManager.getSpanGroupIndex(GridLayoutManager.java:357)
   at android.support.v7.widget.GridLayoutManager.getRowCountForAccessibility(GridLayoutManager.java:128)
   at android.support.v7.widget.RecyclerView$LayoutManager.onInitializeAccessibilityNodeInfo(RecyclerView.java:7659)
   at android.support.v7.widget.RecyclerView$LayoutManager.onInitializeAccessibilityNodeInfo(RecyclerView.java:7619)
   at android.support.v7.widget.RecyclerViewAccessibilityDelegate.onInitializeAccessibilityNodeInfo(RecyclerViewAccessibilityDelegate.java:59)
   at android.support.v4.view.AccessibilityDelegateCompat$AccessibilityDelegateJellyBeanImpl$1.onInitializeAccessibilityNodeInfo(AccessibilityDelegateCompat.java:233)
   at android.support.v4.view.AccessibilityDelegateCompatJellyBean$1.onInitializeAccessibilityNodeInfo(AccessibilityDelegateCompatJellyBean.java:61)
   at android.view.View.onInitializeAccessibilityNodeInfo(View.java:6619)
   at android.view.View.createAccessibilityNodeInfoInternal(View.java:6580)
   at android.view.View$AccessibilityDelegate.createAccessibilityNodeInfo(View.java:23704)
   at android.view.View.createAccessibilityNodeInfo(View.java:6563)
   at android.view.accessibility.AccessibilityRecord.setSource(AccessibilityRecord.java:145)
   at android.view.accessibility.AccessibilityRecord.setSource(AccessibilityRecord.java:119)
   at android.view.View.onInitializeAccessibilityEventInternal(View.java:6517)
   at android.view.View$AccessibilityDelegate.onInitializeAccessibilityEvent(View.java:23616)
   at android.support.v4.view.AccessibilityDelegateCompatIcs.onInitializeAccessibilityEvent(AccessibilityDelegateCompatIcs.java:92)
   at android.support.v4.view.AccessibilityDelegateCompat$AccessibilityDelegateIcsImpl.onInitializeAccessibilityEvent(AccessibilityDelegateCompat.java:179)
   at android.support.v4.view.AccessibilityDelegateCompat.onInitializeAccessibilityEvent(AccessibilityDelegateCompat.java:419)
   at android.support.v7.widget.RecyclerViewAccessibilityDelegate.onInitializeAccessibilityEvent(RecyclerViewAccessibilityDelegate.java:65)
   at android.support.v4.view.AccessibilityDelegateCompat$AccessibilityDelegateJellyBeanImpl$1.onInitializeAccessibilityEvent(AccessibilityDelegateCompat.java:228)
   at android.support.v4.view.AccessibilityDelegateCompatJellyBean$1.onInitializeAccessibilityEvent(AccessibilityDelegateCompatJellyBean.java:56)
   at android.view.View.onInitializeAccessibilityEvent(View.java:6503)
   at android.view.View.sendAccessibilityEventUncheckedInternal(View.java:6364)
   at android.view.View$AccessibilityDelegate.sendAccessibilityEventUnchecked(View.java:23555)
   at android.support.v4.view.AccessibilityDelegateCompatIcs.sendAccessibilityEventUnchecked(AccessibilityDelegateCompatIcs.java:117)
   at android.support.v4.view.AccessibilityDelegateCompat$AccessibilityDelegateIcsImpl.sendAccessibilityEventUnchecked(AccessibilityDelegateCompat.java:210)
   at android.support.v4.view.AccessibilityDelegateCompat.sendAccessibilityEventUnchecked(AccessibilityDelegateCompat.java:358)
   at android.support.v4.view.AccessibilityDelegateCompat$AccessibilityDelegateJellyBeanImpl$1.sendAccessibilityEventUnchecked(AccessibilityDelegateCompat.java:255)
   at android.support.v4.view.AccessibilityDelegateCompatJellyBean$1.sendAccessibilityEventUnchecked(AccessibilityDelegateCompatJellyBean.java:82)
   at android.view.View.sendAccessibilityEventUnchecked(View.java:6347)
   at android.support.v7.widget.RecyclerView.sendAccessibilityEventUnchecked(RecyclerView.java:2649)
   at android.view.View$SendViewStateChangedAccessibilityEvent.run(View.java:23741)
   at android.view.View$SendViewStateChangedAccessibilityEvent.runOrPost(View.java:23774)
   at android.view.View.notifyViewAccessibilityStateChangedIfNeeded(View.java:9367)
   at android.view.View.onFocusChanged(View.java:6232)
   at android.view.View.clearFocusInternal(View.java:6124)
   at android.view.View.unFocus(View.java:6169)
   at android.view.ViewGroup.unFocus(ViewGroup.java:1010)
   at android.view.ViewGroup.unFocus(ViewGroup.java:1012)
   at android.view.ViewGroup.unFocus(ViewGroup.java:1012)
   at android.view.ViewGroup.unFocus(ViewGroup.java:1012)
   at android.view.ViewGroup.requestChildFocus(ViewGroup.java:750)
   at android.view.ViewGroup.requestChildFocus(ViewGroup.java:756)
   at android.view.ViewGroup.requestChildFocus(ViewGroup.java:756)
   at android.view.View.handleFocusGainInternal(View.java:5973)
   at android.view.ViewGroup.handleFocusGainInternal(ViewGroup.java:730)
   at android.view.View.requestFocusNoSearch(View.java:9053)
   at android.view.View.requestFocus(View.java:9032)
   at android.view.ViewGroup.requestFocus(ViewGroup.java:3048)
   at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:3093)
   at android.view.ViewGroup.requestFocus(ViewGroup.java:3049)
   at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:3093)
   at android.view.ViewGroup.requestFocus(ViewGroup.java:3049)
   at android.view.View.requestFocus(View.java:8999)
   at android.view.View.requestFocus(View.java:8978)
   at android.support.v4.widget.DrawerLayout.dispatchOnDrawerOpened(DrawerLayout.java:750)
   at android.support.v4.widget.DrawerLayout.updateDrawerState(DrawerLayout.java:700)
   at android.support.v4.widget.DrawerLayout$ViewDragCallback.onViewDragStateChanged(DrawerLayout.java:1833)
   at android.support.v4.widget.ViewDragHelper.setDragState(ViewDragHelper.java:874)
   at android.support.v4.widget.ViewDragHelper$2.run(ViewDragHelper.java:335)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:158)
   at android.app.ActivityThread.main(ActivityThread.java:7229)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

and here is the Adapter code I'm using
public boolean isPositionHeader(int position){
    return position == 0;
}

public boolean isPositionFooter(int position){
    return position == getItemCount() -1 ;
}

@Override
public int getItemCount() {
    return mProductList != null ? mProductList.size() + 2 : 0;
}

I tried to always add two more items on the list as a header and a footer and always add both view on the list (as a full width content)
I wonder why "RecyclerCategoryAdapter.isPositionHeader(int)' on a null object reference" is in the message.
I checked null for the Adapter before calling the method "isPositionHeader(position)" and for the method isPositionHeader doesn't seem to have any possibility for null
It only happened on 6.0 and 6.1 version of Android phone. but never happens to my phone (my phone is nexus 5x). So it's not always happening
Since I just start replacing ListView to Recyclerview I need an advice.
Can anybody help me solving this problem? or Is there anyone who is struggling with the same problem?
Plz ask me if there is more code I need to attach
Thank you

A: You have one small issue with your if statement. Change it to the following:
if (mListAdapter != null && (mListAdapter.isPositionFooter(position) || mListAdapter.isPositionHeader(position)))


text:
Q: splitting the gvim editor window horizontally In gvim editor how to split the editor window horizontally? so that includes two files and can see simultaneously
?

A: From command line:
open specified files as horizontal splits
gvim -o report.log power.log area.log

open specified files as vertical splits
gvim -O report.log power.log area.log

Within the editor
open file for editing in new horizontal split screen
:split filename
:sp filename

open file for editing in new vertical split screen
:vsplit filename
:vs filename

Check out :h windows.txt for more help

A: Ctrl+W, S (upper case) for horizontal splitting


text:
Q: swift what is the best way to retrieve snap nodes from firebase How can I retrieve senderId from this snapshot. ChildAdded must be use and the FirRef below must stay the same.
this is my current func to retrieve the data from firebase
 func retrieveInfo(completion: (result: String)->()) {
       fireBaseAPI().childRef("version_one/frontEnd/post/\(self.previousViewMessageId)").observeEventType(.ChildAdded, withBlock: {snapshot in

     })

This is the snapshot being printed
Snap (postDescription) Description here
Snap (postTitle) What do you need done
Snap (receiverId) RYclS9Qy4vRr6gp8JbfoztSYQnL2
Snap (senderId) niZKOcnoh0cdFpF2K26bxugw1hz1
Snap (status) 0
Snap (messages) {
    "-KRqOqd2POJYpCNSSumG" =     {
        mediaType = TEXT;
        senderDisplayName = "";
        senderId = niZKOcnoh0cdFpF2K26bxugw1hz1;
        text = iPhone;
    };
}

What is the best way to retrieve any of the nodes that says Snap
This is the firebase Json
 {
  "version_one" : {
    "frontEnd" : {
      "post" : {
        "-KRoucvwAs1jBaoNahDP" : {
          "messages" : {
            "-KRqOqd2POJYpCNSSumG" : {
              "mediaType" : "TEXT",
              "senderDisplayName" : "",
              "senderId" : "niZKOcnoh0cdFpF2K26bxugw1hz1",
              "text" : "iPhone"
            }
          },
          "postDescription" : "Description here",
          "postTitle" : "What do you need done",
          "receiverId" : "RYclS9Qy4vRr6gp8JbfoztSYQnL2",
          "senderId" : "niZKOcnoh0cdFpF2K26bxugw1hz1",
          "status" : 0
        }
      },

A: func retrieveInfo(completion: (result: String)->()) {
   fireBaseAPI().childRef("version_one/frontEnd/post/\(self.previousViewMessageId)").observeEventType(.ChildAdded, withBlock: {snapshot in
    if let messageDict = snapshot.value in [String:AnyObject]{

                  let senderId = messageDict["senderId"] as! String
              .....

      }

 })


text:
Q: Mysql visitor stats per user per day structure? I want to track the visitors for each of my users, for each day.
 date | user_id | US | CA |...
 __________________________
      |         |    |    |

My query is
UPDATE mytable SET :country = :country + 1 WHERE user_id = :user_id AND date = :date

Is there a better way to store the users visitor stats for each country per day? The query will be performed 1 million times a day, so it should be lighweight.

A: You want a data structure like this:
create table UserCountries (
    UserCountyId int primary key auto_increment,
    UserId int,
    Country varchar(3)
);

Just insert rows into the table when you encounter them.  Then, pull the data as you like when you query.


text:
Q: Wrong calculated CPU usage using C# and WMI This is my function for enumerating processes on windows box and calculating percentage of CPU usage for each process but results are not correct.
CPU usage does't add up to 100% but more like to 120% or 130% and I don't know what I'm doing wrong.
It seems like it calculats right CPU usage for varoius apps like firefox, VS2010, office,.. but has problems with System Idle Process.
public List<ProcInfo> GetRunningProcesses()
{
    List<ProcInfo> allProcesses = new List<ProcInfo>();
    UInt64 currentProcessCpuTime = 0;
    UInt64 allProcessCpuTime = 0;

    SelectQuery wmiQuery = new SelectQuery("SELECT Name, Description, ProcessId, KernelModeTime, UserModeTime FROM Win32_Process");
    ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(connectionScope, wmiQuery);
    ManagementObjectCollection moc = oSearcher.Get();

    foreach (ManagementObject mo in moc)
    {
        allProcessCpuTime += (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
    }

    foreach (ManagementObject mo in moc)
    {
        currentProcessCpuTime = (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
        allProcesses.Add(new ProcInfo((string)mo["Name"], (string)mo["Description"], (UInt32)mo["ProcessId"], (currentProcessCpuTime / (double)allProcessCpuTime * 100));
    }

    return allProcesses;
}

EDIT:
I found that my function is all wrong.
I'm starting a bounty for the best working solution. Solution needs to work for local and remote system and should be fast.

A: Here is a C# code with performance counters:
public static void DumpProcessesCpu(string machineName)
{
    List<PerformanceCounter> counters = new List<PerformanceCounter>();

    foreach (Process process in Process.GetProcesses(machineName))
    {
        PerformanceCounter processorTimeCounter = new PerformanceCounter(
            "Process",
            "% Processor Time",
            process.ProcessName,
            machineName);

        processorTimeCounter.NextValue();
        counters.Add(processorTimeCounter);
    }

    Thread.Sleep(1000); // 1 second wait, needed to get a sample

    foreach (PerformanceCounter processorTimeCounter in counters)
    {
        Console.WriteLine("Process:{0} CPU% {1}",
            processorTimeCounter.InstanceName,
            processorTimeCounter.NextValue());
    }
}

It's inspired from here: https://learn.microsoft.com/en-us/archive/blogs/bclteam/how-to-read-performance-counters-ryan-byington
You can't really be faster than this, the reason why is explained in the article. Basically, you'll have to read the value twice to get it right, so you need to wait between samples.
However, depending on what you want to do, for example, suppose you want to write a "remote task manager", you can code all this in a background task (thread) and regularly update the values so the end-user will not really see the delay between samples.

A:         var mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
        var run1 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => (ulong)mo.Properties["PercentProcessorTime"].Value);
        Thread.Sleep(570); // can be an arbitrary number
        var run2 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => (ulong)mo.Properties["PercentProcessorTime"].Value);

        var total = run2["_Total"] - run1["_Total"];

        foreach (var kvp in run1)
        {
            var proc = kvp.Key;
            var p1 = kvp.Value;
            if (run2.ContainsKey(proc))
            {
                var p2 = run2[proc];
                Console.WriteLine("{0}: {1:P}", proc, (double)(p2 - p1) / total);
            }
        }

A: Here is a C# block of code tested and validated and thanks to fejesjoco, I used his code and made the test to get it to work.
public class CPUUtilizationTests
{

    [Test]
    public void TestPercentProcessorTime()
    {
        Assert.That(PercentProcessorTime("Idle"), Is.Not.GreaterThan(100.0));
    }

    public float PercentProcessorTime(string processName)
    {
        var mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
        var run1 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);
        System.Threading.Thread.Sleep(1000); // can be an arbitrary number
        var run2 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);

        if (!run2.ContainsKey(processName)) throw new Exception(string.Format("Process not found: {0}", processName));

        string percentageProcessorTime = "PercentProcessorTime";
        string total = "_Total";

        ulong percentageDiff = (ulong)run2[processName][percentageProcessorTime] - (ulong)run1[processName][percentageProcessorTime];
        ulong totalDiff = (ulong)run2[total][percentageProcessorTime] - (ulong)run1[total][percentageProcessorTime];

        return ((float)percentageDiff / (float)totalDiff)*100.0f;
    }

}