How would you authorize indvidual attributes when viewing

Question: Looking to be able to authorize certain users to have the ability to view fields not just have restrictions on the entire object
Comment: Welcome to Stackoverflow. This is not a good question, see [here](https://stackoverflow.com/help/how-to-ask) how it should look like. Please rework your question and add an example.
Answer: Trying to help you, as part of the documentation:

With Pundit you can control which attributes a user has access to update via your policies. You can set up a permitted_attributes method in your policy like this:

# app/policies/post_policy.rb
 class PostPolicy < ApplicationPolicy
     def permitted_attributes
         if user.admin? || user.owner_of?(post)
             [:title, :body, :tag_list]
         else
             [:tag_list]
         end
    end
end

There is also a helper which can control permissions per action
permitted_attributes(record, action = action_name) which can be used instead.
Or, most probaby, you want to use scopes which define access to certain attributes.
From the documentation about scopes:

Often, you will want to have some kind of view listing records which a particular user has access to. When using Pundit, you are expected to define a class called a policy scope. It can look something like this:

class PostPolicy < ApplicationPolicy
  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user  = user
      @scope = scope
    end

    def resolve
      if user.admin?
        scope.all
      else
        scope.where(published: true)
      end
    end
  end

  def update?
    user.admin? or not record.published?
  end
end


group_concat sqlite and order by

Question: I am trying to order within group_concat in sqlite3. This is not supported in the way that it is for mysql, so I CAN NOT do this:
group_concat(logID order by logDateTime DESC)

My full query is here, I need logID to be ordered by logDateTime. I read about a subquery method here: Sqlite group_concat ordering but I was unable to get it to work in my query.
SELECT logID,
       NULL AS sessionID,
       logDateTime,
       NULL AS sessionName,
       NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL

UNION ALL

SELECT NULL,
       sessions.sessionID,
       MAX(logDateTime),
       sessions.sessionName,
       group_concat(logID)
FROM logs
JOIN sessions ON logs.sessionID = sessions.sessionID
GROUP BY sessions.sessionID

ORDER BY 3 DESC

Comment: Possible duplicate of [Sqlite group\_concat ordering](https://stackoverflow.com/questions/1897352/sqlite-group-concat-ordering)
Answer: This orders the subquery, but SQLite doesn't guarantee that the order remains in all cases:
SELECT logID,
       NULL AS sessionID,
       logDateTime,
       logName,
       NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL

UNION ALL

SELECT NULL,
       sessionID,
       MAX(logDateTime),
       sessionName,
       group_concat(logName)
FROM (SELECT sessions.sessionID AS sessionID,
             logDateTime,
             sessionName,
             logName
      FROM logs JOIN sessions ON logs.sessionID = sessions.sessionID
      ORDER BY sessions.sessionID,
               logName)
GROUP BY sessionID

ORDER BY 3 DESC

Comment: You again, thanks! A bit frustrating how close I am getting to what I need, only being held back by the limited nature of sqlite. Do you know of any alternative methods to ensure my logID's come back ordered by logDateTime. My final application will actually have several columns that need to be returned just like logID shown above, and all of those columns will need to be listed/ordered by logDateTime.

group_concat sqlite and order by


Newline in output from Unix not appearing in Notepad

Question: Ok, Im new to SAS and have been working on a fixed formatted output .txt file. Each Variable needs to be starting at a particular column and be a fixed length and format. I have been using a PUT statement to accomplish this. So far so good.
Where I run into an issue is when I open the output.txt in notepad, the first line follows the rules defined in the put statement until it is time to move down to the next line. data continues to write on the first record opposed to creating a new record at the end of the put statement.
This only occurs when I open the file in a windows environment (notepad). When I view it in UNIX editor everything is the way I need it.
    data _null_;
    set work.get_driver_data;
    file ".......................dw2092340/driverdata.txt" LRECL = 269;
    DV_Term1 = compress(put (DV_Term, mmddyyn8.),'.');

   put @001 SCAC $4.
   @005 DV_REF $10.
   @15 DSP_OFFICE $13.
   @28 UP_RMP $5.
   @33 DV_HIRE mmddyyn8.
   @41 DV_TERM1 $8. @49 FIRSTNAME $20.
   @69 MID $10. @79 LASTNAME $20.
   @99 LICENSE $20.
   @119 LIC_STATE $2.
   @121 LIC_CNTRY $3.
   @124 LIC_EXPIRE mmddyyn8.
   @132 LIC_CDL $1.
   @257 BNSF_PIN $10.;

any help is appreciated
Comment: In addition to RawFocus's answer, this depends on how you transfer the file from Unix to Windows.  If you transfer it via FTP, and do so in Text format, usually the FTP program will convert it for you.  If you're writing to a network drive or similar, then it won't.
Comment: Note: starting May 2018, [Notepad finally will support \n](https://stackoverflow.com/a/50241693/6309)!
Answer: What is your goal?   It sounds to me like you are creating a text file with UNIX style line endings.
If you want this to open in Notepad, you need to give it windows style line endings.  Try this on the end of your file statement:
termstr=crlf

This stands for "Carriage Return Line Feed".  Alternative values include:
LF   (Line Feed) - use TERMSTR=LF to write files suitable for unix systems.
CR   (Carriage Return) - use TERMSTR=CR for mac systems (not a common use case).
If you are only trying to look at your results, perhaps you should consider using a fully featured text editor - there are many free ones available that will open files in all of these formats.  I use Notepad++ but there are many others.
Also, check out the documentation for the filename statement under unix and windows.
Comment: Good answer.  You might want to explain the difference in line terminations in a little more detail, since odds are the user may not be familiar with what this does.
Comment: a good suggestion..  In our (cross platform) systems, we always use unix line endings.  These can be easily read by windows, whereas the other way round (windows format in unix) is not so reliable.


ReactJS - sort by ascending and descending

Question: Im trying to reorder my results (JSON file) based on the title of my contacts.
The initial render is working fine, showing the results of the JSON file in the order they are in the JSON file.
When i change the select dropdown, i expect it to update the .map function (line 143) that is rendering out the results of the JSON.
What is happening is nothing. no change, no errors, just the select dropdown option changed to the selected value.
Not really sure why its not working, spent a few hours trying to debug, bet its something really simple I'm missing.
Any help would be greatly appreciated as I'm lost on what the problem is..

var getContactList = [
    {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "job": "Manager",
      "email": "email@example.com",
      "phone": "1-770-736-8031 x56442",
      "website": "http://www.hildegard.org",
      "company": "Romaguera-Crona"
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "username": "Antonette",
      "job": "CEO",
      "email": "email@example.com",
      "phone": "010-692-6593 x09125",
      "website": "http://www.anastasia.net",
      "company": "Deckow-Crist"
    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "username": "Samantha",
      "job": "Manager",
      "email": "email@example.com",
      "phone": "1-463-123-4447",
      "website": "http://www.ramiro.info",
      "company": "Romaguera-Jacobson"
    },
    {
      "id": 4,
      "name": "Patricia Lebsack",
      "username": "Karianne",
      "job": "Store Clerk",
      "email": "email@example.com",
      "phone": "493-170-9623 x156",
      "website": "http://www.kale.biz",
      "company": "Robel-Corkery"
    },
    {
      "id": 5,
      "name": "Chelsey Dietrich",
      "username": "Kamren",
      "job": "Store Clerk",
      "email": "email@example.com",
      "phone": "(254)954-1289",
      "website": "http://www.demarco.info",
      "company": "Keebler LLC"
    },
    {
      "id": 6,
      "name": "Mrs. Dennis Schulist",
      "username": "Leopoldo_Corkery",
      "job": "Store Clerk",
      "email": "firstname.lastname@example.com",
      "phone": "1-477-935-8478 x6430",
      "website": "http://www.ola.org",
      "company": "Considine-Lockman"
    },
    {
      "id": 7,
      "name": "Kurtis Weissnat",
      "username": "Elwyn.Skiles",
      "job": "Manager",
      "email": "firstname.lastname@example.com",
      "phone": "210.067.6132",
      "website": "http://www.elvis.io",
      "company": "Johns Group"
    },
    {
      "id": 8,
      "name": "Nicholas Runolfsdottir V",
      "username": "Maxime_Nienow",
      "job": "Store Clerk",
      "email": "email@example.com",
      "phone": "586.493.6943 x140",
      "website": "http://www.jacynthe.com",
      "company": "Abernathy Group"
    },
    {
      "id": 9,
      "name": "Glenna Reichert",
      "username": "Delphine",
      "job": "Store Clerk",
      "email": "email@example.com",
      "phone": "(775)976-6794 x41206",
      "website": "http://www.conrad.com",
      "company": "Yost and Sons"
    },
    {
      "id": 10,
      "name": "Clementina DuBuque",
      "username": "Moriah.Stanton",
      "job": "Store Clerk",
      "email": "firstname.lastname@example.com",
      "phone": "024-648-3804",
      "website": "http://www.ambrose.net",
      "company": "Hoeger LLC"
    }
  ];

const App = React.createClass({

  getInitialState: function() {
    return {
      orderSelect: ''
    };
  },
  change: function(e) {
    this.setState({
      orderSelect: e.target.value
    });
  },
  render: function() {
    var contactsData = this.props.items,
      orderSelect = this.state.orderSelect.trim().toLowerCase();

    if (String(orderSelect) == "asc") {
      contactsData.sort(function(a, b) {
        return a.name.toLowerCase() > b.name.toLowerCase();
      })
    } else if (String(orderSelect) == "desc") {
      contactsData.sort(function(a, b) {
        return a.name.toLowerCase() < b.name.toLowerCase();
      })
    } else if (String(orderSelect) == "submitted") {
      contactsData = getContactsList
    }

    return(

      <select onChange={this.change} value={this.state.orderSelect}>
        <option value="" disabled=""> Sort by </option>
        <option value="submitted"> Submitted Date </option>
        <option value="asc"> A - Z </option>
        <option value="desc"> Z - A </option>
      </select>

      {
        contactsData.map(function(l, index) {
          return (

              {l.name}

          )
        })
      }

    );

  }
});

ReactDOM.render(
<App items={getContactList} />,
document.getElementById('app')
);

Comment: What does "its not working" mean? What behavior are you seeing and what behavior are you expecting? Are there any Javascript errors in the console?
Comment: no. that is an array, so you are pointing to the same location in memory. you need to make a copy of your props array.
Comment: [**Heres a working example doing what you want :)**](https://codesandbox.io/s/react-example-tfp2v) Although I would refactor the sorting to be somewhere other than the render. Probably adjust the array as a state property so you can change the order
Comment: Sweet, cheers, I'll have a look over it, I've noticed you have upgraded the react version, so I'll have a run over that and try and take it all in. Thanks for your help, this gives me a great starting place.
Comment: Running that snippet is giving me an error
Comment: First thing I'd recommend is to upgrade your React version / Javascript to a minimum of ES6, so you can write with class syntax rather than `createClass`. Next is you should update the question to be more explicit. What are you trying to do?
Comment: I have updated my original question a little bit @Andy Ray
Comment: probably because you are trying to sort / mutate a `prop`. You should make a copy of the data to render `contactsData = [...this.props.items]`
Comment: John Ruddell, I thought i already had, I already have this ''var contactsData = this.props.items', isn't that the same?'
Answer: Did you get your answer on this? This is my solution, I hope it helps.
getContactList
   .sort(
      ({ job: prevOr }, { job: curOr }) => prevOr - curOr
   )
   .map((slider) => (
      <SliderItem key={slider.order} slider={slider} />
   ))

I would create then a ternary, if the value is A - Z the this one, if is Z - A then this code but with curOr - prevOr.


Google app engine blob store video file storage and retrieval

Question: Is it possible to upload a video file to blob store and then let the clients download the file locally and play form the local copy?
Comment: yes! It's just a file!
Comment: What language are you using?
Answer: Here is the documentation. https://cloud.google.com/appengine/features/#blobstore There are links to python, java, and go.
Since you did not specify a language I will show you the example for webapp2 and python. The example says photos but the same code will work for any blob since it does not explicitly send content type headers.
import webapp2

from google.appengine.api import users
from google.appengine.ext import blobstore
from google.appengine.ext import ndb
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app

# A custom datastore model for associating users with uploaded files.
class UserPhoto(ndb.Model):
  user = ndb.StringProperty()
  # blob_key = blobstore.BlobReferenceProperty()
  blob_key = ndb.BlobKeyProperty()

class PhotoUploadFormHandler(webapp2.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload_photo')
        # The method must be "POST" and enctype must be set to "multipart/form-data".
        self.response.out.write('')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write('''Upload File: <input type="file" name="file">
 <input type="submit"
            name="submit" value="Submit"> </form>''')

class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        try:
            upload = self.get_uploads()[0]
            user_photo = UserPhoto(user=users.get_current_user().user_id(),
                                   blob_key=upload.key())
            user_photo.put()

            self.redirect('/view_photo/%s' % upload.key())

        except:
            self.error(500)

class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, photo_key):
        if not blobstore.get(photo_key):
            self.error(404)
        else:
            self.send_blob(photo_key)

app = webapp2.WSGIApplication([('/', PhotoUploadFormHandler),
                               ('/upload_photo', PhotoUploadHandler),
                               ('/view_photo/([^/]+)?', ViewPhotoHandler),
                              ], debug=True)

Comment: This link doesnt talk about how to "download a blob store file from clients "
Comment: I will update the answer once OP tells us which language he is using.


Imagick Resize, Center, and Sparse Fill problems

Question: My end goal here is to resize the input image to 100px width, 125px height. Some of the input images are a different Aspect Ratio, so I wish for them to be in a 100x125 container with the background sparse filled from their edge color.
Ok, so this works for the basic resize:
<code>$image = new Imagick($imgFile);
$image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
$image->writeImage("$Dir/$game.png");
header("Content-type: ".$image->getImageFormat());
echo $image;
$image->clear();
$image->destroy();
</code>
However I've been searching for hours, and I cannot find a simple "This is how you center an image in a canvas" bit for PHP's Imagick library. Everything is for the actual ImageMagick convert application, which is not really what I'm after. I've tried compositing the resized image into an empty newImage with the set width and height, but it just seems to overwrite the dimensions regardless of the composite type, setting the Gravity to center and then the extent to 100x125 has no effect ( It always sits at 0,0, and trying to set the y offset to ((125-imageheight)/2) resulted in an offset that was way more than it should have been )
Edit:
<code>    $imageOutput = new Imagick();
    $image = new Imagick($imgFile);
    $image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
    $imageOutput->newImage(100, 125, new ImagickPixel('black'));
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((125 - $image->getImageHeight()))/2 );
    $imageOutput->setImageFormat('png');
    $imageOutput->writeImage("$Dir/$game.png");
    header("Content-type: ".$imageOutput->getImageFormat());
    echo $imageOutput;
    $image->clear();
    $image->destroy();
</code>
So I got my centering working, gravity apparently has no effect on actual images.
I have absolutely no idea where I would even begin to try and recreate a command line edge-in sparse fill in PHP with the library.
Comment: Are you trying to take an image, say 500 * 500, and scale it down to fit into a 100 * 125 image? Then, because 500 * 500 doesn't perfectly scale, only make the height 125 and the width scale proportionally then center it vertically inside the box?
Comment: I'm trying to center a square vertically inside of a tall rectangle of the same width
Comment: Y = (rectangleHeight/2) - (squareHeight / 2)
Comment: I was already doing that and it wasn't working, turns out I was an idiot and completely forgot the () on the getImageHeight function, so my offset was half the size of the container instead...

Now I just need to figure out how to sparse fill the background based on the edge color instead of having a solid black background.
Answer: I ended up using a combination of Imagick and shell calls to convert itself, I'll eventually rewrite it to use entirely shell calls. I also changed my dimensions, here's the code:
<code>    $imageOutput = new Imagick(); // This will hold the resized image
    $image = new Imagick($imgFile); // Open image file
    $image->resizeImage(120,0, Imagick::FILTER_LANCZOS, 1, false); // Resize it width-wise
    $imageOutput->newImage(120, 150, "none"); // Make the container with transparency
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((150 - $image->getImageHeight())/2) ); // Center the resized image inside of the container
    $imageOutput->setImageFormat('png'); // Set the format to maintain transparency
    $imageOutput->writeImage("$Dir/$game.temp.png"); // Write it to disk
    $image->clear(); //cleanup -v
    $image->destroy();
    $imageOutput->clear();
    $imageOutput->destroy();
    //Now the real fun
    $edge = shell_exec("convert $Dir/$game.temp.png -channel A -morphology EdgeIn Diamond $Dir/$game.temp.edge.png"); // Get the edges of the box, create an image from just that
    $shepards = shell_exec("convert $Dir/$game.temp.edge.png txt:- | sed '1d; / 0) /d; s/:.* /,/;'"); // get the pixel coordinates
    $final = shell_exec("convert $Dir/$game.temp.edge.png -alpha off -sparse-color shepards '$shepards' png:- | convert png:- $Dir/$game.temp.png -quality 90 -composite $Dir/$game.jpg"); // Sparse fill the entire container using the edge of the other image as shepards , then composite that on top of this new image
    unlink("$Dir/$game.temp.png"); // cleanup temp files
    unlink("$Dir/$game.temp.edge.png");
    set_header_and_serve("$Dir/$game.jpg"); // serve the newly created file
</code>
Comment: Then use just 1 line of shell:
`exec( 'convert -resize ' . escapeshellarg( $w ) . 'x' . escapeshellarg( $h ) . ' -background escapeshellarg( $color ) -gravity center -extent ' . escapeshellarg( $w ) . 'x' . escapeshellarg( $h ) . ' ' . escapeshellarg( $input_png_path ) . ' ' . escapeshellarg( $output_png_path ) );`
Resizes to $w x $h keeping proportions, 'extents' the canvas to the same given $w and $h (if needed), and fills the rest with any background $color ("white"). You get images always the same size with centered and proportional image (not deformed), rest filled with $color.
Comment: Without the escapeshellargs for better readability:
`exec( "convert -resize $wx$h -background $color -gravity center -extent $wx$h $input_path $output_path" );`
Comment: That achieves a different goal than the one I was shooting for
Comment: You're right, I've mistaken "sparse" for "extent", but still you could fix my answer to your needs as it solves the "resize" and "center" part of your question. I didn't play much with sparse, but I'm pretty sure you could achieve what you want with less lines of code. I'll see if I can get an example working on my "sparse" time.
Comment: I do recall gravity not having any effect ( as noted in the initial question ), which was why I ended up doing it the way I did ( split between library and shell ); This project ended up dying though and I've never gone back to fix it up ( and mostly moved to other languages, fell out of love with PHP - That said, a full-shell variant would be accessible to other languages as well. )


Cordova not defined in pushwoosh

Question: I have followed the push notification tutorial with pushwoosh from here.
I have added following js function to my index.js file.
<code> function initPushwoosh()
        {
            var pushNotification = cordova.require("pushwoosh-cordova-plugin.PushNotification");

            //set push notifications handler
            document.addEventListener('push-notification', function(event) {
                var title = event.notification.title;
                var userData = event.notification.userdata;

                if(typeof(userData) != "undefined") {
                    console.warn('user data: ' + JSON.stringify(userData));
                }

                alert(title);
            });

            //initialize Pushwoosh with projectid: "GOOGLE_PROJECT_NUMBER", pw_appid : "PUSHWOOSH_APP_ID". This will trigger all pending push notifications on start.
            pushNotification.onDeviceReady({ projectid: "XXXXXXXXX", pw_appid : "XXXXXXXX" });

            //register for pushes
            pushNotification.registerDevice(
                    function(status) {
                        var pushToken = status;
                        console.warn('push token: ' + pushToken);
                    },
                    function(status) {
                        console.warn(JSON.stringify(['failed to register ', status]));
                    }
            );
        }
</code>
I have successfully added the plugin. But the application is not working on a device and in browser I get the following message:
<code>Uncaught ReferenceError: cordova is not defined
</code>
How to overcome this problem ?
Answer: In PushWoosh's sample app, they require the "com.pushwoosh.plugins.pushwoosh.PushNotification" cordova plugin but in the documentation, they use "pushwoosh-cordova-plugin.PushNotification".
If you use plugin name="pushwoosh-cordova-plugin" in your config file, then use "pushwoosh-cordova-plugin.PushNotification"
If you use plugin name="pushwoosh-pgb-plugin" in your config file, then use "com.pushwoosh.plugins.pushwoosh.PushNotification"

Cordova not defined in pushwoosh


Different ways to distribute

Question: If I have $5$ bananas, $3$ oranges, and $8$ apples, how many ways can I distribute these
to $16$ friends, if each friend gets one fruit?
Would it simply be $5*3*8=120$?
Comment: Does it matter which friend gets which fruit?
Comment: It does not matter
Answer: Hint: There are $\binom{16}{5}$ ways to choose who gets the bananas. For every one of these choices, there are $\dots$.
Comment: Not quite. There are $\binom{16}{5}$ ways to decide who gets the bananas. For each of these ways, there are $\binom{11}{3}$ ways to decide who gets the oranges, and now who gets the apples is determined. So the total is $\binom{16}{5}\binom{11}{3}$. Note that this simplifies in various ways, such as to $\frac{16!}{5!3!8!}$.
Comment: So then there are $\binom{16}{3}$ and $\binom{16}{8}$ ways to choose the other 2 fruits
Answer: As each one gets one fruit, you have to choose who gets the bananas, then you distribute the oranges among those who haven't got a banana, and the others get the apples. This gives:
$$
\binom{16}{8} \cdot \binom{8}{3}
  = \binom{16}{8, 3, 5}
$$
The last is a multinomial coefficient:
$$
\binom{n}{k_1, k_2, \ldots, k_r}
  = \frac{n!}{k_1! \, k_2! \, \ldots \, k_r!}
$$
where $k_1 + k_2 + \ldots + k_r = n$, the coefficient of $x_1^{k_1} \ldots x_r^{k_r}$ in $(x_1 + x_2 + \ldots + x_r)^n$.

Different ways to distribute


undefined reference to espeak function

Question: after typing make to compile a project that is depends on espeak
i got the following error at linking stage
     `EspeakTTSWorker.cpp:(.text+0x118): undefined reference to `espeak_Initialize'
CMakeFiles/TextReading.dir/EspeakBridge.cpp.o: In function `EspeakBridge::init()':
EspeakBridge.cpp:(.text+0x93): undefined reference to `espeak_Initialize'
EspeakBridge.cpp:(.text+0x9d): undefined reference to `espeak_SetVoiceByName'
EspeakBridge.cpp:(.text+0xa7): undefined reference to `espeak_SetSynthCallback'
CMakeFiles/TextReading.dir/EspeakBridge.cpp.o: In function `EspeakBridge::close()':
EspeakBridge.cpp:(.text+0x173): undefined reference to `espeak_Terminate'
CMakeFiles/TextReading.dir/EspeakBridge.cpp.o: In function `EspeakTTSWorker::setText(std::string const&)':
EspeakBridge.cpp:(.text._ZN15EspeakTTSWorker7setTextERKSs[_ZN15EspeakTTSWorker7setTextERKSs]+0x121): undefined reference to `espeak_Synth'
EspeakBridge.cpp:(.text._ZN15EspeakTTSWorker7setTextERKSs[_ZN15EspeakTTSWorker7setTextERKSs]+0x126): undefined reference to `espeak_Synchronize'
collect2: error: ld returned 1 exit status
make[2]: *** [TextReading] Error 1
make[1]: *** [CMakeFiles/TextReading.dir/all] Error 2
make: *** [all] Error 2`

and here is cmakelisits
    find_package (Espeak)
if (Espeak_FOUND)
include_directories(${Espeak_INCLUDE_DIRS})  #/usr/local/include/espeak
endif(Espeak_FOUND)
if (NOT Espeak_Found)
message(FATAL_ERROR "Package Espeak required, but not found!")
endif(NOT Espeak_Found)
add_executable(TextReading
        ${DAD_SOURCES}
        ${DAD_HEADERS}
        ${MY_UI_HDRS}
        ${MY_MOC_SRCS}
    ${MY_CUDA_COMPILED_FILES}
    ${QEXTSERIALPORT_SOURCES} ${QEXTSERIALPORT_HEADERS}
    )

target_link_libraries(TextReading
        ${OpenGL_LIBS}
        ${QT_LIBRARIES}
        ${QGLVIEWER}
    ${Boost}
    ${OpenCV_LIBS}
        ${TESSERACT_LIB}
    ${FFMPEG_LIBRARIES}
    ${MathGL_LIB}
   # ${Flite_LIBS}
   ${Espeak_LIBRARIES}
#/usr/lib/x86_64-linux-gnu/libespeak.so.1
#/usr/lib/x86_64-linux-gnu/libespeak.so.1.1.47
    ${QEXTSERIALPORT_LIBS}
    ${QTMOBILITY_LIBRARIES}
    udev

)

hint:i put FindEspeak.cmake file in the Module path of cmake
Comment: No espeak development files ? ... `sudo apt-get install libespeak-dev`
Comment: i have installed `libespeak-dev`  but still the previous error
Comment: Run it like that to see the actual linker command: `make VERBOSE=1`. Then take that linker command and execute it separately and try to change it to make it work. That will give a clue about what to change in the `CMakeLists.txt`. To check that the symbols are actually present in the libespeak, use `objdump -tT /usr/lib/x86_64-linux-gnu/libespeak.so.1.1.47` (read about the "-t" option in the `man objdump` to understand what the output means).
Comment: thanks a lot i have tried the following answer and it works
Answer: I just edited this part
############ Find ESPEAK TTS ############

find_path(LIBESPEAK_INCLUDE_DIRS
          NAMES speak_lib.h
          HINTS /usr/include/espeak)
find_library(LIBESPEAK_LIBRARIES
             NAMES espeak
             HINTS /usr/lib/ /usr/x86_64-linux-gnu/
             PATH_SUFFIXES lib)

########################################

add_executable(TextReading
        ${DAD_SOURCES}
        ${DAD_HEADERS}
        ${MY_UI_HDRS}
        ${MY_MOC_SRCS}
    ${MY_CUDA_COMPILED_FILES}
    ${QEXTSERIALPORT_SOURCES} ${QEXTSERIALPORT_HEADERS}
    )

target_link_libraries(TextReading
        ${OpenGL_LIBS}
        ${QT_LIBRARIES}
        ${QGLVIEWER}
    ${Boost}
    ${OpenCV_LIBS}
        ${TESSERACT_LIB}
    ${FFMPEG_LIBRARIES}
    ${MathGL_LIB}
    #${ESPEAK_LIBRARIES}
    ${LIBESPEAK_LIBRARIES}
    ${QEXTSERIALPORT_LIBS}
    ${QTMOBILITY_LIBRARIES}
    udev

)

undefined reference to espeak function


how to set hex colour as the background for my window in tkinter python

Question: I have been trying to figure out why this has been happening when I try to access my hex colour as the background color in window, searched for the solution everywhere but didn't got the exact one.
It is throwing -> tkinter.TclError: unknown color name 'f7f5dd'.
Please guide me the way :
    from tkinter import *
    YELLOW = "f7f5dd"
    window = Tk()
    window.minsize(width=400, height=300)
    window.title("Pomodoro App")
    window.config(padx=100, pady=50,bg=YELLOW)
    window.mainloop()

Answer: Just add the hash symbol/number-sign to the front of the color string.
from tkinter import *
YELLOW = "#f7f5dd"
window = Tk()
window.minsize(width=400, height=300)
window.title("Pomodoro App")
window.config(padx=100, pady=50,bg=YELLOW)
window.mainloop()

Answer: Instead of window.config. You can use this. Add symbol # in front of color string.
from tkinter import *
YELLOW = "#f7f5dd"
window = Tk()
window.minsize(width=400, height=300)
window.title("Pomodoro App")
window['background']=YELLOW
window.mainloop()


Existence of step from N to P position in compound game using Sprague-Grundy function

Question: Given $3$ piles containing $\{27, 24, 36\}$ pebbles in each. Players can take
$\{1,4,5\} , \{2,3,7\}, \{3,4,6\}$ from first, second and third piles respectively.
I need to show that Sprague-Grundy function gives me the winning and loosing position of the compound game.
I started by drawing each sequence separately and observing the pattern. I found this repetitive Sprague-Grundy values from $0$ to $m,n,k$ as follows:
$\text{pile #1} \{0,1,0,1,4,5,4,5\}$, $\text{pile #2}\{0,0,2,2,4\}$, and  $\text{pile #3}\{0,0,0,3,3,3,6,6,6\}$.
So the initial Sprague-Grundy is $g(27,24,36) =$ g1(27)^g2(24)^g_3(36) = 1^3^0 = 6, which is a losing position. From this state $(27,24,36)$ I can move to the winning position $(27,22,36)$ because it is a movable step and its Sprague-Grundy value is 1^1^0 = 0; At this point I know why result $0$ of xor gives winning position in nim game, there is no restriction to number of pebbles to remove, but in take away game there is restriction. Why even with this restriction there exists a move from loosing position(N) to winning position(P) in compound subtraction game?
Comment: I haven't been introduced to "Sprague-Grandie". Could you at least give a reference (I would give you a reference if had to make development about the not so well known von Hindenburg - Nekrasov - Yamamoto formula)
Comment: Sure [here](https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem)
Comment: It is the Sprague-Grundy theorem, as in the Wikipedia page you cite.
Answer: The point of the Sprague-Grundy theorem is to calculate the nimber, the number of stones in a pile of unrestricted nim, that corresponds to a pile of stones in your game.  The nimber of a position is the minimum nimber that you cannot move to from that position.  In regular nim, a pile of six stones can move to $0,1,2,3,4,5$, so the nimber is $*6$.  Taking your second game, a pile of $0$ or $1$ stones is $0$ because you can't move at all.  A pile of $2$ stones is $*1$ because you can move to $0$ but not to $*1$.  A pile of $3$ stones is $*1$ as well because both moves are to $0$.  A pile of $4$ stones is $*2$ because you can move to $0$ by taking $3$ or to $*1$ by taking $2$.  You need to recalculate all of your nimber values.
Assuming the values of the three piles were $*1,*3,0$, the value of the group of three piles would be $XOR(*1,*3,0)=*2,$ not $*6$.  You could reach a winning position by moving from $*3$ to $*1$ because $XOR(*1,*1,0)=0$.  You are guaranteed to be able to do this because $*3$ must be able to move to any of $0,*1,*2$.  Then if your opponent takes one $*1$ to $0$ you take the other.  Otherwise he must take the $0$ to some nimber which you can take back to $0$ or he can take one of the $*1$s to a higher nimber and you can take it back.


Determine the value of r where the series converges

Question: show that $$ \big(r\big)^{ln(n)} =  \big(n\big)^{ln(r)} $$ Then determine the values of r (with r>0) for which the series
$$ \sum_1^\infty (\big(r\big)^{ln(n)})$$ converges.
r must be in what interval?
Answer: Hint: To show the first thing you are asked to do, find the natural logarithm  of each of the given expressions.
For the second problem, find equivalently the $r$ for which
$$\sum_1^\infty \frac{1}{n^{-\ln r}}$$
converges. Put in this way, the problem  should feel familiar.
Comment: I get the interval (0,1) but that's not the answer.
Comment: We get convergence if $\ln r\lt -1$, that is, if $0\lt r\lt e^{-1}$.


Why is this a fake proof? Cauchy's Mean Value Theorem

Question: We are assuming that g and f satisfy the mean value theorem and apply it to each, then divide f'(z) / g'(z), Why is this a fake proof?
As f and g satisfy the hypotheses of the mean value theorem we apply it and we have that there exists z that belongs to the interval (a, b)
such that $f '(z) = \frac{f (b) -f (a)}{ b- a}$ and
$g '(z) = \frac{g (b) -g (a)}{ b- a}$ then we divide $\frac{f '(z )} { g '(z)}$ and we have the proof of Cauchy's mean value cause this is equal to
$\frac{f '(z )} { g '(z)} = \frac{f (b) -f (a)}{ b- a} / \frac{f (b) -f (a)}{ (b- a)} = \frac{f(b)-f(a)}{g(b)-g(a)}$
Comment: Please use MathJax to format mathematics. See https://math.stackexchange.com/help/notation The problem is that $z$ may be different for $f$ and $g$, i.e., you have a $z_f$ for $f$ and a $z_g$ for $g$, and $z_f \neq z_g$ in general.
Comment: This argument doesn't work if $g(b)-g(a)=0$, since then you'll be dividing by zero. Moreover, the numbers appearing in the argument of $f'$ and $g'$ need not be equal; the $z$ appearing for $f'$ is not necessarily the same $z$ appearing for $g'$.
Answer: It's a fake proof because the $z_1$ such that $f'(z_1) = \frac{f(a) - f(b)}{a - b}$ and the $z_2$ such that $g'(z_2) = \frac{g(a) - g(b)}{a - b}$ are not necessarily the same $z$.


Java Transformer Empty Element

Question: I wrote a program (I'm using JDK 11) to format an XML string; however, I want my program to contract empty elements. For example: <element></element> should become <element/>. I have written the below code which does not work:
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
        transformer.setOutputProperty(OutputKeys.INDENT,"yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
        transformer.setOutputProperty(OutputKeys.METHOD,"xml");
        transformer.transform(new DOMSource(unformattedXml),new StreamResult(stringWriter));
        return stringWriter.toString();

How can I contract the empty elements?
Comment: I have ched this with jdk 11 and it is not reproduceable
Comment: What input string did you use?
Comment: `Document document = db.parse(new ByteArrayInputStream("".getBytes("UTF-8")));` outout: `

`
Comment: Your input works fine using my code. Can you try `"\n"` as input?
Comment: `\n` is a valid charcter, so it is not an empty element!
Comment: I am well aware that \n is a character. My code was working fine and performing the contraction as expected when I used it on JDK 8. The problem appeared when I used JDK 11.
Comment: I get same result in java8 and java11 `

`
Comment: What is the actual Java class of the returned `Transformer`? I'm puzzled by the serialization property `http://www.oracle.com/xml/is-standalone` which is very non-standard: where is this documented?
Comment: @MichaelKay I tried the code with and without the serialization property. Same result. I have used it due to this: https://stackoverflow.com/a/38773720/10270181 This is the class of the Transformer that gets loaded: com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
Answer: I don't know which XML libraries you are using. I just tried with raw installation and works fine for me.
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
//from w  w  w.  ja  va2 s.c om
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Transform {

    public static void main(String[] args) throws Exception {
        String unformattedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<note>\n"
                + "  <to>example</to>\n"
                + "  <from>Server</from>\n"
                + "  <heading>Reminder</heading>\n"
                + "  \n"
                + "</note>";
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(convertStringToDocument(unformattedXml).getDocumentElement()), new StreamResult(stringWriter));
        String s = stringWriter.toString();
        System.out.println(s);
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Output:
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>example</to>
  <from>Server</from>
  <heading>Reminder</heading>

</note>

Comment: If it is not reproduceable, the question should closed
Comment: These are my imports : import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
Maybe it is related to jdk 11?
Comment: @RobotWizard Try to debug, which DocumentBuilder gets loaded. It will be loaded by DocumentBuilderFactory and what is the actual implementation of Transformer class you get. In debug you can see that, and then it will be easier to recommend.
Comment: @Optional this is the DocumentBuilder that gets loaded com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl  and this is the the Transformer that gets loaded com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
Comment: I have same transformer and DocumentBuilder.
Comment: @Optional I ran your code on my input, it didn't work. The input I am using is `"\n"`
Comment: @Jens, no if it's not reproducible then we need to dig more deeply to find out why it works for us and not for the OP.
Comment: @MichaelKay ok. But not answer as "I can not reproduce it"
Comment: In theory this isn't an answer according to SO rules, but it's a helpful response and too complex to go in a comment, so my inclination is to ignore the rules.

Java Transformer Empty Element


Ember.Select selected value not binding to object

Question: Ok folks, this is really starting to wind me up.  I'm assuming I'm doing something dumb or missing something but I cannot seem to get a select list to bind the selected value to the object.  All I'm trying to do is create some cascading drop down lists, like you see in sites like auto trader.
App.CarController = Ember.ObjectController.extend({
    selectedCarMake: null,

    availableCarMakes: Em.computed(function () {
        return this.store.find("carMake"); // => GET /carMake
    }).cacheable(),

    availableCarModels: Em.computed(function () {
        var make = this.get('selectedCarMake');
        // the line below returns the id and not an object
        console.log(make);
        if (make === undefined || make === null)
            return [];
        return make.get('carModels');
    }).property('selectedCarMake'),
});

these are my models
App.CarMake= DS.Model.extend({
    name: DS.attr('string'),
    carModels: DS.hasMany('carModel', { async: true })
});

App.CarModel= DS.Model.extend({
    name: DS.attr('string')
});

and this is my html markup

                {{view Ember.Select
                            contentBinding="availableCarMakes"
                            optionLabelPath="content.name"
                            optionValuePath="content.id"
                            valueBinding="selectedCarMake"
                            prompt="Please Select..."
                }}

So the first drop down list (shown above) does populate but when you select a value and it calls availableModels to bind the second drop down list, it bombs because selectedCarMake is an id and not an object.  Any pointers would be much appreciated!
Answer: If, as you said, you're binding the user's selection to an object, use selection=selectedCarMake instead of valueBinding='selectedCarMake'. Value just binds the value of each <option> (not the entire object bound to the Ember option) to whatever property your specify. See the Em.Select docs for more info.


Create, name, and populate new workbook with data

Question: I have an Excel sheet with two columns of data. Column A has the desired new workbook names and Column B's adjacent cell has the data I want in the new work book.
So if 032411 is in column A and 50 is in column B then the macro would create a new workbook named 032411 and 50 would be in cell A1 of that workbook.
Answer: You can use this:
Sub CreateBooks()

    Dim oCell As Excel.Range
    Dim oWorkbook As Excel.Workbook

    'Added to avoid messages asking to confirm overwriting
    '   previous existent files with same name

    Application.DisplayAlerts = False

    For Each oCell In Range("A:A")

        If oCell.Value = "" Then Exit For

        Set oWorkbook = Workbooks.Add

        oWorkbook.Sheets(1).Cells(1, 1).Value = oCell.Offset(0, 1).Value

        'If the cell value contains only the file name (instead of the whole path
        '   the file needs to be saved) it will save into MyDocuments folder
        oWorkbook.Close True, oCell.Value

    Next oCell

    Application.DisplayAlerts = True

End Sub

In case you have several files to generate, you can alternatively use the application.ScreenUpdating = False.
Comment: Thanks Tiago.  That was a huge leap forward.  It just needs tweaked now.  The macro generated all new workbooks but did not rename them with the value from cell A1 and save it as such.  I tried to update it as suggested but can't seam to get it right.
Comment: Also worth noting is the file name MMDDYY includes a zero at the beginning in many cases and uses the custom cell format.  When the cell is clicked on the formula bar shows the date as M/DD/YYYY.
Comment: Following your example, we need to save a file named as 032411.xls, right? I believe it's already happening, I'd need a clarification about what you need / what we have now and the diff between what you need / what we have.
Comment: When I copy/paste the macro I get runtime error 1004: cannot access the file 'C:\....My Documents\3\26\74C4B900.  The 3\26\ after my documents is why I think it is having a problem with the number format.  When I hit debug it highlights oWorkbook.Close True, oCell.Value.  When I delete that, it will generate new workbooks with the data from column B but does not save them with the value of column A.  Each workbook is named generically by excel as book2, book3, etc.
Comment: Yes, probably. You cannot have a slash within a file name. From where this \3\26 is coming from?


MS Word alternative for Ubuntu to work with templates having mergefields and if conditions

Question: I have been using LibreOffice on my Ubuntu laptop for quite sometime now and everything was fine up until I had to work with word templates with a lot of merge fields and if conditions.
Whenever I open sample templates on Libreoffice writer, it gets all wonky and doesn't even display the merge fields and if conditions already there in the opened word template.
Said templates open without any issue in MS Word on a windows machine.
Is there any alternative for MS Word that I can use to create and edit such templates on my Ubuntu machine?
Comment: Does this answer your question? [Is there any way to use microsoft office in ubuntu without using wine? or any other alternative similar to microsoft office which uses the same format](https://askubuntu.com/questions/1332473/is-there-any-way-to-use-microsoft-office-in-ubuntu-without-using-wine-or-any-ot)
Comment: @mikewhatever It doesn't actually. I already use LibreOffice and I don't think I'll be able to run a VM given the resources I have on my system.
Comment: I need something for creating and updating word templates that use merge fields and if conditions...
Comment: I'm not sure it fits the bill but you may want to try WPS Office.
Comment: @ChanganAuto Downloading and trying it
Comment: @ChanganAuto pretty much the same as LibreOffice
Comment: @BileshGanguly The answers provide a few alternatives, but most importantly, should lead you to a logical conclusion. Obviously, that last one has not happened yet.
Comment: @mikewhatever Yeah... looks like a futile effort...
Answer: Due to how proprietary and complicated Microsoft Word is, I'm afraid there isn't a solution to this that doesn't involve running actual desktop Word. Even Microsoft, who has access to the source code of Word, can't make features like this work in their web version of Word.
Comment: Yeah... Seems like a futile effort...
Comment: I've run a Windows VM on Ubuntu on some pretty old/cheap hardware. It's not going to be fast but would probably work if you really need it. Or if you have fast enough internet and are willing to pay $5/mo you could get a Windows VPS and remote into it.


Why can't I absorb a dragon soul?

Question: I recently started a new game, including all official DLC, the unofficial skyrim patch, deadly dragons and a couple more mods.
Everything went well until I beat Mirmulnir, I didn't get to absorb his soul, he just lies there, busy being dead. All the guards around were hiding/crouching as if I was absorbing the soul, but nothing happened. A reload from an earlier save didn't help. This resulted in the mainquest being effectively stuck.
If I play in another game and kill a dragon there, I still can't absorb his soul.
Comment: If anyone is playing the Legendary edition, for some stupid reason, the DLC load orders can be wrong and can cause this problem out of the box.
Comment: @Nelson, that's ridiculous. But in that case changing load order should fix it. However stupid that it is required.
Comment: Wouldn't say it if it didn't happen.  Wasted 3 hours to fix a fresh install.
Answer: Do you also have the Unofficial Dragonborn Patch installed (separate from the Unofficial Skyrim Patch)?
If not, install it. One of its fixes is:

Dragonborn's changes to DragonActorScript.psc have now been properly
merged with the fixes done in the USKP. Dragon soul absorbtion is now
working 100% correctly.

According to the Unofficial Dragonborn Patch's mod description, the load order should be like this:

Skyrim.esm
Update.esm
Unofficial Skyrim Patch.esp
Dawnguard.esm
Unofficial Dawnguard Patch.esp
Hearthfires.esm
Unofficial Hearthfire Patch.esp
Dragonborn.esm
Unofficial Dragonborn Patch.esp
HighResTexturePack01.esp
HighResTexturePack02.esp
HighResTexturePack03.esp
Unofficial High Resolution Patch.esp

Also as a reply to this answer, you shouldn't load Dragonborn after USKP, as it could undo the fixes of USKP. If unsure, just let LOOT take care of the load order.
Install the other Unofficial Patches if you have their DLCs too: Dawnguard, Hearthfire, High Resolution DLC.
Also, see the troubleshooting steps for the 'cannot absorb dragon souls' issue listed at the Unofficial Dragonborn Patch Nexus forums sticky post by Arthmoor, one of the UDGP developers:

Check for: dragonactorscript.pex and/or mqkilldragonscript.pex. Remove them if present. They are from dragon mods that came as loose files.
DSAMG - Dragon Soul Absorb More Glorious, and Diversified Dragons are known to cause this. Those mods need to be updated with a Dragonborn patch that incorporates the fixes from the UDBP.
Skyrim Unbound will cause this as well due to the script being unaware of the changes for Dragonborn.
Others may be a factor as well.
Note too that the offending mod may have the script packaged inside a BSA. That will need to be handled by that mod's author.
If you are using Mod Organizer and are here to report issues with dragon souls, sorry, but you're on your own as we do not support issues caused by incorrectly letting that program modify the BSA load order system the game has. Your post is likely to just be ignored. We don't have time to keep fending off false bug reports caused by people who insist on unpacking their BSA files using the program and thus subverting the entire system the game relies on for proper behavior.
Comment: I will install all Unofficial patches later this evening(at work now), I'm pretty certain I only have the USKP and not the other patches for the DLC's.
Comment: Putting these in order worked for me. I had a quick save right before I killed a dragon; no soul absorption. Adjusted the order to match above, loaded the quick save and soul was absorbed. Thanks!
Answer: It seems that there is a conflict between the unofficial skyrim patch and the dragonborn expansion.
After I placed dragonborn after the USKP in the load order I could absorb dragon souls again.
Comment: Hi Arperum - even though you are answering your own question, please mark the answer as accepted so people can know at a glance that this is a working solution. Thanks!
Comment: @Alex The solution posted by galacticninja is the better option, so I accepted that one instead.
Comment: Ah ok, missed that somehow! Sorry :)
Answer: try this fix http://skyrim.nexusmods.com/mods/31685/?tab=4&navtag=%2Fajax%2Fcomments%2F%3Fmod_id%3D31685%26page%3D1%26sort%3DDESC%26pid%3D0%26thread_id%3D915803&pUp=1
"Dragon Soul Absorb Fix". ALSO DELETE MQKillDragonScript.pex
I also have looked for a fix everywhere. I have all the unofficial patches, also all the dlc's. After I installed this mod DSAMG : http://skyrim.nexusmods.com/mods/13850//? the soul absorbtion did not work anymore, now after installing this fix, it works again. I'm at the first dragon at Western Watchtower, the dragon's name is Mirmulnir.
Comment: Are you sure your load order is right? It has to be the order as shown in @galactivninja's answer. otherwise it won't work.
Answer: before i start, i need to say that this program is in beta. "experimental" even. i personally have never had a problem with it, but that is not to say it could not happen. using this program, i have been able to play past many bugs which previously haunted me, and allowed me to complete missions i could not previously complete.
also, you might want to have a look at this TESV Edit video.

 It is way too long and drawn out. To simplify,
1) Download TESV Edit. http://skyrim.nexusmods.com/mods/25859/?
2) Unzip the file anywhere, open the folder, then open TESV Edit.
3) Right click and choose "Select None" at the list which pops up, then check the mod, or master file that needs cleaning. (Dragonborn.esm, Dawnguard.esm, Hearthfires.esm, and Update.esm all need to be cleaned. Skyrim.esm DOES NOT NEED CLEANING, DON'T DO IT.) To simplify this, only do one mod or master file at one time.
4) Wait for the mod or master file to finish loading, then right click that file, and select "Apply filter for cleaning." (At the top of the program, it says "yes, this takes a while, just wait!) so wait. lol
5) after the filter has been applied for cleaning, right click the file again, then select "remove identical to master records." This will probably go very quickly.
6) right click the file yet again, but this time select "undelete and disable references.
7) close TESV edit. if everything went right, you will see one of two things. First, you might see the selection window load up again with only your file checked. this means you successfully cleaned a dirty file. Second, TESV edit might just close. This means your file did not nead cleaning.
8) in closing, the author of the video does not recommend blanket cleaning all your mods. i have a different attitude. if a mod shows up dirty, i clean it. if that means the mod doesn't work anymore (that hasn't happened yet, but i have seen at least one mod which specified it could not be cleaned in TESV edit.) then i ditch that mod. be really careful about which mods you install. for instance, the latest CBBE version already has remodeled female feet, and does not need a mod called "femfeet." Using these two mods together results in broken texture seams at the hips, and or feet. Another mod "NPC Hair Overhaul" is known to create the grey face bug, yet it still exists in its unfinished/unfixed form at Skyrim Nexus. don't try to make known troublemaker mods work for you.
Also, the previous question mentioned BOSS. BOSS automatically sorts your files, and gives a report, which includes some of the files need cleaning in TESV edit. If the mod is in the unrecognized area, it may still need cleaning, even though BOSS did not report it.
Comment: Cleaning the ESMs will not help this problem. It's cause by incompatibility between the USKP and Dragonborn DLC's changes to dragons, and is fixed by installing the Dragonborn unofficial patch too. Cleaning helps with lots of bugs caused by mod conflicts and should be part of every player's toolbox once they get into mods, but this is not one cleaning can help with.

Why can't I absorb a dragon soul?


Dryer wiring is messed up i think

Question: I'm having issues with dryer I took apart the outlet it's only three prong when I take my multimeter and touch the neutral to the negative I get no power I touch the neutral to the positive I get no power I touched the hot and the negative I get my 240 is that okay or is there something wrong in my wiring
Comment: Please upload a picture. There is no positive or negative with AC. You *should* have 4 wires - bare or green ground, white neutral, black and red (usually, colors can vary) hot. The hots should be 240V to each other, 120V to ground or neutral. The ground and neutral should be 0V to each other. A 3-prong receptacle should have hots and neutral but no ground.
Comment: You using Negative and positive is scary. Hope you survive long enough to continue this discussion.
Comment: It sounds like your neutral is not connected anymore.  This also means there is no ground path to save you from electric shock.  Turn off the breaker for the dryer now.  Do not use.  Google nema type 10 circuits to see why they were banned.  You can repair that circuit, but it is highly recommended to upgrade to nema 14(hot, hot, neutral and ground).
Comment: Reading again, it sounds like your problem is a bad/broken neutral. Depending on configuration, that could be at the receptacle, at the panel or at some junction (wire nut or other splice) in between.
Comment: I don't know too much on electricity just a little what do I have to do to fix that issue if that's what it is and thank you
Comment: How do I upload a picture to this page
Comment: I would suggest asking an electrician to do the work for your safety.  If you do want to fix it yourself, turn off the breaker for the dryer and/or the main breaker.  Check the outlet for loose connections(a wire loose).  If not there it might be in the panel, main breaker off for this part.
Comment: Is my bare wire and my white wire supposed to be connected to the same thing in my outlet
Comment: Please [edit] your question, then click the "sun & mountain" icon to upload a picture. Or, just drag the picture into the text edit box. Either way, the site will upload the image and host it for you. If you do have 4 wires - bare, white, red, black - then you're ideally suited for safety and modern code compliance. Before you do anything else, though, make sure the breaker is OFF and get the pic uploaded. That will help us help you.
Comment: The white wire is being used as the second hot(should have a black mark on it).  The bare is your neutral, it goes to the middle bottom/top slot.  the white to one side and the black to the other side.
Comment: So if I'm reading the comment right the red and black wire are my hots and then my white wire and my bare wire or my neutrals with the way this is set up is the red and black on my heart and then the white wire and bare wire are connected together as a neutral so when I put my multitester on my neutral and then on either one of the hots it shows no voltage or if I touch both of my hot I got 240 is that ok
Comment: It won't load up the picture
Comment: Most likely problem with the picture is that is larger than the truly arbitrary 2 Meg. limit. Which StackExchange should have fixed years ago by allowing a much larger size and automatically shrinking. But I digress.
Answer: There is some good news here. Based on the comments, OP has black, red, white and bare. Which means this is a NEMA 10 that can be replaced with a NEMA 14, provided the wires are all functioning properly.
There are two likely possibilities here:

Receptacle gone bad. That happens. Which is OK because we want you to replace it anyway.
Neutral wire someplace else gone bad. That could be at a junction box in between the receptacle and the breaker panel or actually in the breaker panel. Or (small but non-zero possibility) rat chewed through wires somewhere.

So which is it? And what to do next?

Turn off the breaker
Disconnect all 4 wires from the receptacle and toss the receptacle. Yes, toss it. You don't want anyone else taking it and using it, plus even brand new and 100% working it is only worth $10 retail.
Spread the 4 wires apart from each other and from the box (especially if the box is metal.
Turn on the breaker.
Carefully test the voltage between every pair of wires. Write the information down.
Turn off the breaker.

If you get:

Black - Red = 240V
Black - White = 120V
Red - White = 120V
Black - bare = 120V
Red - bare = 120V
White - bare = 0V

then you are ready for step 2. If any reading is different from the above by more than a few volts, STOP and ask for more help.
The next step is to get a UL/ETL listed NEMA 14-30 receptacle, such as this Leviton one from Amazon:

Picture is from Amazon. Be extremely careful buying anything electrical from Amazon. Leviton is a good brand and Amazon makes it easy to import pictures to this site. But Amazon also sells a lot of not-UL-listed junk. For anything electrical, if it says "Shipped by Amazon" but "Sold by someone else" don't get it. The safest thing is to go to your local hardware store or Home Depot or Lowes or similar because they don't (or rarely, hopefully) sell unlisted stuff because the rules are a little different for bricks 'n mortar stores.
Connect it according to the instructions and then turn on the breaker and verify voltages in the receptacle.
The last step is to replace the dryer cord with something like this Whirlpool cord from Amazon:

Note that brand does not matter - i.e., you can use a Whirlpool cord with a GE dryer or vice versa. But as with the receptacle, make sure it is UL or ETL listed and bricks 'n mortar may be a better bet than Amazon unless you watch carefully (when you order and when you receive the order!) to make sure you get the real deal.
The final step is to install the cord on your dryer. The process varies by model. But basically involves removing some part of the back of the dryer, then removing the old cord and attaching the new one, and then remove the neutral-ground bond from the dryer. That last step is critical to making the 4-wire cord/receptacle safer than the 3-wire cord/receptacle. The exact process for doing that varies by model/manufacturer. If you are not sure, find the model # and ask a question here.
Finally, I prefer to verify that the neutral/ground bond is disconnected. To do this, set your multimeter on resistance. You should get close to 0 Ohms (and a beep if your meter beeps on continuity) between the ground pin of the cord and the metal case of the dryer but infinite Ohms/no continuity between the neutral pin of the cord and the metal case.
Comment: @KMJ And how often have I started a long answer and then Harper shows up with a HUGE answer :-)
Comment: I find it amusing how many times I'm writing a short answer when you're putting together a long one. Take my upvote.
Comment: Right? Yours doesn't even have a link to a Technology Connections video in it. Clearly slacking.
Answer: Please note: the instructions below might result in needing to go behind the cover / dead front on an electrical panel. Electrical work can be dangerous. If you are not confident of how to do it safely, please hire it out or at least do more reading in a DIY book. Full education on how to safely work with 240V is out of the scope of this answer.
Since you said in the comments that you have red, black, white, and bare wires, this means you have a four wire circuit. Here's the correct wiring at the receptacle end:

If you have four wires but a three prong receptacle, it's wrong. To fix it you will need to replace the receptacle and the dryer cord. See your dryer installation manual for correct wiring instructions.
At the breaker panel end, the red and black wires are connected to the circuit breaker. The white wire will be under a screw at the neutral bus. The bare wire will be under a screw at the ground bus. If it's a subpanel, those will always be separate. In a main panel, they may be the same bus.
If you can't get 120v to either hot leg from ground or neutral, then your ground or neutral is open. This either means it's not properly connected at the panel end, or there is a break in the wire.
Comment: I've seen more than a couple professionally installed and signed off main panels where grounds and neutrals are freely mixed across the bars, so this may be more of a 'code vs practice' thing. The important part I was trying to get the Asker to notice was that if you mix them in a subpanel, Bad Things can happen. Mixing them in a main panel is not the end of the world.
Comment: *The bare wire will be under a screw at the ground bus. If it's a subpanel, those will always be separate. In a main panel, they may be the same bus.* Mostly correct. But actually in a main panel it is 100% legitimate to have separate (but bonded) neutral and ground buses, and in that case grounds can go on the neutral bus but neutrals can't go on the ground bus. Better to keep separate (except for the bond) but not strictly necessary. When my electrician was doing my heavy-up, he put a few (but just a few) grounds on the neutral bar due to the layout of the panel and the short old wires.
Comment: Agreed. Code says: Neutral on neutral, ground on neutral or ground. Best practices says neutral on neutral and ground on ground so that if you ever turn this main panel into a subpanel you don't have to move any ground wires. Wrong but not fatal says neutral, ground - they're bonded anyway in this box so "whatever". Wrong *and* fatal says: They're bonded in the main panel so I can mix them up elsewhere...

Dryer wiring is messed up i think


How big do squares need to be to fit a box, tesselating, with minimal remainder?

Question: A geometry question that I feel utterly defeated by. I'm trying to design a responsive user interface that efficiently fits a variable number of square elements on a screen, by adjusting the size of the squares. With a known square size, the number of squares along and up will be implicit. I'm also very interested to know the answer.
I describe the problem as thus:
A known number of squares, n, must be fit as efficiently as possible (least remaining area) into a rectangle of known dimensions x & y. The dimension (equal width and height) of the squares, s, must be adjusted to achieve this. The squares must be axis-aligned. Find s.
All I've been able to establish is that where n/(w/h) is an integer, n + 1 is a worst case scenario of remainder. I can't seem to get any more facts to come out in the wash, but am interested in the working of the answer.
Update:
I've worked out (I hope), the maximum number of squares that may be fit, as follows:
<code>max squares =
( floor( longest side / shortest side ) * divisor^2 ) +
( floor( r / ( shortest side / divisor ) ) * divisor )
</code>
Based on fitting squares with a size of the shortest side of the rectangle, dividing them down by the divisor (iteratively until enough squares are achieved), each time seeing how much of the remainder can be occupied by the divided down dimension.
Now I just need to turn this into a single formula so it doesn't have to be computed iteratively, if possible.
Comment: If I follow it right, $s=1$ will have no remaining area, but is there a balance between square size and remaining area?
Comment: All squares must be the same size. The problem is to find a size where all squares fit the rectangle, with the least possible remainder of space.

In some cases there might be no remainder at all; e.g. a rectangle of width 4 units and height 2 units, of which 8 squares must be fit, in which case s = 1 unit. If the width were increased to 4.1 units the solution would be the same, but there would now be a remainder of 0.2 units^2.
Answer: I'm decently sure this can be accomplished by simply adding the largest possible square i.e. has the minimum of width or height as side length.  put square on side of rectangle and you end with a rectangle demension $x$ and $y-x$ without loss of generality.  then simply repeat until either there's no remainder or your out of number of squares.
Comment: Sorry, I should have made this clear; all squares must be the same size. The problem is finding that size, where all of them fit the rectangle with the least possible remainder.
Comment: @TobyWilson Ah ok that adds a degree of complexity let me think about that.
Comment: @TobyWilson Are any of the variables known or are "known" values simply constants
Comment: Known values (constants): Width and height of the rectangle, and the number of equal squares that must be fit into that rectangle.
Unknown value: Size of those squares, where the size is such that there will be the least possible empty space left in the rectangle.


while loop error in retrieving data from mysql

Question: I have a database and i want to extract result based on two table of database .say tablea and tableb . php searches for particular id in tablea and if it is found  it has to do the work . it may be confusing here so i  will present my tabela and tableb structure here.i am showing the details for a particular user which i am filtering by where clause
tablea

id         userid
123         45
543         45
454         45
367         45
647         35
565         65

tableb

id        jid
23        123
24        123
25        123
4535      543
4536      543
4506      454
4507      454

etc
we can see that for a particular userid there may be several values in mysql tablea and for each id of tablea there may be several values in tableb id.please note that based on tablea id i want to present all data of tableb and please note that tablea id and tableb jid are same but in tableb jid will appear several times based on the number of times that occurs and for every time there will be new id in tableb. i have don e this query but it results only one output . i want to display all .
$res1 = sql_query("SELECT id from tablea  userid='{$user['id']}' order by id");

while ($row = sql_fetch_array($res1))
{
    $phid=$row['id'];
    {
        $res2 = sql_query("select * from tableb where jid='{$phid}' order by id desc");

        $row2 = sql_fetch_array($res2);
        $d1 = $row2['id'];
        echo ' '.$d1.' ';
    }
}

Comment: You're missing `$` in the `{phid}` part of your second query - so even if the loop was working right, you're doing a where on a fixed string, not the $phid you retrieved from the first query.
Comment: were those {} after $phid=$row['id']; on propose? If so, why?
Comment: You should set php to report errors. Place `error_reporting(E_ALL);` and
`ini_set('display_errors','On');` on top of all the code
Answer: This is much more easily done in one query:
Using an IN () clause:
SELECT * FROM tableb WHERE jid IN (SELECT id FROM tablea WHERE userid='{$user['id']}');

Or with a LEFT JOIN:
SELECT
   tableb.*
FROM tablea JOIN tableb ON tablea.id = tableb.jid
WHERE tablea.userid = '{$user['id']}'

This simplifies the PHP to:
$userid = mysql_real_escape_string($user['id']);
$res = mysql_query(" SELECT tableb.* FROM tablea JOIN tableb ON tablea.id = tableb.jid WHERE tablea.userid = '{$userid}'");
if ($res) {
  while ($row = mysql_fetch_assoc($res)) {
     echo $row['id'];
  }
}

Comment: it returns only one value i want 10 values to display so i was running while loop
Comment: @user1096307 This still uses a while loop to iterate over the result set. It will return as many rows for `jid` as there are. Try it and see.  Also test the query in a plain MySQL client. For example, by your example data, using userid=45 will return 7 rows.
Answer: You should do in single query with join both tables.
SELECT ti.id,t2.id as t2id
FROM tablea as t1 LEFT JOIN tableb as t2 ON t1.id = t2.jid
WHERE t1.userid = '{$user['id']}'

Then make 2D array for showing multiple records of single user in tableb.
Like below :
$dataarray=array();
while ($row = sql_fetch_array($res1)) {
$dataarray['id'][]=$row['t2id'];
}

Answer: This should make it. Although not very friendly.
$res1 = sql_query("SELECT id from tablea  userid='{$user['id']}' order by id");

while ($row = sql_fetch_array($res1)){
    $phid=$row['id'];
    $res2 = sql_query("select * from tableb where jid='{phid}' order by id desc");
    while ($row2 = sql_fetch_array($res2)){
        $d1 = $row2['id'];
        echo ' '.$d1.' ';
    }
}


What are the possibilities to design an API that needs overloads depending on a generic type?

Question: In a given class Example I need the following two functions to be available:
void doSomething(Supplier)
 void doSomething(Supplier)
What are the possibilities to achieve this? I know the following approaches:

give the functions different names
use a wrapper-type for the second-definition WrapperType.of(Supplier)
use a function that converts Example to Example

Are there any other approaches?
I dislike 1) as it clutters my API. 2) is really verbose as I have to call said function often and static imports are very unusual outside of testing code. 3) is very explicit about the internal problem which I don't want the user to 'care' about
Comment: There is a 4th option, make an interface that implements Supplier... So you can have StringSupplier, a ByteSupplier, etc... other than that though, there's nothing you can do.
Comment: Care to share why this question is getting downvoted ? I would like to improve my problem description
Comment: I see, but I am looking for other approaches to have a broader solution set to decide upon. If there aren't any other thats fine for me too though. Thanks for your reply :)
Comment: I will get ambigous an method call then because a lamda `() -> "Hello"` is both a `Supplier` and a `StringSupplier` :(
Comment: @john16384: Your comment made me think from another angle I hadn't thought about yet. I am so thankful for your comment. Thanks, thanks, thanks :) Have a great day
Comment: There is no sense in a declaration like ` void doSomething(Supplier)` Since `B` can be any type the caller wants, there is no difference to `void doSomething(Supplier)` Since this *does* overlap with `void doSomething(Supplier)`, as `B` can be `A`, the method should either, do the same, in which case it is obsolete, or it should have a different name, expressing the different operation.
Comment: You are right, my question is missing bounds on `B` but it would still be impossible to express in Java (with the same name)
Answer: I have found another way by specifying an extension of Function as follows:
class SpecificFunction extends Function {}

Multiple overloads on Function and SpecificFunction can be defined then which would be impossible without an additional class because of type erasure. This works because the java language specification explicitly enforces that the java compiler has to bind a function call to the most specific function it can find. One part in the defnition of how to find the most specific function is as follows: if two functions m(a) and n(b) exists m(a) is more specific than n(b) if b is not a subtype of a, which holds for our SpecificFunction.
Comment: Nice, I'll remember that :)
Comment: A bit more information: actually don't use this as every non-explicitly typed lambda is always resolved to the `SpecificFunction` overload even if the type-parameter cannot match. This is because the java language specification explicitly excluded the usage of any generic type information when resolving which overload to take for such lamdas. As this only works with explicitly typed lambdas or method references - don't use it.


Memory effects of synchronized keyword in Java

Question: This might have been answered before, but because of the complexity of the issue, I need a confirmation. So I rephrase the question
Question 1 :  When a thread enters a synchronized block, the memory barrier will include any fields touched, not just fields of the object that I synchronized on? So if many many objects are modified inside a synchronized block, that's a lot of memory moves between thread memory caches.
Thread 1
object.field1 = "";
synchronized (lock) {
  farAwayObject.field1 = "";
  farAwayObject.evenFarther.field2 = "";
}

Thread 2. assuming thread ordering is correct
synchronized (lock) {
  //thread 2 guaranteed to see all fields above as ""
  //even object.field1 ?
}

Question 2 : Is object.field1 = ""; in thread 1 implicitly part of the happens-before relationship?
I hope it is but It might not. If not is there a trick to make it so without putting it into the sync block? It is hard to reason on the program otherwise
and it is not practical to put everything under the synchronized { }.
EDIT: clarification: object.field1 is not volatile and the question is "will thread 2 guaranteed to see the write of thread 1, at least ". My question is about memory visibility. For the sake of the argument, let's say only thread 1 writes to non volatile object.field1.
The question 2 can be rephrased as
"Will a synchronized block on a lock push changes made before to be seen by other threads synchronizing on the same lock? "
Comment: The answer is yes to both questions.
Comment: @shmosel I had the understanding that `object.field1` would not be a part of happens-before and `Thread2` may or may not see the update?
Answer:
1) When a thread enters a synchronized block, the memory barrier will include any fields touched, not just fields of the object that I synchronized on?

Correct.  (Assuming that thread 1 and thread 2 synchronize on the same lock.)

So if many many objects are modified inside a synchronized block, that's a lot of memory moves between thread memory caches.

Potentially, yes.  However, it is (probably) not movement between caches.  More likely, it is a movement from one processor's cache to memory, and from memory to a second processor's cache.  Of course, that depends on how the hardware implements the memory hierarchy.

2) Is object.field1 = ""; in thread 1 implicitly part of the happens-before relationship?

There is a chain of happens-before relations

The write to object.field1 happens before the lock is acquired.
That happens before the writes to farAwayObject and so on.
That happens before the lock is released by thread 1
That happens before the lock is acquired by thread 2
That happens before thread 2 reads object.field1.

The problem is what happens if there is an intervening write to object.field1, either before the lock is acquired by thread 1, or by some other thread.  In either of those cases, the happens-before chain is not sufficient to ensure that thread 2 sees the value that was written by thread 1.
Comment: can you clarify in the light of my clarification. assume there are no intervening writes. Would you answer yes like shmosel?
Answer:
When a thread enters a synchronized block, the memory barrier will
  include any fields touched, not just fields of the object that I
  synchronized on

Assuming that the fields of farAwayObject and evenFarther are always modified and accesed by obtaining a lock on the same object all around your application, all threads will always see the updates made to farAwayObject and evenFarther since synchronized enforces a happens-before condition.

//thread 2 guaranteed to see all fields above as ""

The same cannot be said for object.field1 without knowing how it was declared. Assuming that field1 is a reference not marked as volatile, it will not be a part of the happens before relationship and threads may see stale values for it.

I hope it is but It might not. If not is there a trick to make it so
  without putting it into the sync block?

Yes. Mark object.field1 as volatile.

Addresing your edit :

The question 2 can be rephrased as
"Will a synchronized block on a lock push changes made before to be
  seen by other threads synchronizing on the same lock? "

AFAIK the answer is Yes, provided that the writing threads acquire the lock before the reading threads. Unfortunately, this is something you generally can't guarantee and that's why object.field1 needs to be marked as volatile or the statement needs to moved inside the synchronized block.
Take a look at JSR 133 which talks about the cache being flushed to main memory when the thread exits a syncronized block. This should clarify things further.
Comment: see my clarifaction. If i don't want to set object.field1 as volatile. isn't the specific write of thread1 to object.field1 pushed to main memory when the synchronized(lock) is executed? If no. would that mean the JVM flags memory changes made under a synchronized lock? so as to only push those changes?
Comment: @Mordan See edit. Does that make things more clear? Let me know if it needs further clarification.
Comment: your link answered my question apparently. It is a yes. I am relieved. :) I have been searching the web for weeks but never found it. Great link ! thank you.
Comment: @Mordan Glad to be of help. I believe my answer would have made more sense quickly if I spoke about the `synchronized` block flushing caches on exit before I spoke about anything else. By yes, do you mean that other threads will *always* see the updated value of `object.field`?. That's not true as explained in my answer.
Comment: By yes.. Provided no other threads write to it, Thread 2 will always see "" in object.field because it synchronized on the same lock. Your link provided another gems. "Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f."
Comment: Those comments prove the subject is tricky. Do you agree with "Provided no other threads write to it and provided Thread 2 acquires the lock after Thread 1, Thread 2 will _always_ see "" in object.field because it synchronized on the same lock" ? @CKing
Comment: @Mordan Yes. Your last comment is correct. That's what I explained in my answer.
Comment: OK then we agree :). In my case I can make sure Thread 2 does not run before acquiring the Lock. It is waiting.
Answer:
the memory barrier will include any fields touched, not just fields of the object that I synchronized on?

Yes.

Is object.field1 = ""; in thread 1 implicitly part of the happens-before relationship?

Yes, even if it is not volatile.

The happens-before order is a partial order.
The happens-before order is given by the transitive closure of synchronizes-with edges and program order. It must be a valid partial order: reflexive, transitive and antisymmetric.
(JLS 17.4.7)

Actions before a synchronization edge (i.e. The release of the synchronized lock) are ordered by program order and thus synchronized with the release. Transitivity says that actions that are ordered by an acquire of the same lock in another thread therefore has a happens-before order with both the release of that lock AND the actions preceding the release of that lock, whether or not it is inside the body of the synchronized block. The important thing to remember about this is that ordering occurs on actions (i.e. Acquire/release of a lock) not a block such as implied by the brackets of the synchronized keyword. The brackets indicate the position of the acquire/release actions as well as where a set of actions cannot be interleaved.
Finally, remember that happens-before is a "partial" order. It means:

Happens before enforces memory consistency when actions happen to come in the particular order (i.e. release/acquire, write/read, etc)
Happens before depends on stronger guarantees such as program order to produce the correct functionality.
Happens before does not prevent errors coming from interleaving of nonatomic actions
Happens before is the transitive relationship between the action and a strong action. (You can put the read of your shared variable outside the synchronized block as long as the write comes before the block and the read comes after the block). Stronger ordering guarantees also follow happens before ordering, but they also provide additional effects described in the spec.


Indexing issue creating a matrix from parts of others

Question: I am trying to create a master dataSheet using bits of other matrices located in the workspace. This visual representation should show what I am trying to achieve:

The arrows indicate the different arrays I am trying to combine. So far 1 to 3 are quite simple. But I cannot figure out how to move 4. The problem is I want it to start at dataSheet(4,1) and go all the way down, but I am getting indexing errors for the things I have tried.
dataSheet = fitVal(:,1)';
dataSheet(2,:) = fitVal(:,2)';
dataSheet(3,:) = 360*asin((1/4)*dataSheet(2,:)*(632.8*1e-9)/(pi*1.332))*(10^6)/pi;
dataSheet(4:length(isf(:,1)),1) = isf(:,1); ?????????????

Any help would be apprecaited. Thanks
Answer: Try this:
nrows = size(isf, 1);
dataSheet(3 + (1:nrows),1) = isf(:,1);

That should do it.
You were trying to put nrows elements into nrows - 3 rows... that's why Matlab was complaining.
Comment: Thank you kindly! Moving parts of matrices have always confused me, this clears up a lot.


Should I use Drop downs instead of radio buttons?

Question: This is for a University Information Repository. The user must choose only one collection to submit a report item into. Each collection is gathered into a community. So the hierarchy from top to bottom goes Community > Sub-community > Collection. At the moment we have radio buttons for every collection. Should I use Dropdowns divided up into the Communities instead of radio buttons?
Comment: Is this helpful? http://ux.stackexchange.com/questions/10728/dropdown-vs-radio-button
Comment: Given that it's a long list of options, it essentially *is* a dropdown list. Just "open" by default. The issue isn't so much radio vs. drop down, but the fact that you're asking a person to pick an item from a huge list in the first place.
Comment: is possible to select 1 item per category, or 1 item in the whole list?
Answer: Because your list is really long, you should look at ways to make it shorter. Harvest has a great open source library for presenting lists. You can create a dropdown with all your options

You can group your categories in to a single dropdown list.
http://harvesthq.github.io/chosen/
Answer: I think you have a bigger issue here: Radio inputs are unique, so the giant list is not needed at all, it only adds friction to the flow. You also say this:

So the hierarchy from top to bottom goes Community > Sub-community >
  Collection

Thus, why don't you simply let the user select the Community, then display ONLY the available sub-communities for users to choose, then ONLY the available collections within that community?
These approaches can be achieved with a variety of methods, from simple page to page navigation to AJAX based selection, enable/disable accordions and so on. But the most important part is to guide the user to a narrow and filtered set of options.
This way, you reduce the friction in the flow while accurately guiding the user to perform the right action for the right content, minimizing the chance for errors
Answer: On dropdowns
Good:

Takes little space - good when there are many fields to display on the page and there are many option to choose from. For 2 or 3 options radio groups are often better.

Bad:

Extra click for selection.
Users can't see the options before opening the dropdown.
With long list it can be hard to find the right option.

Your case
I believe that in your case there is only the collection selection on the page, so I don't see any reason to hide all these options in a dropdown.


How do I travel to other systems?

Question: I recently started playing naev at the suggestion of some of our users, and so far it seems like a pretty fun game.
One of the problems I seem to be facing, however, is an inability to travel to any systems other than Hakoi and Enegouz. This makes my transport missions quite difficult, and is really keeping me from advancing in the game.
How can I travel to the other systems, like Apez and Gamma Polaris?
Answer: You have to explore around the edge of the sector to find a jump gate.  Just fly around the edges of the sector to look for them.  If you don't want to explore, you can choose to buy a local system map at any planet in the sector with an outfitter (I make it a habit to buy a local star system map for any sector I visit).  Finally, having a jump scanner addon for your ship means you can detect the gates at a much further range, making them easier to find.

How do I travel to other systems?


Could not load type .... from assembly error when trying to add dll (user control)

Question: I made my custom user control, so that i use it in different applications. The problem is that when i want to rename dll which i get in bin/debug ,then drag it into toolbox, i get that error:

I tried with renaming user control namespace , name and solution name, but it still generates dll with old name every time.
How to get desired new dll name and is it even possible?
It would be hard and elbow grease work if i create new control with new name and
start from beggining.
Answer: You should change the assembly name.
In solution explorer, goto the project properties (right click on the Project -> Properties  or press Alt+Enter). Under the 'Application' tab you will see a textbox for Assembly Name.
Change the textbox value to the desired name you need. Then build the project.
Now you should have your dll with the new name.


Trying to set X-Powered-By header, no luck

Question: I'm trying to set a custom X-Powered-By header in PHP. I set it at the end of my document, and it doesnt't show up when I use cURL to see the headers.
This is a snippet of my code:
<?php
header('X-Powered-By: Riverside Rocks');
die();
?>

Is there anything I am doing wrong?
Comment: Are you getting any errors or warnings in your logs?
Comment: Do you already output any content? If so this won't work. Move it to the top of your file so it is output before any content.
Answer: Fixed - Some file was messing everything up, it was listed in my error log and may have messed with the headers.
PHP Warning:  Cannot modify header information - headers already sent by (output started at /var/www/html/includes/tracking.html:1) in /var/www/html/includes/header.php on line 5, referer:


Custom model problems

Question: I am having two problems with custom models in my resource pack. I am not sure, but I think that they are related. I have looked everywhere and found this and this.

you cannot give a solid block a model like that

Is there any way of fixing it? Here is a screenshot with both problems:
Comment: I can't seem to infer what problem you're trying to solve. Well, at least not with 100% accuracy. Are you asking for help with the fact that your block has a base color that is not grass, and therefore stands out? That's the only issue I see.
Comment: @Tacoタコス I want to solve the problem that the diagonal sides are dark and that when you look under it you see void and not grass.
Answer: As the post you linked specifies, due to how Minecraft renders textures, blocks which should be solid will remove textures connecting to other solid blocks. It's why the post has a screenshot showing why a slab works, but not solid dirt.
Your best bet would be to, maybe, create a texture for the bottom, or simply not use that model.
Comment: Is there any way of fixing it?
Comment: as i said, your best bets are only to make a texture of some form for the bottom or to not use that model
Comment: OK. But how do I make Minecraft think that it was never a full block in the first place?

Custom model problems


Send newsletter to Gmail having div with background image

Question: I can send newsletters to email accounts. I am using div for containing the text. Now, I want to set a background image to the div as demonstrated in the code below:
string containerDiv = @"
";

But the problem is, my Yahoo account can fetch the image in its body but my Gmail account cannot. Below are two screenshot: I used 'Inspect element' option in Google Chrome to get the rendered div in my browser.
Yahoo:

Gmail:

My question is what is the problem in my code? Why can Yahoo get the URL properly and render it but Gmail cannot get the URL and cannot render it? What should I do if I want to display the background image in Gmail as well?
Comment: If that's the kind of BG image you're including, I'd rather be reading (and be ABLE to read it) on gmail than seeing that ugly blob in Yahoo...
Comment: I see at least missing opening parenthesis after `url`.
Comment: i pasted the right code now.but it is not working
Answer: You are missing the bracket after "background:url".
Should be
style=""background:url('http://www.instantfetch.com/Content/restaurant_logos/promo1.gif');""
I guess Yahoo is overlooking your mistake.
Answer: The "" might be causing the issue. Try this:
string containerDiv = @"
";

Answer: Gmail does not support background images.
It's created many problems here and caused redesign due to the limitation. It's not your code... it's Gmail.
Comment: yes. you are right. i have tested so many ways last day but couldn't make it happen. :)