Sill plates (thresholds) before floor tiles or otherwise?

Question: The contractor wants to install the granite sill plates now and later have the tiles installed. I heard from one granite fellow that the sill plates should be last.
Is there any advantage for going one route or another? I would like to have the sills already installed and be done with it, but I also don't want gaps between the sill and the tile.
Comment: Granite sill plate? Do you mean a tile base?
Comment: I might be using the wrong word. I mean the pieces of granite that goes between different floors and below doorways. In Brazil that I'd very common : http://3.bp.blogspot.com/_lX6_MZ6kq0I/TUra7YgAfJI/AAAAAAAAANw/LBOkUn_mmSE/s1600/IMG_1035.jpg
Comment: Ahha. I'd call that a threshold but every area had its own lingo.
Comment: I might me using the wrong word, i thought of window sill, then i went to door sill and pictured that it might also be called sill.
Comment: No worries. Terminology is always a hurdle even between tradesman.
Answer: In terms of the general process it's acceptable to do it threshold(sill plate) first but there may be specifics to the situation that we're not aware of. Contractors are primarily concerned with pushing the project along to keep pace, but occasionally to do that you have to do things out of sequence. An example would be, if the threshold is available but the tile isn't in yet, a contractor would be tempted to set the thresholds first. This might make it look like progress is being made but it could ultimately make your tile guys job a lot more difficult. If the guy contracted to do the tile work wants to do it a particular way, I would trust his/her judgement unless the contractor can produce a very compelling reason not to. In the end (however they do it) if the finished product isn't satisfactory it's on them to make it right.
Comment: Hmm, that does change things. I'll scratch my head and get back to you.
Comment: I have gone round and round on this and I just can't in good conscience advise you one way or the other without being intimately involved in the project. There's just too many variables. All I can say is I can't think of anything specifically wrong with setting your thresholds first.
Comment: The contractor really wants to push the threshold now because he will be doing the screed layer over the concrete base. He is not the one who will do the tiles (i think that i will do that, as the tile workers around here aren't reliable).
Answer: I would suggest doing the thresholds first.  These are very prominent and you want the things that stand out looking the best.  In a doorway if you do threshold first then it is a rectangle fitting doorway.  If you do the threshold last, than who knows - this would be up to how square your room is and how well you aligned your tiles.
Added: Also when cutting or placing threshold you want to align it up with the wall in the room you will tile.  So you have threshold, grout, then first tile row.  You shouldn't have to cut the first row of tile to adjust for the threshold - they should flow over threshold.


Haskell - How to construct a program which will read some setting files?

Question: According to the introduction about ReaderT , I can only find:
ReaderT Env IO String

And it means
...is a computation which involves reading values from some environment
of type Env (the semantics of Reader, the base monad) and performing some
IO in order to give a value of type String.

So the order of execution will become
1. ( Already has ) some environment values          -- ReaderT Env
2. Do `IO` accroding to these pre-existing values   -- IO a
3. Use the `IO a` values to do more computations    -- IO b...z

This will requests our program has some pre-existing values as the environment, but I thought most of program need to load these environment values. Such like the database URL, debugging switcher or anything else.
Thus, we have an inverse order of execution, and which is illegal according to the Monad stack:
1. Do some `IO` to load environment settings        -- IO a first !!
2. Do more `IO` according to these settings         -- fill the env and do IO

The monad stack will become:
IOT Env ReaderT Env

This is illegal because the IO monad can't be the base monad in monad stack. So, is there a proper way to initialize my program with external setting files ?
PS1. I noticed that the xmonad compile it's settings as a part of program. I'm still not sure whether this is the only way to "load" settings...
Comment: have a look at this similar question: http://stackoverflow.com/questions/11226338/missing-something-with-reader-monad-passing-the-damn-thing-around-everywhere
Comment: Reading a config file is no different from 'reading' command line arguments. You don't need ReaderT, just `config <- fmap parseConfig (readFile "config")` which is no different from `number <- fmap (read.head) getArgs` as Roman is saying.
Answer: First, the order of monads in the monad stack doesn't have anything to do with the order of actions that you're going to perform.
Second, you probably don't even need a stack here.
A typical program that deals with configuration is structured in the following way:
data Config = ...

readConfig :: IO Config
readConfig = do
    text <- readFile "~/.config"
    let config = ... -- do some parsing here
    return config

meat :: Reader Config Answer
meat = do
    -- invoke some operations, which get config automatically through the
    -- monad

main = do
    config <- readConfig
    let answer = runReader meat config
    print answer

You need a monad stack only if meat itself needs to perform some IO (apart from reading the config). In that case, you'd have
meat :: ReaderT Config IO Answer
meat = ...

main = do
    config <- readConfig
    answer <- runReaderT meat config
    print answer

Comment: But in the 18th chapter of the book "Real World Haskell" : "We use a WriterT on top of IO because there is no IOT monad transformer. Whenever we use the IO monad with one or more monad transformers, IO will always be at the bottom of the stack" -- the order of stack still make differences ?
Comment: And thanks for the `main` function in your examples! I got it when I saw the function extracting values in `IO` field, and treated it as environment.
Comment: By the way, can I conclude that the monad transformer is not necessary, unless a computation under a monad ( Reader in the example ) will use anything in another monad ? Because your said: "You need a monad stack only if meat itself needs to perform some IO (apart from reading the config). "
Comment: Monad transformers are a way to combine features of multiple monads. If you need just one monad (which isn't uncommon), then you don't need transformers. Yes, the order of monad transformers in the stack matters, in general. For more info on that you can try reading my article, http://ro-che.info/articles/2012-01-02-composing-monads.html, although it does assume some familiarity with the subject.


How did the sideboards come to be raised over a hardwood floor?

Question: I'm a little puzzled at the position of sideboards in this picture.

I am not covering with carpets. I will remove the sideboards, hopefully without breaking them. Then I'll paint them before re-installing them, and renovate the floor while they're off. I'm assuming that it's all right in the final look for a few nails to remain visible, and that I can be spared having to apply masking tape to the entire perimeter of each room on both sides of the sideboards. Leaving the sideboards high is not an option because it looks ugly and, more importantly, is a recipe for having dust and mites.
My question is: how did the sideboards reach this position. If initially a carpet was installed in this bedroom, I have a hard time believing someone would have used a reasonably decent hardwood (oak? I'm not sure) as a foundation for the carpet.
If the hardwood was initially installed, then the sideboards would not be where they are.
My conclusion is that when I spot this sort of thing (hardwood and elevated sideboards) it means that the room must have gone through three stages:

Hardwood was initially installed.
At some point someone decided to install a carpet. That person raised the sideboards.
In a third renovation someone decided to get rid of the carpet. So they just ripped it and didn't bother to lower the sideboards.

Did the room really have to have gone through these three stages of renovation for the sideboards to be high over a hardwood floor, or is there a simpler explanation?
Comment: You should be able to tell if the molding was installed after the floors were renovated or before, just look to see if the current stain and varnish extend under the molding.
Answer: Plenty of homeowners put carpet over hardwood in the 60s, 70s and 80s. It's not clear why the baseboard and base shoe are elevated, though. Normally shoe isn't used with carpet.
To avoid unsightly lines left on your walls, I'd remove just the shoe, finish the floor, sand and paint the baseboard (in place), then reinstall the shoe tight to the floor.
Comment: Baseboard may have been elevated to hide carpet edges, which some find easier than trimming the carpet neatly and precisely to the wall. The whole purpose of baseboard is to hide the sometimes-messy transition from floor to wall, after all.
Comment: In my experience, base is rarely raised when carpet is installed over existing hardwood. Not saying it doesn't happen. I was mostly referring to confusion over the shoe, though. Maybe it was a commercial-style carpet where shoe looked nice.
Comment: Granted, it's more common to have the shoe handle the carpet transition.
Comment: I didn't even consider that the "base shoe" is optional. So you're suggesting that the base shoe is decorative enough that I should really reinstall it over hardwood, even if it's not necessary with carpets (though I'm puzzled why it ceases to be decorative with carpets).
Comment: Shoe is typically used with hard floors to cover expansion gaps and add aesthetic appeal. It's not typically used with carpet because it wouldn't be supported, and is likely to sag away from the base trim over time due to impacts and gravity. It also looks a bit odd because it's apparently floating over the carpet.
Answer: i am not sure how much simpler you could ask for.  we see this all the time.  many people historically have covered over hardwood floors with carpet for style, fashion or camouflage )stains, wear, etc).  your description of events matches perfectly to my experiences of same.  there are no elves or goblins that are doing this to irk you.  you are just not seeing the perspectives of previous users of that space.
Answer: Styles change over time, that's just a fact of life.  At one time shag carpet was in, so folks tended to install it in their homes. In more recent times, hard surfaces seem to be popular.  As folks rip out carpeting, they find that the molding also has to be adjusted to compensate.
Molding is a decorative finish material, and as such is normally installed very near the end of the construction process.  This means that the molding is usually installed on top of the floor covering, and is used to make a more attractive transition between floor and wall.
Whenever the finish floor material is changed, the molding should be removed and reinstalled.  This is a step that most flooring installers neglect. Fortunately, if you're installing a similar type of floor covering, the molding may not have to be adjusted.  Other times, lazy installers use shoe moldings to avoid adjusting the molding.
You wouldn't expect to leave the molding around a window or door, if you were replacing the window or door. So I'm not sure why there's an expectation to leave base molding in place, when you're changing the floor covering.
A previous occupant of your home removed carpeting, but never adjusted the base molding accordingly.  If you're not happy with this, it's up to you to make it right. Carefully remove the molding, and reinstall it at the proper height. Cover any nail holes with filler, and paint the filler to match (this may require painting the entire piece of molding).
Comment: You're giving me an important hint. I vaguely intended to either: 1- take out the baseboard *and* the base shoe (thank you, isherwood, for the proper terminology) and then install both, but lower, or 2- take out just the base shoe and lower just it (I confirmed in the closet that that would not leave the baseboard too high). From your answer I see that another option is to lower the baseboard and simply discard the base shoe.
Answer: I put baseboards 1/16 or 1/8 inch or so above the wood floor without touching it, using a thickness of cardboard as a spacer.
This is part of the sound-dampening system so the upstairs doesn't turn into a drum for the room below. The gap is meant to then be filled with a sound-dampening caulk, but it smells so bad that I might not bother with it for subsequent rooms.
In my case, there is sound dampening material below the wood surface. You may have something like that, or have a "floating" floor and want to keep it uncoupled at the edges of the room too.
Comment: In wood-frame homes I find that no parameter is more important than sound proofing. It's very tough to achieve. It seems that maintaining heat is the dominant factor in construction. So I'd love to follow your advice and keep a gap when lowering the baseboards, but I fear that without caulking doing so would be a recipe for harboring over the years any number of allergens and unsavory minuscule gremlins.
Comment: So use calk. Even plain silicone will prevent vibration transfer; I don't know how much better is the stuff sold for that purpose.
Answer: I observed a similar situation on the ground floor in a circa 1940 house I had just bought
The difference was that the quarter round had stayed attached to the floor as the floor sank, leaving a 3/4 inch strip of different colored paint on the baseboard, which was nailed to the wall.  The previous owners had removed about twelve feet of load-bearing masonry wall in the basement, along the line of the ground floor wall, and bridged the resulting gap with three 2x4s on edge as a header.
Before following all the other good answers, eliminate slow structural collapse as an explanation.
Comment: Thanks for the hint. It's intriguing, and it's of course very important to keep an eye on whether structural deformation is the culprit, but the hallmark of that would, I suspect, be a nonuniform gap. As long as the gap is the same all around, there is no need to worry.
Answer: I've had the misfortune to experience this myself. It's possible that your foundation is sinking.
I discovered I lived in a house with a sinking foundation when after many years of carpets, the landlord approved and paid for a hardwood floor install. The installer had to add concrete in one corner to level the foundation. (The drying concrete was in the shape of a puddle.)
Now, a few years later, the baseboard is an inch or so above the flooring.
Answer: This is how this happens. See Question - What height to set baseboards before carpet is installed? You're absolutely right that it should NOT be this way at all. And, you can't lower the shoe molding because there's no baseboard or anything to nail or screw to, sorry.
Only if there was a floating laminate floor should there even be a shoe molding & a corresponding gap. Not for carpet, unless you have an inept carpet installer.
You'll have to either remove them & re-install them correctly or spline fill & also caulk the gap into non-existence. The gap will not be perfectly uniform.


difference between sizes javascript transform:scale(?.?)

Question: using javascript to calculate; how do I use transform:scale(w,h); to get this div to scale to fit its parent container?
I was in special math group at school so I'm not sure what I am googling (ratio, length comparison, proportion, fraction?) seen as we never learned that stuff (maybe for a day or two).

 I want to always fill my parent

edit: btw, I don't want to use width/height:100% because I have an image inside the square that is fit like that so, i really need to zoom.
this seems to zoom inward to the microscopic level:
'-webkit-transform':'scale('+$('#container').width()+'.'+$('#square_of_unknown_size').width()+','+$('#container').height()+'.'+$('#square_of_unknown_size').height()+')'

px A compare B px get A.B = always fit
Answer: You have to calculate the proportion between the two divs:
var scaleX = $('#container').width() / $('#square_of_unknown_size').width();
var scaleY = $('#container').height() / $('#square_of_unknown_size').height();
$('#square_of_unknown_size').css('-webkit-transform', 'scale(' + scaleX + ',' + scaleY + ')');

Comment: I cant see how its just divide!? and cause my div is always a square shape its like scale(scale+','+scale)
Comment: can the effect be reversed?
Comment: For example, if the container is 200x200, and the content is 100x100, the scale is 2.0, i.e., the content must be scaled by a factor of 2 to fit the container.


rxjs6 Timer not being triggered in Angular 6 subscription to observable timer placed in service

Question: I'm trying to put a timer from rxjs 6 in an angular 6 service. And it's  not being triggered. I looked in the documentation without any luck. This is my service code(only the relevant part:
import { map,flatMap, catchError, take } from 'rxjs/operators';
import { BehaviorSubject, of, throwError,timer, Observable } from "rxjs";

.....

  countdownTimer = new Observable<number>();

  formatCountdownTime(count) {
    const seconds = count % 60 < 10 ? '0' + Math.floor(count % 60) : Math.floor(count % 60);
    /*    if(count <= 1000){
         //set timer to NOT RUNNING state so it updates UI components like the button that depends on the count
          this.contributorManagerService.countdownTimerIsRunning.next(false);
       } */
       return Math.floor(count / 60) + ':' + seconds;
  }

  createCountdownTimerObservable(count){
    this.countdownTimer =  timer(0, 1000);

  }

and this is the consumption of the timer. I need to know when time has elapsed and that's why I'm passing that 3rd function parameter to the subscription since I need to enable a button when the time is up.
import { map,take } from 'rxjs/operators';

export class CampaignDataComponent implements OnInit, OnDestroy {

 countdownTimerIsRunning = false ;
 count: number;

ngOnInit(){

/* I subscribe to the timer and the 3rd parameter indicates what to do when time has elapsed */
      this.sharedHelpersService.countdownTimer.
      pipe(
        take(this.count),
        map(() => {
          --this.count;

          return this.count;
        })
      ).subscribe(count=>{
        console.log("New count",count);

          if(count>0){
             this.countdownTimerIsRunning = true;
          }
      },
      err=>{
        console.log("Countdown timer error", err);
      },
      ()=>{
        console.log("Time has elapsed");
        this.countdownTimerIsRunning = false;
      });

}

}

Do you know why is not being triggered? It used to work when I used the whole chain on the component but since I need to consume it from other components I had to put it in a service and that broke it. Any ideas?. Thank you very much in advance
EDIT: Just to clarify, they all the components should consume the same countdown
Answer: The problem is with this code
  pipe(
    take(this.count),
    map(() => {
      --this.count;

      return this.count;
    })

I am assuming there is no other code in the component than that so this.count initializes to 0.  You then subscribe to the observable and say effectively take(0), so then the observable immediately completes.
Comment: An ngIf condition made the component unreacheable. this helped me detect the first stage of the problem!!
Answer: The following should do the trick to have a timer shared by multiple components:
Service:
import { Injectable } from '@angular/core';
import { timer, Subject, Observable } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';

@Injectable()
export class CountdownService {

  private _countdown = new Subject<number>();

  countdown(): Observable<number> {
    return this._countdown.asObservable();
  }

  private isCounting = false;

  start(count: number): void {
    // Ensure that only one timer is in progress at any given time.
    if (!this.isCounting) {
      this.isCounting = true;
      timer(0, 1000).pipe(
        takeWhile(t => t < count),
        map(t => count - t)
      ).subscribe(
        t => this._countdown.next(t),
        null,
        () => {
          this._countdown.complete();
          this.isCounting = false;
          // Reset the countdown Subject so that a
          // countdown can be performed more than once.
          this._countdown = new Subject<number>();
        }
        );
    }
  }
}

A component can initiate a countdown with
countdownService.start(myCountdownTime)

and all components interested in the countdown time can subscribe with
countdownService.countdown().subscribe(t => ...)

Stackblitz Example
Comment: All the answers were really useful and Brandt thought me a lot about rxjs. For this particular case I had the need to create a service like yours for a couple of reasons and that's why I'm picking this answer
Comment: just to clarify, I had to create an additional behavior subject to check if a new timer has started since otherwise some components wouldn't update unless I refreshed the page, I added that over your solution and it worked really well
Answer: When you say that you need to consume the countdown from other components, if with that you mean that you need to consume the functionality from other components but that each component that subscribes has their own independent countdown, then you can do the following:
Service:
import { timer, Observable } from 'rxjs';
import { filter, takeWhile, map } from 'rxjs/operators';

// startTime is in seconds
count(startTime: number): Observable<number> {
  return timer(0, 1000).pipe(
    takeWhile(t => t < startTime),
    map(t => startTime - t)
  )
}

Component:
// Count down for 10 seconds.
countdownService.count(10).subscribe(
  t => console.log(t),
  null,
  () => console.log('Done!')
)

This will print: 10 9 8 7 6 5 4 3 2 1 Done!
Comment: First of all thanks for your help! No, all the components needs to consume the same countdown since it's to enable different UI components and the same countdown lives after components are destroyed and created
Comment: Sam Herrmann since one of the components initiates the countdown and then the same countdown is consumed by 2 components more that has UI elements that need to be updated
Comment: See my other answer. I hope that's more inline with your requirements.


RAM problems while creating and deleting custom QWidgets inside of QLayout

Question: I have created a custom QWidget (code below) [with a QHBoxLayout and two QPushButtons inside] and added it to a QVBoxLayout in GUI. This custom QWidget-object will be created and deleted several times (code below).
When I type top inside into the console (on embedded linux) there is a RAM-increase every time I add a new QWidget. That's Ok! But I can't see a decrease of RAM on deletion.
What is wrong with my code? I want, that the RAM decreases on deletion of the custom QWidgets.
myCustomWidget.h
class QCustomPushButton_withinIcon_LeftAndRight : public QWidget {
    Q_OBJECT

public:
    //functions
    QCustomPushButton_withinIcon_LeftAndRight(QWidget *parent = 0);
    ~QCustomPushButton_withinIcon_LeftAndRight();

    //other slots like:
    // - virtual void mousePressEvent();
    // - virtual void mouseReleaseEvent();
    //other signals like:
    // - void clicked();
    //other functions like:
    // - virtual void setEnabled(bool a);
    // - virtual void paintEvent(QPaintEvent *);
    // - ...

private:
    //variables
    QLayout *innerLayout;           //!< Layout for two buttons
    QPushButton *buttonLeft;        //!< Button left
    QPushButton *buttonRight;       //!< Button right

    //other variables like:
    // - bool enabled;
    // - ...
};

myCustomWidget.cpp
QCustomPushButton_withinIcon_LeftAndRight::QCustomPushButton_withinIcon_LeftAndRight(QWidget *parent) :
    QWidget(parent),
    mSVG (new svg),
    mGradient (new gradient)
{
    enabled = true;

    //create innerLayout
    innerLayout = new QHBoxLayout();
    this->setLayout(innerLayout);

    //create buttons
    buttonLeft = new QPushButton();
    buttonRight = new QPushButton();
    innerLayout->addWidget(buttonLeft);
    innerLayout->addWidget(buttonRight);

    //create connections like:
    // - connect (buttonLeft, SIGNAL(pressed()), this, SLOT(mousePressEvent()));
    // - ...

    //set some stylesheets
    // - buttonLeft->setStyleSheet("...");
}
QCustomPushButton_withinIcon_LeftAndRight::~QCustomPushButton_withinIcon_LeftAndRight()
{
    //I think, that this is right. If not, correct me.
    delete buttonLeft;
    delete buttonRight;
    delete innerLayout;
}

//void QCustomPushButton_withinIcon_LeftAndRight::mousePressEvent() {}
//void QCustomPushButton_withinIcon_LeftAndRight::mouseReleaseEvent() {}
//void QCustomPushButton_withinIcon_LeftAndRight::setEnabled(bool a) {}
//void QCustomPushButton_withinIcon_LeftAndRight::paintEvent(QPaintEvent *) {} ...

gui.cpp (add QWidgets to a QLayout in the GUI)
    QCustomPushButton_withinIcon_LeftAndRight *button = new QCustomPushButton_withinIcon_LeftAndRight();
    //add button to layout
    parentUiWindow->aLayoutNameInGui->addWidget(button);
    //aLayoutNameInGui is type of QVBoxLayout

gui.cpp (delete QWidgets in a QLayout that is in the GUI)
    //delete all buttons in layout
    QLayoutItem *child;
    while((child = parentUiWindow->aLayoutNameInGui->layout()->takeAt(0)) != 0) {
        //parentUiWindow->aLayoutNameInGui->removeWidget(child->widget()); //already removed by ->takeAt()
        //child->widget()->setParent(NULL);
        delete child->widget();
        delete child;
    }

Comment: I'm sure there must be a few duplicates around regarding this issue. But the "problem" is most likely that the operating system doesn't have to unmap the allocated memory pages from your process when you `delete` or otherwise free memory. Instead it can do it at any time it feels like. That means those pages will seem like a memory leak. It's a false positive.
Comment: I see you create `mSVG` and `mGradient` with `new`, but do you destroy these objects anywhere?
Comment: It would be easier to read and replicate your code if you put the function declarations in your code instead of "gui.cpp (add QWidgets to a QLayout in the GUI)"
Comment: @Someprogrammerdude are you really shure? That would be great if it is true.
Comment: @thuga I tried, to delete them to.. app does actually better after that
Comment: @thuga I think, that this was actually the problem. Great thanks :) just write an answer (refer to `someprogrammerdude`: he has a important point to).
Answer: When you look at the memory usage with the top command, you can get false positives. As stated by some programmer dude, the OS doesn't always release the allocated memory from your process when you call delete on some objects.
However, you are creating two objects in your QCustomPushButton_withinIcon_LeftAndRight constructor with new:
mSVG (new svg),
mGradient (new gradient)

but you never seem to destroy these objects. So you might have a memory leak there.


How do I get Rei's Minimap waypoints from inside the .minecraft folder?

Question: So I read this post and I did what it said, but when I tried to open the .points files, it either said it was empty or that it wasn't supported. What do I do?
Comment: IIRC either in the mods folder of config
Answer: It sounds like you just tried to click the file open. Since it has a .points file extension, that won't work on most operating systems. You need to open it in a text editor.
Answer: Simply double-clicking on the points folder is not going to get you anywhere since such a file extension is not supported by any known program.  You will need to right click on the file and choose the Open With option if it is available.  A lot of the time on these really strange database files however, that isn't an option.  So double click it and select the second option which should read: "Select a program from a list of installed programs" then hit OK.
Use Notepad to open it.
Copy and paste by opening the new installation the same way and so forth.


12.04: php5-curl not working, NOT a LAMP server

Question: I've just setup a fresh install of 12.04 Server. Have everything working nicely, except getting this php5-curl mod to work.
I ran apt-get install curl libcurl3 libcurl3-dev php5-curl
So I go check phpinfo(); and there's no curl section.
Answer: I heard I have to include a line in my /etc/php5/apache2/php.ini file, so I included:
extension=php_curl.so
and now it's working.


Function is returning the array not value

Question: I have a function in PHP that is returning the array but not the value.
Can you tell me what I am doing wrong
<code>function get_current_call_count() {
    //Variable declearation
    $line1="";
    $line2="";
    $total_call_count="";
    $current_call_count="";
    $var=array();
    // Executing shell command to get total number.
    $shell_command = ("/usr/sbin/asterisk -rx 'core show calls'");
    exec($shell_command,$result,$status);
    //print_r($result);
    $line1=explode(" ",$result['0']);
    $current_call_count=$line1['0'];
    $line2=explode(" ",$result['1']);
    $total_call_count=$line2['0'];
    $var=array("$current_call_count","$total_call_count");
    return($var);
    //echo("Current call count is $current_call_count and Total system call count is $total_call_count");
}
</code>
Comment: What value are you expecting? You are attaching an Array to `$var` so its obviously that you return the Array.
Comment: @putvande are you saying about this line `$var=array("$current_call_count","$total_call_count");`
Comment: Yes that line is attaching an array to `$var`.
Answer: Your function is returning array, because you made it so:
<code>$var=array("$current_call_count","$total_call_count");
return($var);
</code>
So all is fine. I suspect that later on you try to use the value returned by this function as non array, so cast occurs and you end with "Array" string. But it's your fault in later code. If you want use certain value from the array, you must get it from there, which is most likely missing in your other code.
Comment: i am using like this `$var=array();
$var = get_current_call_count(); `
Comment: how can i get the values that i get from arrary or how can i split
Comment: try then $var[]=get_current_call_count(); or just $var=get_current_call_count(); without setting $var=array();


Cannot animate (0).(1) on an immutable object?

Question: I have a ComboBox with a custom theme I wrote, and I get the error message "Cannot animate (0).(1) on an immutable object." This specifically happens when I set its selectedindex after the user selects one of the options in the combobox.
Doing some research online, I found that this is a common issue with databound items or dynamic resources. I'm not using any databound resources, but what I think is happening is since the combobox is collapsed, it tries to set the state of a button that doesn't exist. I narrowed it down to this code:
<ControlTemplate.Triggers>
  <Trigger Property="IsSelected" Value="True">
     <Setter TargetName="Border" Property="Background" Value="{DynamicResource spPressedStateBrush}" />
  </Trigger>
  <Trigger Property="IsMouseOver" Value="True">
     <Setter TargetName="Border" Property="Background" Value="{DynamicResource spOverStateBrush}" />
  </Trigger>
</ControlTemplate.Triggers>

Which depends on these Dynamic Resources:
<LinearGradientBrush x:Key="spOverStateBrush" StartPoint="0,0" EndPoint="0,1">
    <GradientStop Color="#2C8CBF" Offset="0" />
    <GradientStop Color="#2793BF" Offset="0.5" />
    <GradientStop Color="#2483BF" Offset="0.5001" />
    <GradientStop Color="#2C8CBF" Offset="1" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="spPressedStateBrush" StartPoint="0,0" EndPoint="0,1">
    <GradientStop Color="#0C6C9F" Offset="0" />
    <GradientStop Color="#07739F" Offset="0.5" />
    <GradientStop Color="#04639F" Offset="0.5001" />
    <GradientStop Color="#0C6C9F" Offset="1" />
</LinearGradientBrush>

So I'm pretty sure those dynamic resources are the culprit, but how would I solve this problem?
Comment: You narrowed the code a bit too much. Show us more please. Upload your project somewhere online. Those are all triggers, where is the animation?
Comment: @devhedgehog oops I said animation by accident, they aren't animated they're instant, I'll update the question
Comment: Can you show full code? I have a trigger works fine setting of a dynamic resource.
Answer: After painstakingly trying to debug it by comparing the code to the original Control Template, I figured out that transporting all of the resources that my control uses into the file itself, and replacing all DynamicResources with StaticResources and that fixed the bug I was having.
Answer: Be sure that both this two (spOverStateBrush or spPressedStateBrush) Brushes are not used in different place in your code.
In order to be animatable, the Background Brush (spOverStateBrush or spPressedStateBrush) of the Border must be mutable, which the default value isn't.
If you use one of these two Brushes in another place, You should assign a new LinearGradientBrush before animating something like this code:
    LinearGradientBrush gradient = new LinearGradientBrush();
    gradient.StartPoint = new Point( 0.5, 0 );
    gradient.EndPoint = new Point( 0.5, 1 );

    gradient.GradientStops.Add(new GradientStop(Colors.Black, 0));
    gradient.GradientStops.Add(new GradientStop(Color.FromArgb(100,69,87,186), 1));

    Border.Background = gradient;


Derive a new equation from $m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$

Question: $$m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$$
$$\implies m^2=\frac{m_0^2}{1-\frac{v^2}{c^2}}$$
$$\implies m^2c^2-m^2v^2=m_0^2c^2$$
Differentiating the equation,
$$2m \;dm\;c^2-2m\;dm\;v^2-2v\;dv\;m_0^2=0$$
Our book says when we differentiate $m^2c^2-m^2v^2=m_0^2c^2$. We will get the above equation. But, what I understand about Calculus. That I can't derive it anyway. Actually, what we differentiate here? $mass$ or, $velocity$?
Relativistic mass equation :
$$m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$$
Above question is a constant equation which maybe found from Lorentz Transformation. In the second line I've just squared both side. In third line I've just moved "something" right to left. Then, I differentiate. But, I can't understand how they differentiate here.

After writing the question, I was doing some the sum again.
Relativistic mass changes over time (How fast you travel through space your mass decreases). Here $m$ is relativistic mass and $m_0$ is "normal" mass.
So, I decided to differentiate mass
$$(mc)^2-(mv)^2-(m_0c)^2=0$$
We know,
$$(f(x))^n=n(f(x))^{n-1} . f' (x)$$
Then :
$$2 (mc) . c - 2 (mv) .v -$$
Then, I can't differentiate anymore. $c$ is speed of light which is constant. That $m_0$ is also constant. So, I stopped there.

Prove of $E=mc^2$,
$$F=\frac{dp}{dt}$$
$$=\frac{d}{dt} (mv)$$
$$= m \frac{dv}{dt} + v \frac{dm}{dt}$$ ----------------1
$$dW=F .dS$$
$$=>dK=F .dS$$
$$=>dK=[m \frac{dv}{dt} +v \frac{dm}{dt}] .dS$$
$$=m\frac{dS}{dt} .dv + v . \frac{dS}{dt} .dm$$
$$=mvdv+v^2dm$$ -------------------2
$$m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$$
$$\implies m^2=\frac{m_0^2}{1-\frac{v^2}{c^2}}$$
$$\implies m^2c^2-m^2v^2=m_0^2c^2$$
$$2m \;dm\;c^2-2m\;dm\;v^2-2v\;dv\;m_0^2=0$$
$$c^2dm=mvdv+v^2dm$$ ---------------3
$$dK=c^2dm$$
$$\int = \int c^2dm$$ (In LHS Integral starts from 0 and finishes at $k$. In RHS Integral starts from $m_0$ and ends at $m$)
$$k=c^2[m-m_0]$$
Hence,
$$Total energy = k + Rest mass energy$$
$$E=c^2[m-m_0]+m_0c^2$$
$$=mc^2-m_0c^2+m_0c^2$$
$$=mc^2$$
$$E=mc^2$$
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/127108/discussion-on-question-by-istiak-derive-a-new-equation-from-m-fracm-0-sqrt).
Answer: Say you are given
$$
m(t) = \frac{m_0}{\sqrt{1 - \frac{v(t)^2}{c^2}}},
$$
for some $t> 0$, with constants $m_0$ and $c$. Then, differentiating with respect to time, we get that
$$
\begin{align}
\frac{dm(t)}{dt} = \dot{m}(t) &= m_0 \frac{d}{dt}\left(1 - \frac{v(t)^2}{c^2}\right)^{-\frac{1}{2}} \\
&= \frac{-m_0}{2c^2} \frac{d}{dt}\left(v(t)^2\right) \left(1 - \frac{v(t)^2}{c^2}\right)^{-\frac{3}{2}} \\
&= -\frac{m_0 v(t) \dot{v}(t)}{c^2} \left(1 - \frac{v(t)^2}{c^2}\right)^{-\frac{3}{2}} \tag{1}
\end{align}
$$
In Equation (1), using the fact that
$$
\left(1 - \frac{v(t)^2}{c^2}\right)^{-\frac{3}{2}} = \left(\frac{m(t)}{m_0}\right)^3,
$$
we find that
$$
\dot{m}(t) = -\frac{m_0v(t)\dot{v}(t)}{c^2}\left(\frac{m(t)}{m_0}\right)^3
$$
Simplifying further, we obtain that
$$
\dot{m}(t) m_0^2 c^2 = \dot{v}(t) v(t) m(t)^3
$$
Instead, in Equation (1), using the fact that
$$
\left(1 - \frac{v(t)^2}{c^2}\right)^{-\frac{1}{2}} = \left(\frac{m(t)}{m_0}\right),
$$
we can instead obtain that
$$
\begin{align}
\dot{m}(t) = - \frac{m_0v(t)\dot{v}(t)}{c^2}\left(1 - \frac{v(t)^2}{c^2}\right)^{-1}\left(\frac{m(t)}{m_0}\right)
\end{align}.
$$
Simplifying this then gives us
$$
\dot{m}(t)(c^2 - v(t)^2) = -v(t)\dot{v}(t)m(t)
$$
That is, putting everything to one side
$$
\dot{m}(t) c^2 + \dot{v}(t) v(t) m(t) - \dot{m}(t) v(t)^2 = 0,
$$
which is similar to what you require.
Answer: What your question had was a differential equation for energy in terms of two variables, $m$ and $v$. But we could write it in terms of one variable if we knew the Jacobian, which is a fancy word for the scale factor when you convert between $v$ and $m$ variables. This is similar to the manipulation you have seen before in implicit differentiation
$$x^2+y^2=r^2 \implies 2x + 2y\cdot \frac{dy}{dx} = 0$$
but this manipulation is different because it doesn't rely on a parametric variable (one variable inside both - in the above case $x = x(x)$ and $y = y(x)$). It's just like the manipulations you've see for $u$ substitution
$$u = \tan x \implies du = \sec^2x\:dx $$
$$\tan^{-1}u = x \implies \frac{du}{1+u^2} = dx$$
and so on. In physics we can always interpret the Jacobian as the ratio of the two changes i.e.
$$\frac{dx}{du} = \cos^2 x = \frac{1}{1+u^2}$$
What the manipulation does is answer the following question: if we have a little change in each of the variables, how does the little change in one relate to the little change in the other
$$f = f(x,y) \implies df = \frac{\partial f}{\partial x}dx + \frac{\partial f}{\partial y}dy$$
In this specific case, since we know $f(m,v)$ is a constant we have that
$$df = 0 = \frac{\partial f}{\partial m}dm + \frac{\partial f}{\partial v}dv \implies \frac{dv}{dm} = -\frac{\frac{\partial f}{\partial m}}{\frac{\partial f}{\partial v}}$$
which is actually a famous theorem called the implicit function theorem. With this Jacobian in hand, we are free to replace $dv$, the change in velocity, in the following equation with the related change in mass, $dm$ by
$$dv = \frac{dv}{dm}dm$$
or, the Jacobian (scale factor) times the change in mass.
Again, this doesn't require $m$ nor $v$ to be functions of a parametric time variable. This is important for relativity because time is not suitable to be a universal parametric variable. Both time and spatial coordinates are parametrized in terms of other variables, such as the arclength of a worldline (proper time) or just an arbitrary variable with no physical meaning.
Comment: @Istiak you don't have to know what a Jacobian is, I explained what it was in my answer - for the purposes of this problem it is a scale factor.
Comment: Is Jacobian Matrix of Partial Derivatives? I don't know what Jacobian actually is
Comment: I guess that the expression df=0 and all the other passages are after that are just intuitive right? df is a linear map on the tangent space and putting it equal to zero would require some comment. Also the ratio between two linear maps, dv/dm, can sound strange. Would it be possible to comment on these passages?
Comment: I am a physicist by training, but we are on math.stackexchange :D
Comment: @Thomas $0$ is a perfectly good linear map :) as for the other one you mentioned, I have already pointed to the implicit function theorem
Comment: Yes but df is what it is on the whole tangent vector space. I guess you would like to impose somehow that df applied to the vector tangent to the curve defined by a submanyfold is zero, but that is not for my understanding what is written when writing df=0,  a condition that is generally not true.  For the implicit theorem it is nice to give a reference, but your passages are only formal for my understanding and this is now not clear to the reader.


When Submitting Form, getting Null in JqueryAjax response

Question: I have created a form, that submits its data through Ajax. The form shows me success message but when i see Response it shows Null in 1 data field.
Post:
teacher_id    6
user_id    4
comment   MyCommentttttt

Response:
{"teacher_id":"6","user_id":"4","comment":null}

I have written the following code, it successfully send teacher_id & user_id but unable to send comment data. Kindly check the code and guide me what i am doing wrong here.
View -Jquery
var teacherId= $("input#teacher_id").val();
    var userId= $("input#user_id").val();
    var commentText =$("textarea#comments").val() ;

    jQuery.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>index.php/data_controller/user_comments",
            dataType: "json",
            data: {teacher_id:teacherId, user_id: userId, comment: commentText },
            success: function(){
                    alert("success");
                },
            error: function()   {
                alert("Fail");
                }

    });

Controller
public function user_comments()
    {
        $teacher_id= $this->input->post('teacher_id');
        $user_id= $this->input->post('user_id');
        $comments= $this->input->post('comments');

        $data= array(
                    'teacher_id'    =>  $teacher_id,
                    'user_id'       =>  $user_id,
                    'comment'       =>  $comments,
                    'Date'          =>  date('Y-m-d')
        );

    //  $this->load->model('comments');
    //  $this->comments->add_comments($data);

        echo json_encode($data);

    }

Answer: You send the parameter named comment, but in the server you're checking for comments. Change the below line:
$comments = $this->input->post('comment'); // < note the 's' is removed

Comment: I have spent more than 2 hours on this..How can be i so blind ! Thanks anyway :)


Firewall blocking mySQL port

Question: I am trying to connect to mysql through node.js program but it throwing an error.

I am not able to connect to mysql on port 3306.
I already have apache installed on my PC.

I have tried http://www.cyberciti.biz/tips/linux-iptables-18-allow-mysql-server-incoming-request.html
but still it is not working.
Error :
<code>Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)
    --------------------
    at Handshake.Sequence (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/protocol/sequences/Sequence.js:15:20)
    at new Handshake (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/protocol/sequences/Handshake.js:9:12)
    at Protocol.handshake (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/protocol/Protocol.js:42:50)
    at Connection.connect (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/Connection.js:72:18)
    at Connection._implyConnect (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/Connection.js:182:10)
    at Connection.query (/opt/lampp/htdocs/1nodeapp/node_modules/mysql/lib/Connection.js:97:8)
    at Server.<anonymous> (/opt/lampp/htdocs/1nodeapp/mysql.js:22:18)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2108:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
</code>
Comment: Can you add the error that you're getting?
Comment: @FreudianSlip : Error updated in above question.
Comment: Are you able to actually connect to mysql using the standard mysql client - if so, what's the output of : netstat -nlp | grep -i mysql
Comment: @FreudianSlip : When i have tried sudo netstat -nlp | grep -i mysql i am not getting any response.
Comment: If you're running that command on the machine where mysql is expected to be running, i'd suggest that at this stage, it's not actually started.  From the machine with mysql installed, run a : ps -ef | grep -i mysql
Comment: @FreudianSlip : Yes,i failed to start mysql on my PC.I have started it now and it is working fine.
Answer: To summarise the above:
1) try to connect using the standard mysql client
2) if that works, find out the port it's using

netstat -nlp | grep -i mysql

so that you can configure the appropriate firewall ports
3) if it didn't work, run

ps -ef | grep -i mysql | grep -v grep

to discover if mysql is actually running or not
4) if not (as was the case here) start it and repeat if connectivity still fails.
Comment: Issuing command `netstat -nlp | grep -i mysql` passig sudo, allowed me to see right port for mysql and configure firewall rules.

Firewall blocking mySQL port


For posting back on itself with query string

Question: I have
<form action="?#cgi.query_string#" method="post" ...

The cgi.query_string comes in with an indefinite number of variables. I tried using
<form action="?#EncodeForURL(cgi.query_string)#" method="post" ...

Should I be doing any kind of escaping?
Comment: I think this `action="?#cgi.query_string#"` is actually unnecessary; if you omit the `action` attribute then the page will submit to itself (including the query string). Not sure that actually answers your question.
Comment: It drops the `cgi.query_string` if I do that.
Comment: The `EncodeForURL()` function should be doing the escaping for you. What problem are you having with the code you shared?
Comment: if I use EncodeForURL(), the `&` and = are excaped. It become just a long string
Comment: But it still works, right?
Comment: No it doesn't work.
Comment: Ah okay, hence your question. I assumed the browser would interpret the encoded characters for you. Does it work if you add this `application/x-www-form-urlencoded` to your form? I realize that has to do with `form` data but I'm curious if it will also help in handling the encoded query string.
Answer: You are using method="POST" in your form tag. So you're trying to have a page with both a query string (URL scope) and a form body (FORM scope), correct?
I'm not sure that's best practice or even allowed by some browsers (I read elsewhere they'll strip query strings on POST actions).
The best solution might be to make the action either GET or POST, and loop through the query string making each item a hidden input?
<cfloop list="#CGI.query_string#" delimiters="&" index="i">
  <input
  type='hidden'
  name='#listFirst(i, "=")#'
  value='#listLast(i, "=")#'
  />
</cfloop>

As you say, you can't do this. Your specific question was whether you should do any escaping. The answer to that is "yes" and the location is going to be on the backend, parsing the query string.
<cfoutput>
  <form action='?#CGI.query_string#' method='POST' class='form-horizontal bordered-group' role='form' id='test'>
    <input
    class='form-control'
    type='text'
    name='formvar'
    />
    <input
    class="btn btn-primary btn-lg btn-block"
    type="submit"
    value="Submit"
    />
  </form>
</cfoutput>

Will submit a form to the same page, with the FORM scope present, the URL scope present, and the CGI.query_string defined. The CGI.query_string will have url formatting (%20 for space, etc). The FORM and URL scopes will already be decoded (%20 converted to space, etc).
It seems the crux of your question is really about security and sanitization. In which case you'll want to examine encodeForHTML() (Adobe Docs for encodeForHTML()).
Obviously, this isn't 100% foolproof, since I don't know the details of your code and what you do with the input. But those sanitization functions should be a good start.
So very generally, if you use the URL scope, use encodeForHTML(), and if you use #CGI.query_string#, it will be URL-encoded.
Comment: You should not be recommending `htmlEditFormat()` or `htmlCodeFormat()` any more. Those are the old methods for handling escaping.  Newer versions of ColdFusion come with the antiSamy libraries installed. The new `encodeFor...` methods should be used instead.
Comment: Nothing to do with the question, but if you plan to re-encode the params individually, watch out for empty params. listLast() gives the wrong answer in that case https://trycf.com/gist/782af2b6ff1b5f3ea9997ee8593cdca4/acf2016?theme=monokai
Comment: I am trying to both. ColdFusion will process url params and form at the same time. I inherited this code. If it were up to me, I would only do one way, but that is currently not an option.
Comment: My primary concern is if there there is a URL inject attack that is possible by no escaping `CGI.query_string`. If so, what do I do about it.
Comment: Ah, ok, you're talking security. I'll update my answer again to address that.


Problem with PNG image loading function not working, and showing a blank image

Question: I am uploading a file image. I compress it to a specified width and height, but it always shows a blank image when I attempt to display a PNG, but it WILL display jpg or jpeg files.
function compress($extention, $destination, $quality, $tmpsource)
{
    $extention = strtolower($extention);
    list($width, $height) = getimagesize($destination);
    $y = (800 * $height / $width);
    $getType = null;
    if ($extention == "jpeg") {
        $source = imagecreatefromjpeg($destination);
    }
    if ($extention == "jpg") {
        $source = imagecreatefromjpeg($destination);
    }
    if ($extention == "png") {
        $source = imagecreatefrompng($destination);
    }

    $thumb = imagecreatetruecolor(800, $y);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, 800, $y, $width, $height);

    if ($extention == "jpeg") {
        imagejpeg($thumb, $destination, $quality);
    }
    if ($extention == "jpg") {
        imagejpeg($thumb, $destination, $quality);
    }
    if ($extention == "png") {
        imagepng($thumb, $destination, $quality);
    }

    return $destination;
}

Here is where I call it:
if (in_array($imgTypeArr[$i], $allowedTypes))
{
    $newImgName = uniqid($newUniqName . "_") . "." . $getExt;
    $imgUploadArr[] = $newImgName;
    $destination = "../images/products/" . $proFolder . "/" . $newImgName;
    move_uploaded_file($imgTmpArr[$i], $destination);
    compress($getExt, $destination, 100);
}

Comment: the destination is the file from the folder im doing an override up there
Comment: You should include the code of the actual function that loads the png. Is it a custom function you created, or is it part of a third party source?
Comment: Why don't you use a library like this: http://image.intervention.io
Comment: Please include the code for the following functions: imagecreatefrompng() & imagepng. We need to see how they function, so we can determine if the creation process fails in those portions of code.
Comment: @JRFerrell See [imagecreatefrompng](https://www.php.net/manual/en/function.imagecreatefrompng.php).
Comment: i didnt get you about code for the following function: imagecreatefrompng
Comment: but im moving the file then after i do the compress
Comment: Oh, sorry. I see what you mean. And you said JPGs work fine?
Comment: yes jpeg and jpg works like charm the problem only with png show blank img like nothing
Comment: actually ive that problem on my live website so i decide to test on local the same problem do you c any probs in my code ?
Comment: It might be that [`imagepng`](https://www.php.net/manual/en/function.imagepng.php) expects a `quality` value between -1 and 9, and you're passing it 100.
Comment: yes thanks alot @showdev it fixes the problem but it loses its transparency and replaced with black any fix for that ?
Comment: It's possible that you'll need to enable the blending mode for PNGs with [`imagealphablending`](https://www.php.net/manual/en/function.imagealphablending.php) and/or save alpha channel information with [`imagesavealpha`](https://www.php.net/manual/en/function.imagesavealpha.php). See [PHP GD imagecreatefromstring discards transparency](https://stackoverflow.com/questions/12181573/php-gd-imagecreatefromstring-discards-transparency). If you run into trouble, you may want to post a new question.
Comment: works like charm thanks alot @showdev :)
Answer: imagepng expects a quality value between -1 and 9, but your code passes a value of 100:
compress($getExt, $destination, 100);

quality
  Compression level: from 0 (no compression) to 9. The default (-1) uses the zlib compression default. For more information see the » zlib manual.

You can leave off that value to use the default zlib compression for PNGs and the default IJG compression (about 75) for JPGs:
compress($getExt, $destination);

Or you may want to specify different quality values for JPGs and PNGs.


How to trigger a method to start at a certain?

Question: I need a piece of code to start whenever it it 11 AM everyday. I do not want to use windows task manager or any other external things to start my app.
I need my app to trigger my method whenever it is time, 11 AM.
I have the following questions:
1) Is there any "Time Listener" (similar to action listener) that would do that
2) Is it ok if my app is always runs without closing
Comment: Check out Quartz scheduler
Comment: `java.util.Timer` - You may want to consider what to do if your system restarts.  If you're using something like `Timer`, the CPU load is relatively low to nonexistent
Comment: Thank you @MadProgrammer .  I heard about java.util.Timer. I am curious is there any hidden threat while the app stays idle in between the tasks execution? My computer will get locked .. but never shut down
Comment: Spring integration with Quartz is a good thing too, makes it so easy, just annotate a method and that's it.
Comment: Well some memory usage of course, and that can be lots of memory usage if your application leaks.
Answer: As others have suggested, you can use the Timer class in java (java.util.Timer) or for finer control the Quartz library (that library uses the Unix cron style).
And yes it is ok if your app runs without closing. You can run it at the background but you might be better adding notification icon in the taskbar to ensure the user can find your app when they need to.
Comment: if you're going to leave your app running in the background to make sure you don't have any memory leaks or you could run into trouble
Comment: if we are using timers, if you have some sort of outage window, schedule a service restart.


C# Reading newest file in directory

Question: I't trying to get my program to read the most recent file in a directory with a few similar files and retrieve a name but its still reading all the files. If anyone knows why I'd appreciate the help :)
EDIT: Undo
here's my code:
public GetMyNames()
{
    DirectoryInfo fileDirectory = new DirectoryInfo(@"C:\user\mark\folder");
    List<string> files = new List<string>();

    int creationDate = 0;
    string CreationDate = "";

    foreach (FileInfo fileInfo in fileDirectory.GetFiles("*.txt"))
    {
        string creationTime = fileInfo.CreationTime.ToString();
        string[] bits = creationTime.Split('/', ':', ' ');
        string i = bits[0] + bits[1] + bits[2];
        int e = Int32.Parse(i);
        if (e > creationDate)
        {
            creationDate = e;

            files.Add(fileInfo.Name);
        }
    }

    foreach(string file in files)
    {
        string filePath = fileDirectory + file;
        string lines = ReadAllLines(filePath);

        foreach (string line in Lines)
        {
            Name = Array.Find(dexLines,
        element => element.StartsWith("Name", StringComparison.Ordinal));
        }

        MyName = Name[0];
    }

Comment: it's use 0 for the minimum creation date. EVERY FILE YOU HAVE will match that.
Comment: If you want the last written file, why don't you sort by the write date and pick the one that sorts to the top of the pile?
Comment: If you're only interested in one file, then why are you storing and iterating over a collection of them in the second loop in your method?
Comment: I tried to dumb down my code for the question but I broke it
Comment: Try taking a look [here](https://stackoverflow.com/q/1179970/3775798) for some ideas.
Comment: @Christopher My directory has multiple files each with a unique identifier in the name but there's multiple files with the same identifiers, im trying to get the newest file for each of them, any idea's?
Answer: Note that OrderBy runs at an order of O(nlog(n)) as it sorts the enumerable.
I suggest using Linq Max extension method, that is:
newestFile = files.Max(x => x.CreationDate);

this is more efficient (runs at an order of O(n)) and is more readable in my opinion
Answer: Why not use Linq and order by the date?
files.OrderBy(x => x.CreationDate)

C# Reading newest file in directory


can you use mods on scalacube?

Question: I want to play on a server with me and my friend.
Can you use mods on ScalaCube
Answer: Yes, depending on what you choose on the hosting site you provided (ScalaCube).
According to the hosting site, it provides Modpack Support. It also provides instant server setups for 230 modpacks.

can you use mods on scalacube?


$\lim_n (\int\frac{e^{-nx}}{\sqrt{x}}d\mu)_{n\in\mathbb{N}}$

Question: Let $(0,\infty)$ measure space with borelians in $(0,\infty)$ and $\mu$ Lebesgue's measure.
Show that $(\int\frac{e^{-nx}}{\sqrt{x}}d\mu)_{n\in\mathbb{N}}$ converges and find the limit.
Why converges?
Answer: For $x \in (0, \infty)$, we have
$e^{-nx} \le \frac{1}{e^{x}} < \frac{1}{1+x+\frac{1}{2}x^2}<\frac{1}{1+x}$
Let $f_n(x)=\frac{e^{-nx}}{\sqrt{x}}$, let $g(x)=\frac{1}{\sqrt{x}(1+x)}$.
$f_n$ are measurable, $f_n(x) \rightarrow f(x) = 0$ for each $x \in (0, \infty)$. And we could check that $g$ is integrable ($2\arctan(\sqrt{x})\bigg |_0^{\infty}=\pi$). Plus we have $|f_n(x)| \le g(x)$. By Dominated Convergence Theorem, we know that:
$$\lim_{n \rightarrow \infty} \int f_n d\mu = \int f d\mu = 0$$
Answer: This can be done using the dominated convergence theorem, for example using $e^{-nx} \leq e^{-x} \leq 1 + e^{-x}$. So for example ${1 + e^{-x} \over \sqrt{x}}$ is a dominating function.
Another approach is to change variables to $y = nx$. Then you are looking at
$\lim_{n \rightarrow \infty} {1 \over \sqrt{n}} \int_0^{\infty} {e^{-y} \over \sqrt{y}}\,dy = 0$.


Simple simple Euler Lagrange Equation

Question: Just starting a course on Lagrangian Mechanics and I'm just wondering what about the Euler-Lagrange equation, and more specifically what I'm meant to be trying to do ..
One of the questions from my textbook reads :
Solve the Euler-Lagrange equation for the following function
\begin{align*}
f(y,y') = y^2+y'^2
\end{align*}
Looks simple enough... But where should I be headed to start?
The Euler-Lagrange Equation as we have it is
\begin{align*}
\frac{\partial f}{\partial y} = \frac{d}{dx} \frac{\partial f}{\partial y'}
\end{align*}
Do I just find the partial derivatives of f treating y and y' as independent variables as follows:
$$\frac{\partial f}{\partial y} = 2y,$$
$$\frac{\partial f}{\partial y'} = 2y$$
so then we have :
$$2y = \frac{d}{dx}(2y')$$
$$y = \frac{d}{dx}(y')$$
$$yx+c = y'$$
$$\frac{yx^2}{2}+cx+d = y$$
And then simplify with the y isolated on the right so it looks nice .. or at least thats what I thought..
Any comments ? right track, wrong track?
Also, what is this euler equation actually solving for? Is it just a nice way of solving differential equations in this form ?
When we did this in class, we did a monster proof showing it minimizes the path between 2 points or finds the extrema for the function $I(x) = \int^a_b \ F(y(x),y'(x),x) dx,$ which is all great but I'm not too sure how this relates to the equation we solve in the question .. Thanks for all
Comment: How did you go from $y=\frac{d}{dx}y\,'$ to $yx+c=y\,'$? Did you perhaps do $\int ydx=yx+c$ (which is incorrect)?
Comment: you seem to be 'losing' derivatives. $\frac{d}{dx} y' = y^{''}$. At least if $y=y(x)$. Then $y=y^{''}$ is the ODE you have to solve. Also,  $\frac{df}{dy'} = 2 y'$, but that you fixed later on somehow, so it was possibly only a typo.
Comment: $y$ and $y'$ are not independent of $x$, so you cannot solve $y = \frac{d}{dx}y'$ this way.
Comment: Though you *are* correct that we keep $y$ and $y\,'$ independent when we take *partial* derivatives.
Comment: ok, so the problem line seems to be $y = \frac{d}{dx}(y')$ .. from here I should've gone to $y = y''$ which is easy enough to solve.. The reason I can't just integrate both sides with respect to $x$ is because the $y$ on the LHS is dependent of $x$ .. Can somebody confirm these thoughts for me ? thanks thanks
Answer: The function $f(y,y') = {y'}^2+y^2$ can be interpreted as a Lagrangian $L = T-V$, where $T={y'}^2$ is the kinetic energy and $V = -y^2$ the potential energy of some object.${}^\dagger$
Among other things, this is the Lagrangian of pencil that is balanced vertically on its tip.
$y$ is then interpreted as the angle the pencil makes with the vertical, and must be assumed to be small.
$x$ should be interpreted as time.
We expect at least one unstable solution since the pencil can fall over.
The action is extremized by solutions to the Euler-Lagrange equation.
The equations of motion found by the principle of least action are equivalent to Newton's laws of motion---we are going to find out how the pencil drops.
First, note that
$$\begin{eqnarray*}
\frac{d}{dx} \frac{\partial f}{\partial y'}
&=& \frac{d}{dx} 2 y' \\
&=& 2y'' \\
\frac{\partial f}{\partial y}
&=& 2 y.
\end{eqnarray*}$$
The Euler-Lagrange equation gives
$$y'' = y.$$
The solutions are
$$y(x) = A e^x + B e^{-x},$$
where $A$ and $B$ are some constants determined by the initial conditions.
For example, if $y(0)=0$ and $y'(0)=1$ we find
$$y(x) = \sinh x.$$
This solution is indeed unstable, the angle increases without bound.
Of course, this can only be taken seriously for small $y$.
The principal advantage of finding equations of motion in this way is it allows the simple use of generalized coordinates.
With practice it becomes automatic to write the total kinetic and potential energy of a system in terms of some convenient coordinates and to find the equations of motion via the Euler-Lagrange equations, which have the same form for any system of generalized coordinates.
As a cultural side note, be aware that variational methods extend far beyond their application to the Lagrangian formulation of classical mechanics.

${}^\dagger$The force corresponding to this potential is $F = -\frac{d}{dy}V = 2y$. This is Hooke's law with the wrong sign.
What happens if $f(y,y') = {y'}^2 - y^2$?
Comment: Thank you so much ! I have a hopeless lecturer (who is indeed very smart but who can't seem to teach and is very impatient) so I am badly in need of a better approach... I may be putting down a lot of questions in the next few months :/
Comment: So in the final y(x)=sinhx , does the x then represent time (oh wait, you told me that)..

as for the †, would $f(y, y')=y'^2 - y^2$ then be the Lagrangian of a spring ?
Comment: @Ronald: Glad to help. Yes, if you flip the sign you can also think of it as the Lagrangian of a pendulum for small oscillations. You'll get simple harmonic motion.

Simple simple Euler Lagrange Equation


@Valid(javax.validation.Valid) annotation did not work when maven project is packaged in WAR

Question: I'm using @Valid annotation to validate the incoming request body and it is working fine when I'm packing the code in jar. But when I change the packaging from jar to war, @Valid annotation does not work for request body.
Below is my pom.xml file:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.db</groupId>
    <artifactId>bff-global-payment-simulator</artifactId>
    <packaging>war</packaging>
    <name>bff-global-payment-simulator</name>
    <version>1.0.0</version>
    <properties>
        <java.version>1.7</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <springfox-version>2.5.0</springfox-version>
        <spring-boot.version>1.4.1.RELEASE</spring-boot.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>

            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <id>central</id>
            <url>https://artifactory.intranet.db.com/artifactory/mvn-public-local/</url>
            <name>mvn-public-local</name>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <url>https://artifactory.intranet.db.com/artifactory/mvn-snapshot-local/</url>
            <name>mvn-snapshot-local</name>
        </snapshotRepository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>

        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.apple</groupId>
            <artifactId>AppleJavaExtensions</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
</project>

Below is my Java file:
public ResponseEntity<POSTResponseForGlobalPaymentRequestForDomesticPayments> createSingleImmediatePayment(
            @Valid @RequestBody GlobalPaymentPOSTRequestForDomesticPayments body,
            @Valid @RequestHeader MultiValueMap<String, String> headers)
            throws UserDefinedFailure, URISyntaxException, ParseException, IOException {
            ....
            }

Not able to figure out , why this is happening.
Comment: Is that file Controller layer? Try adding `@Validated` at class level
Comment: Which tomcat version are you deploying to and how have you implemented your `SpringBootServletInitializer`? Also instead of including `javax.validation` use `spring-boot-starter-validation` instead.
Comment: MaruthiAdithya : yeah this is at Controller layer and tried with @Validated as well..but it didn't work when i packaged in war
Comment: have already implemented SpringBootServletInitializer and tried spring-boot-starter-validation as per suggestion..still didnot work :(  @M.Deinum
Comment: Apache Tomcat/8.5.34  is the version where i'm deploying. @M.Deinum
Comment: Please add your configuration. You don't have a `web.xml` by accident do you? Also your validation dependency shouldn't be provided. As suggested remove that dependency and replace with `spring-boot-starter-validation` (to get both the API and an implementation) and don't make it provided, just use the regular scope.
Comment: I have removed 'provided' from scope of javax.validation dependency and it worked fine in both the packaging(war and jar).. And when I removed the dependency from pom.xml for javax.validation then also it worked as this jar is getting downloaded from spring-boot-starter-web. And spring-boot-starter-web is already there as a dependency in my firstname.lastname@example.com
Answer: I removed javax.validation dependency from the pom.xml as it comes with spring-boot-starter-web. No need the explicitly define..So the problem was with scope "provided" which I had mentioned in my javax.validation dependency explicitly.
Answer: There is a spring dependency
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

It works for me.


Oracle Virtual Box failing to open

Question: I was trying to run Oracle Virtualbox Manager but it is not working. I am getting the following error message:
Failed to open a session for the virtual machine Oracle DB Developer VM.

The virtual machine 'Oracle DB Developer VM' has terminated unexpectedly during startup with exit code 1 (0x1).  More details may be available in 'C:\Users\Ornob\VirtualBox VMs\Oracle DB Developer VM\Logs\VBoxHardening.log'.

Result Code: E_FAIL (0x80004005)
Component: MachineWrap
Interface: IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}

How do I fix this issue ?
Comment: `More details may be available in 'C:\Users\Ornob\VirtualBox VMs\Oracle DB Developer VM\Logs\VBoxHardening.log'`....
Comment: Now I'm dying to know what it says in that logfile.
Answer: I started virtual box in administrator mode, now it's able to start my VM
Comment: I faced this error (0x80004005; MachineWrap) after upgraded my PC with additional DRAM module. Thanks to this advice I was able to start VM using Administrator mode. After one successful launch I was able to start VM normally (without Administrator mode).
Answer: The error message indicates that the image is inaccessible, this may be due to several reasons but in most cases, the image has been moved to another directory by making a cut paste from the Windows Explorer.

go to the "Machine Manager" and click on "File".
Click on "Media Manager".
In the first tab called "Hard Drives", click on the image that is unreachable  then click on the "Release" button to remove the disk link (UUID) to the VM.
Now click the "Delete" button to remove the disk from the "Virtual Media Manager".
Now all you have to do is add your image from the storage section and start on your virtual machine.
Comment: Where can I find the "Machine Manager" ?
Comment: CTRL+D on Virtual Box
Answer: FWIW mine was a permission problem (ubuntu box).  Looked in /var/log/syslogs and found :
Mar 23 14:54:54 xxxx update-notifier.desktop[2988]: ERROR: AssertionError("cannot parse ProcMaps line: Error: [Errno 13] Permission denied: 'maps'"
...
    dlopen("/usr/lib/virtualbox/VBoxRT.so",) failed:

Have a look at permissions in /usr, /usr/lib, /usr/lib/virtualbox
These should all be owned by root.root, in my case /usr/lib was owned by another user.
Answer:
Navigate to C:\Program Files\Oracle\VirtualBox\drivers\vboxdrv
Right click on VBoxDrv.inf file and select Install option
Restart VBox as administrator

Oracle Virtual Box failing to open


Git bash acting weird in intellij-idea

Question: managed to put GIT bash to intellij idea. it starts well from IDE but not recognizing any git bash commands as well as java commands.
throws "bash: java: command not found"
git bash works perfectly when lunched not from IDE. weird part that they both have the same path to the same .exe file.
Comment: The terminal run inside your IDE seems to miss the directory to `your_java_installation/bin` from its `PATH` variable. That's why you get `bash: java: command not found`.
Comment: Could you please check what path do you have under Preferences | Version Control | Git
What output would you get if you run "Test" next to a path to Git executables?
Comment: C:\Program Files\Git\bin\git.exe
when I run "Test" it says: "Git version is 2.30.1"
Answer: Git is automatically managed by the IntelliJ idea which does not require any additional commands. All happens via button click.
Git basic operations:

Now if you don't have these options. Then go to VCS > Enable version control integration and select git. Then these options will come on toolbar.
Comment: Got these options but it didn`t solve the problem. Still not recognizing neither git or java commands.

Git bash acting weird in intellij-idea


Timezone issues when running my django app on Heroku

Question: I'm creating a scheduling app with Django. As per most recommendations on the topic, the appointments (in my Appointments model) are stored in UTC timezone format. So my settings.py are set to TIME_ZONE = 'UTC'.The app was working perfectly on my local server, but when I deployed it to Heroku, i started having issues.
To give you an example (in production):
>>> heroku run bash
>>> python manage.py shell
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2020, 3, 10, 17, 10, 10, 453536)

Yet, on local, I get:
datetime.datetime(2020, 3, 10, 13, 10, 10, 196794)

I tried to solve the issue (ie, 4-hour difference) by changing the TZ config value of the app to my local time, like so:
heroku config:add TZ='America/Toronto'
No luck. Anyone understands why this is happening? Any suggestions on how to solve this?
Comment: `heroku config:add TZ="America/Toronto"`?
Comment: Is that incorrect? I'm using the TZ database names provided here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Comment: Choose your closest TZ with your city
Comment: Which is Toronto... I don't understand what your comment is about...
Answer: Use:
datetime.datetime.utcnow()

or, based on documentation best practices:
datetime.datetime.now(timezone.utc)

datetime.datetime(2020, 3, 11, 19, 33, 32, 335610)
>>> datetime.datetime.utcnow()
datetime.datetime(2020, 3, 11, 18, 33, 37, 582409)
>>>

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 3, 11, 18, 32, 56, 146774, tzinfo=datetime.timezone.utc)

Comment: `timezone.now()` is the best practice, I'm using the same in all my apps. There is no issue with that until now.
Comment: That doesn't seem to work. I get the same time with or without .utcnow()
Comment: @MaximVallee it works perfectly fine. Just look at my updated answer.
Comment: @ Sam I think you're misunderstanding my problem. The solution you suggested returns the Heroku server's time, which is not the same as my local time.
Answer: Try this;
import pytz
from datetime import datetime

tz = pytz.timezone('America/Toronto')
print(datetime.now(tz))

This will print the current datetime as per your timezone (America/Toronto)


Expected update behavior on re-saving while using MongoDB's official C# driver

Question: Trying to understand the expected behavior on re-saving a existing document (from a 3+ level object graph) that was previously saved.  Is an update applied to only the top level fields or does it attempt to traverse for nested objects changes?
var models = _database.GetCollection<Model>("Models");
var model = models.FindOneAs<Model>(Query.EQ("_id", new ObjectId("4df7bce0dc1c792230912fda")));

// Apply various changes on multi-level object graph...

models.Save(model);

When trying the above, nested changes were not being applied to db.
Comment: Can you post full code, with document class and update part? I want try with you.
Answer: I've builded test for your problem:
Here is document that i saved into mongodb (with 3 level array deep):
{
  "_id": "4dfa48d1872b4a1a50f60033",
  "NestedLevels": [
    {
      "Name": "Nested1",
      "NestedLevels": [
        {
          "Name": "Nested2",
          "NestedLevels": [
            {
              "Name": "Nested3",
              "NestedLevels": []
            }
          ]
        }
      ]
    }
  ]

}
I am loading it from c#, updating Name=Nested3 with another value and saving back, after that i am reading from mongodb updated document and it updated actually.  So i guess problem in some other part of you code.
BTW: If you need i can post here complete test in c#.
Update:
Test case:
    [TestMethod]
    public void MongodbTest()
    {
        var mongoServer = MongoServer.Create("mongodb://localhost:27020");
        var database = mongoServer.GetDatabase("StackoverflowExamples");
        var levels = database.GetCollection("levels");
        var level1 = new Level1();

        var nested1 = new LevelX() { Name = "Nested1" };
        var nested2 = new LevelX() { Name = "Nested2" };
        nested1.NestedLevels.Add(nested2);
        var nested3 = new LevelX() { Name = "Nested3" };
        nested2.NestedLevels.Add(nested3);

        level1.NestedLevels.Add(nested1);

        levels.Insert(level1);

        var item = levels.FindOneAs<Level1>();

        item.NestedLevels[0].NestedLevels[0].NestedLevels[0].Name =
                                         "Changed nested level 3 name";

        levels.Save(item);

        var itemAfterUpdate = levels.FindOneAs<Level1>();

        Assert.AreEqual("Changed nested level 3 name",
            itemAfterUpdate.NestedLevels[0].NestedLevels[0].NestedLevels[0].Name);

        levels.RemoveAll();
    }

Documents classes:
public class Level1
    {
        public Level1()
        {
            Id = ObjectId.GenerateNewId();
            NestedLevels = new List<LevelX>();
        }

        [BsonId]
        public Object Id { get; set; }

        public List<LevelX> NestedLevels { get; set; }
    }

    public class LevelX
    {
        public LevelX()
        {
            NestedLevels = new List<LevelX>();
        }

        public string Name { get; set; }

        public List<LevelX> NestedLevels { get; set; }
    }

Comment: I must be doing something wrong.  Posting your test code would help identifying where i went wrong.  Thx!


Are there abandoned ships in X3: Albion Prelude?

Question: Has anyone found any abandoned ships in Albion Prelude.
Perhaps they are the same as Terran Confict?
I would like to know if there are abandoned ships that I can claim to kickstart a little money.
Thanks
Comment: If you go to the Stock Exchange in Nyanas Hideout you will make millions in minutes.
Buy shares at index 100 from buyer perspective and sell when they get low.
Answer: From what I gather (i.e. digging around on egosoft forums and exploring the game), abandoned ships in the galaxy are now randomized, so they're no longer in a predetermined position.
If you are having trouble with money, make your way to the Omicron Lyrae area (I hung around in Circle of Labor a lot, which is just north of OL) and start looting the various missiles that gets dropped during the battles between Terrans and Argons.  You can easily make 1 mill in half an hour.
Just make sure you don't wander into a stray PSP or you'll be instantly vaporized.
Comment: Also, If you play Terran Commandet, finding Aldrin and the Aldrin shipyard, then swapping your Katana for the Springblossom lets you complete the harder freight- and passenger (if you buy life support) missions. That'll give you millions in a matter of hours.
Comment: By far, the easiest and fastest way to make money in AP so far is to do stocks.  Just an hour of buying and selling naturals got me the 25 million to complete the poisoned paranid start.  Now I'm rocking along in my overtuned hyperion barely 8 game hours in.  The only hard part was actually getting to a stock exchange in the slow ass freighter you start out with.
Answer: I have found 1 corvette in unknown sector, next to Xenon sector 534.
Stats:

39% damaged
no shield
10 kyon beta
2 thorn missiles

Coordinates: 1.48 km X / -24.1 km Y / -855 Z
I found it while mining for nividium.
It was 25 km below the nividium 5 rock.
Comment: In my game, the corvette was at the second to last Unknown Sector when searching for it by name, at 72k,~0,~0. This is almost certainly random for every new game one starts.
Comment: I also located the above ship in the above location.


How can I access the location of Shalidor's writings in Wolfskull Cave?

Question: I've researched bugs on this quest and have not resolved the inability to access the location of Shalidor's writings when directed to Wolfskull Cave.  I had completed the "The Man Who Cried Wolf" quest before I began the Shalidor's Writings quest, although I do not recall which of the two quests I received first.
Does the order I received the quests matter?  More importantly, is there a way to fix this quest so I can retrieve the writings and complete the quest?
If it helps, I'm playing the PC version.
Comment: You haven't told us what your problem is.
Comment: I am not able to access the location of Shalidor's writings in Wolfskull Cave.  The pointer points to a location on the floor that sits outside of the map - there is no pathway to the location.  everything I've researched says it has to do with not completing the Man Who Cried Wolf quest, but I completed that quest long before I even began the Shalidor's Writing/Insights quest given by the librarian from the Arcaneum. My problem is I want to know if Shalidor's Writings quest can be fixed and completed, or if I'm just going to have to let it sit there incomplete the rest of the game?
Answer: If you're on PC, try this command setstage MGR21 20, the game should act like you have collected the item. If you're not on PC, there isn't anything you can do, but at least this quest isn't very important.
Comment: Thank you very much Kotekzot.  Now for the million dollar stupid question.  Where and how do I enter that command - and yes, I'm playing on the PC :)?
Comment: Hit the grave/tilde key (`/~), it should be under Escape and left of 1.


Can we decide pod failure based on one or 2 containers failure?

Question: If I have containers A and B in a pod.. Can i define the failure condition in a pod?? Let's say if container B is not up and running or if its status is exited then spin up another pod with the same set of containers ? An example of configuration file if any ?
Comment: Can you split the containers into separate pods?  This is usually better practice and avoids some ambiguities like this.
Answer: A PodSpec has a restartPolicy field with possible values Always, OnFailure, and Never.If a container fails, it is restarted according to its restart policy. Other containers in the same Pod aren't affected. So it does not create a completely new pod if one of the containers fails.
The problem if you use pod is that it's not restarted into another node. For that you should use a higher level controller such as deployment.
Additionally you should define readiness and liveness probe for each container. So kubernetes will remove that container PORT from services if the probe fails.
So with all these you really don't need to worry about creating a new pod if one of the container fails.


Weighted bipartite matching

Question: I'm aware of there's a lot of similar topics. But most of them left me some doubts in my case. What I want to do is find perfect matching (or as close to perfect as possible in case there's no perfect matching of course) and then from all of those matchings where you are able to match k out of n vertexes (where k is highest possible), I want to choose the highest possible total weight.
So simply put what I'm saying is following priority:

Match as many vertexes as possible
Because (non weighted) maximum matching in most cases is unambiguous, I want choose the one that have the biggest sum of weights on edges. If there are several of them with same weight it doesn't matter which would be chosen.

I've heard about Ford-Fulkerson algorithm. Is it working in the way I describe it or I need other algorithm?
Answer: If you're implementing this yourself, you probably want to use the Hungarian algorithm.  Faster algorithms exist but aren't as easy to understand or implement.
Ford-Fulkerson is a maximum flow algorithm; you can use it easily to solve unweighted matching.  Turning it into a weighted matcing algorithm requires an additional trick; with that trick, you wind up with the Hungarian algorithm.
You can also use a min-cost flow algorithm to do weighted bipartite matching, but it might not work quite as well.  There's also the network simplex method, but it seems to be mostly of historical interest.
Comment: In fact it's to my final study diploma (idk exactly international equivalent of degree) about assigment problem, so i will give a try to understand ford-fulkerson. Problem is that i'm not sure if it's work in the way I desire. for instance take following case:  := <1,3,1> <2,4,1> <1,4,infinity> doesn't max-flow means that edge <1,4,inf> would be taken and in the same way took maximum possible weight instead of first finding maximum vertex set and as second condition sum of edge weights?
Comment: That isn't really how you'd use flow to solve this.  You want unit capacities.  If you want a direct formulation, you use a minimum-cost flow model, keep the unit capacities, and let the costs be, um, the costs.  This isn't a maximum-flow problem, but there's a trick (the primal-dual method) that lets you use maximum flow as a subroutine.

Weighted bipartite matching


Ubuntu fan noise while watching videos

Question: While watching videos on either YouTube or anywhere else, on Ubuntu 22.04 creates high CPU utilization and fan noise. What's the reason? Is this okay and how do I avoid it?
My Windows dual booted with Ubuntu, never faced such thing on Windows.
GRAPHICS : NVIDIA CORPORATION GK208B[GeForce GT 730]

Normally the sensors used to be around 40 to 45 deg C.
Good to mention: When I first downloaded Ubuntu I accidentally downloaded xorg when nvidia driver was installed. Then uninstalled xorg and auto/reinstalled nvidia (if that created some problem).
not able to install psensor:

result when doing this way sudo apt-add-repository ppa:jfi/ppa:
Comment: Disable CPU onboard graphics in the BIOS if you have any. It's called Intel UHD for Intel and I think AMD Radeon for AMD. Then run `lspci -v`. For your graphics card it must say `Kernel driver in use: nvidia`.
Comment: Is this a laptop, desktop or what? When last did you dust it out? Possibly the thermal paste has degraded.
Comment: Have you done `sudo dpkg --add-architecture i386` ?
Answer: The high CPU load of 90% is misleading. It is really 90% divided by the number of virtual CPU cores. In your case, 12 CPUs, it would be 7.5% CPU load.
You are using Google Chrome for YouTube videos and I found that makes my fans kick in as well. If I use Firefox to watch YouTube videos, then the fans stay off, or at least spin so slow, I can't hear them.
Comment: yep! it works fine in firefox , what's the reason it doesn't in chrome
Comment: @NarendraPal Chrome tends to have more "bleeding-edge" features. I imagine this comes with a penalty of more system overhead. You can try turning off new features / experimental features in Chrome. I use Firefiox all the time and only use Chrome for background testing so it's not important enough to investigate Chrome.
Comment: chrome only use 90% CPU when using you tube otherwise it's not .In firefox using youtube does not causes fan noise but it uses around 40-50 % CPU utilization when using you tube is that okay?
Comment: @NarendraPal Sounds about right. Mine is using 7% on 8 virtual cores which is 56% CPU in your language. You have 12 virtual cores so it's 50% / 12 = 5% CPU usage in my language which sounds correct because my CPU is older i-7.

Ubuntu fan noise while watching videos


Extra wires and jacks on my chandelier - where do they go?

Question: Can someone help me understand why my chandelier has a positive, negative and ground wire, then something I've never seen: 2 sets of blue and white wires and 2 jack holes inside connection pad? I'm assuming they go inside the jacks for over heating but I'm not an electrician.
Thanks in advance,
Francesco
Comment: if it's a 2-bulb chandelier (or a 2 cluster) then there is a set of wires to each bulb (cluster)
Comment: We need another view of the fixture.  As posted it's not possible to know if there's one bulb or twenty.
Comment: Hello, and welcome to Stack Exchange. Where did this fixture come from? Did it come with instructions?
Answer: The black, white and green/bare are for you to connect.
The blue/white are internal to the appliance to route the current to the various place it is needed (each bulb). It's got nothing to do with over-heating.
Answer: That Eurofase F-20KAS2-05 fixture uses low-voltage halogen light bulbs.
This means that somewhere hidden in that big cover is a power supply - that's where the blue wires go.
The blue wires are connected to the white wires (which run down the shaft to the light bulbs) with those white crimped-on caps. These are not intended to be fiddled with by the user/installer - they're permanent & non-removable.
The only wires you need to concern yourself with are the black/white/ground wires which supply power to the hidden low-voltage power supply - black to hot, white to neutral, ground to ground.


Why do you have to open doors in Cod Zombies?

Question: Why do you have to open doors in Zombies? Can't you just stay in the room you spawn in?
Comment: I haven't played CoD in ages but if I'm not mistaken you just lose access to more weapons (that will help on later stages) and less points overall
Answer: The waves of zombies become progressively harder to deal with, and the weapons you have access to in the initial areas just aren't up to the task.  Opening new areas unlocks new weapons and other bonuses, which are basically essential to surviving later rounds.


XPAGES: Link name using getelementbyid

Question: How can I get the label of the link that is clicked by the user?
I have tried:
var elem=document.getElementById("#{id:link1}");var lbl=elem.label;

But this is not returning the label name.
Answer: The "label" property of a Link control is called text so the following server-side Javascript will get you the value of the label of the link and store the value in the variable "label":
var linkControl = getComponent("linkExample");
var label = linkControl.getText();

Comment: As a follow on from this. This is a common piece of code. I would recommend getting the XPages cheat sheet from http://xpagescheatsheet.com/ .
Comment: thanks.It worked on SSJS.
I was able to do on client JS as follows. var id = "#{id:link1}";
alert(dojo.byId(id).text);
Answer: In Xpages [xp:label] tags turn into [span] tags so on csjs you have to use the innerHTML to get the value so your original code would have worked had it been.

var elem=document.getElementById("#{id:link1}");
var lbl=elem.innerHTML;

XPAGES: Link name using getelementbyid


Simulation doesn't run for the determined 10 seconds

Question: This simulation is set to work for 10 seconds but stops at 4.5 when the FTP is supposed to start sending packets. would you please help me fix it?
I have been working with NS2 for 3 hours. I am a hell of a noob right now.
<code>#Creating a simulator object
set ns [new Simulator]
global $ns
set traceFile [open output.tr w]
$ns trace-all $traceFile
set namFile [open output.nam w]
$ns namtrace-all $namFile

#Defining the finish procedure
proc finish {} {
  global ns namFile traceFile fert
  $ns flush-trace

  close $namFile
  close $traceFile

  exec nam output.nam &
  exit 0
}

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
#for {set i 0} {$i<5} {incr i} {
#set n($i) [$ns node]
#}

#Creating the links
$ns duplex-link $n0 $n1 1Mb 20ms DropTail
$ns duplex-link $n0 $n2 1Mb 20ms DropTail
$ns duplex-link $n1 $n3 1Mb 20ms DropTail
$ns duplex-link $n2 $n3 1Mb 20ms DropTail
$ns duplex-link $n2 $n4 1Mb 20ms DropTail
$ns duplex-link $n2 $n6 1Mb 20ms DropTail
$ns duplex-link $n4 $n6 1Mb 20ms DropTail
$ns duplex-link $n4 $n5 1Mb 20ms DropTail

#Topology
$ns duplex-link-op $n0 $n1 orient down
$ns duplex-link-op $n0 $n2 orient right
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n2 $n3 orient down
$ns duplex-link-op $n2 $n4 orient right
$ns duplex-link-op $n2 $n6 orient right-down
$ns duplex-link-op $n4 $n5 orient right-down
$ns duplex-link-op $n4 $n6 orient down

#Agents - Attach Agents - SInk and Null connetions
set udp0 [new Agent/UDP]
set tcp3 [new Agent/TCP]
set null4 [new Agent/Null]
set sink5 [new Agent/TCPSink]
$ns attach-agent $n0 $udp0
$ns attach-agent $n3 $tcp3
$ns attach-agent $n4 $null4
$ns connect $udp0 $null4
$ns connect $tcp3 $sink5

#CBR over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set type_ CBR
$cbr0 set packet_size_ 1500
$cbr0 set rate_ 830kb

#FTP over TCP connection
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3
$ftp3 set type_ FTP

#Queue Limit of n2-n4 and n4-n5
$ns queue-limit $n2 $n4 30
$ns queue-limit $n4 $n5 20

#Assigning a link variable for the link between n4 and n5

#Monitoring
set mon [open "mon.txt" w]
set qmon [$ns monitor-queue $n2 $n4 $mon 0.01]
[$ns link $n2 $n4] queue-sample-timeout
#set qmon24 [$ns monitor-queue $n2 $n4 "" 0.01]

#............................................
    set link01 [$ns link $n2 $n3]
# Create monitor
    set fmonitor [$ns makeflowmon Fid]
    $ns attach-fmon $link01 $fmonitor
        set drop_count [$fmonitor set parrivals_]

#............................................
proc mon { } {
global ns qmon
set t [$ns now]
puts "$t [$qmon set pkts_]"

$ns at [expr $t + 0.5] "mon"
}

#Link Down and Up at 5.0 and 7.0

        $ns rtmodel-at 5.0 down $n2 $n4
        $ns rtmodel-at 7.0 up $n2 $n4

#$ns rtproto LS

$ns at 0 "mon"

$ns color cbr "red"

$ns at 2.0 "$cbr0 start"
$ns at 4.5 "$ftp3 start"
$ns at 8.0 "$cbr0 stop"
$ns at 9.0 "$ftp3 stop"

$ns at 10.0 "finish"

$ns run
</code>
And another question. What is a link queue? I gotta monitor the queue of a link between two nodes for my project but I don't understand the concept of a link queue! oh and one more thing. The Nam doesn't start automatically and I get this:
Classfier::no-slot{} default handler (tcl/lib/ns-lib.tcl) ---
    _o21: no target for slot 4294967295
    _o21 type: Classifier/Hash/Dest
content dump:
classifier _o21
    0 offset
    0 shift
    1073741823 mask
    1 slots
        slot 3: _o196 (Classifier/Port)
    -1 default
Comment: Links INFO: ns2 documentation https://www.isi.edu/nsnam/ns/doc/index.html ... I can make a version of your file to get a result https://www.dropbox.com/s/4nql1eljfekk7xm/Aramesh-ns2.tcl?dl=0 ... But nam fails: `class Animator: constructor failed: class NetworkModel: constructor failed: error when calling class NetworkModel: link 1 0 1.0 20.0 0 0.5` ... ( output.nam = 159kB ). ... The set simulation time is maximum time.
Comment: ns2 is old. Some files can run with an old OS. Your original code runs better with the 32bits `Ubuntu 10.10 - i386` : output.nam = 238kB. ... `$ nam output &` ... shows https://www.dropbox.com/s/3doe3glu8cglq3s/nam-output.jpg?dl=0
Answer:
Classfier::no-slot{} default handler

The error  "Classfier::no-slot{} default handler .."  indicate coding errors (or a too complex file.)
Besides that, the error causes the simulation not to finish.
EDIT : The typical ways to have "mixed traffic" → cbr, tcp, udp, ftp ... see examples https://www.dropbox.com/s/63ultpb20ugqlvf/new-A-ex.tar.gz?dl=0
A primitive fix : With ftp entries commented out, your simulation ends OK, and the NAM window opens. Snippet :
<code>#FTP over TCP connection
#set ftp3 [new Application/FTP]     ;# edited
#$ftp3 attach-agent $tcp3           ;# edited
#$ftp3 set type_ FTP                ;# edited
.
#$ns at 4.5 "$ftp3 start"   ;# edited
$ns at 8.0 "$cbr0 stop"
#$ns at 9.0 "$ftp3 stop"    ;# edited
</code>
Simulation :
<code>$ ns 3-no-ftp__2Aramesh.tcl
0 0
0.5 0
1 0
1.5 0
2 0
2.5 0
3 0
3.5 0
4 1
4.5 0
5 -4
5.5 -4
6 -4
6.5 -4
7 -4
7.5 -3
8 -4
8.5 -4
9 -4
9.5 -4
</code>
Files created: mon.txt 1001 lines, output.nam 514.7kB, output.tr 203.7kB .
"Link queue" ns2 doc 49.2.2 https://www.isi.edu/nsnam/ns/doc/node634.html
Note : The time you have set is maximum time.
If a simulation finishes in two seconds, no time setting will extend the actual simulation time.