Swift | The timer wont stop on invalidate call, rather speeds up?

Question: i have made a stop watch using Timer in this app and added start stop button to pause and play the same.
When the press button is pressed, it is sent to a function which invalidates the timer and it should stop.
But Strangely Enough When The Stop Button Is Pressed, Instead Of Stopping The Timer Somehow Speeds Up
i have not changed the time interval other than once just declaring it.
i have tried to disabled the start button once it is pressed and even hide it. also tried changing the time interval but nothing works. the more i press the start stop button , the more it speeds up and starts going much faster than the mentioned time interval.
startButton.frame = CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1)
    startButton.setTitle("Start Timer", for: .normal)
    self.view.addSubview(startButton)
    startButton.setTitleColor(.white , for: .normal)
    startButton.backgroundColor = .red
    startButton.addTarget(self, action: #selector(playButton(_:)), for: .allTouchEvents)

    stopButton.frame = CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1)
    stopButton.setTitle("Stop Timer", for: .normal)
    stopButton.setTitleColor(.white , for: .normal)
    stopButton.backgroundColor = .red
    stopButton.addTarget(self, action: #selector(pauseButton(_:)), for: .allTouchEvents)
@objc func playButton(_ sender : Any)
{
    timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(updateTimer), userInfo: nil, repeats: true)
    startButton.isEnabled = false
    stopButton.isEnabled = true
    isRunning = true
    self.view.addSubview(stopButton)
    startButton.isHidden = true
    stopButton.isHidden = false

}

@objc func pauseButton(_ sender: Any) {
    self.view.addSubview(startButton)
    timer.invalidate()

    stopButton.isHidden = true
    startButton.isHidden = false

    startButton.isEnabled = true
    stopButton.isEnabled = false

    isRunning = false

}

@objc func updateTimer(_ sender : Any)
{
    counter += 0.1
    titleLabel.text = String(format: "%.1f", counter)
}

Answer: Try to add both the buttons at the same time by hidding the stop button and just hide and unhide the buttons on button click. Your play button method is running every time, when you are trying to stop the timer
Comment: i did added stop button in its properties like start button and deleted all start button hide code lines but nothing changed. Also this does not explain why would the timer speed up and start going faster and faster on each stop click
Comment: This is because some how your playButton method is called again and again. check it  by placing break point on this function
Comment: ok thank you so much it worked and i spent hours but couldnt see the mistake
Comment: i did use them but didnt notice they were being stopped twice , seemed like lag in my PC, but i am still confused why would it speed up even if called again and again since the initial definition of interval never changes
Comment: It is because when ever the play button method is called a new separate timer is scheduled which causes the calling of updateTimer method separately. So when ever this happens, the counter value increments
Answer: As far as I can recognize, you have 2 mistakes.
First one is mentioned by the other answer. It is a true suggestion that you shouldn't always add a new UIButton and should use just hide/unhide property for each button.
Second mistake is on how you add a target. You are using .allTouchEvents, however you might intent to use .touchUpInside as your control state.
Kindly see the below corrected code for your reference:
import UIKit

class ViewController: UIViewController {

@IBOutlet weak var titleLabel: UILabel!

var startButton: UIButton!
var stopButton: UIButton!
var timer: Timer!
var counter: Double = 0.0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    startButton = UIButton(frame: CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1))
    startButton.setTitle("Start Timer", for: .normal)
    startButton.setTitleColor(.white , for: .normal)
    startButton.backgroundColor = .red
    startButton.addTarget(self, action: #selector(playButton(_:)), for: .touchUpInside)
    self.view.addSubview(startButton)
    self.startButton.isHidden = false

    stopButton = UIButton(frame: CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1))
    stopButton.setTitle("Stop Timer", for: .normal)
    stopButton.setTitleColor(.white , for: .normal)
    stopButton.backgroundColor = .red
    stopButton.addTarget(self, action: #selector(pauseButton(_:)), for: .touchUpInside)
    self.view.addSubview(stopButton)
    self.stopButton.isHidden = true
}

@objc func playButton(_ sender : Any) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(updateTimer), userInfo: nil, repeats: true)

    startButton.isEnabled = false
    stopButton.isEnabled = true
    startButton.isHidden = true
    stopButton.isHidden = false
}

@objc func pauseButton(_ sender: Any) {
    timer.invalidate()

    stopButton.isHidden = true
    startButton.isHidden = false
    startButton.isEnabled = true
    stopButton.isEnabled = false
}

@objc func updateTimer(_ sender : Any)
{
    counter += 0.1
    titleLabel.text = String(format: "%.1f", counter)
}
}

Comment: thanks for such an detailed and accurate answer, wish i could have noticed instead of wasting hours, appreciate the effort
Answer: You have 2 correct answers already, but I'll throw in my 2p as I think the premises you've started on hasn't been correct.
Your biggest mistake is having 2 buttons in the first place. You would not have had the issue if you only had one buttons and styled it as needed.
class MyTest {
    let magicButton = UIButton()
    let timer: Timer?

    override viewDidLoad() {
        super.viewDidLoad()

        // Setup Button
        magicButton.addTarget(self, action: #selector(buttonPress(_:)), for: .allTouchEvents)
        magicButton.setTitleColor(.white , for: .normal)
        magicButton.frame = yourFrame
        view.addSubview(magicButton)

        customiseButton()
    }

    @objc private func buttonPress() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(updateTimer), userInfo: nil, repeats: true)
        } else {
            timer.invalidate()
        }

        customiseButton()
    }

    private func customiseButton() {
        let isStartButton = timer == nil
        let buttonTitle = isStartButton ? "Start" : "Stop"
        let buttonBackgroundColor: UIColor = isStartButton ? .green : .red

        magicButton.setTitle(buttonTitle, for: .normal)
        magicButton.backgroundColor = buttonBackgroundColor
    }
}

// add updateTimer function too

This way you have less code to maintain and no conflict between stuff being hidden / shown, so fewer things that could go wrong. The magic is happening in the buttonPress method where if a timer is started you stop it, otherwise you start one, followed by a quick update to the button UI.


What are the correct mechanics for a guitar F barre chord

Question: I have been having trouble with the F barre chord and have a question about mechanics.  As an experiment I've tried moving the body very far to the right so that my eyes are somewhere over the seventh fret.  Completely impractical for playing but I wanted to see what would happen if I could get my forearm almost exactly perpendicular to the neck.  In this position it is relatively easy to play the chord.
Now when I move the guitar back to a normal playing position (casual for me), my left forearm instead of being square is now at an angle to the neck (because my left hand has to now reach left to access the first fret).  So I find to get proper mechanics i.e.  Fingers fairly square to the fretoard, I have to either stick my left elbow out to square my forearm or else twist my wrist at a weird angle so that at least I can square my palm.  If I don't square something I can press the strings with some difficulty but my fingers end up side on rather than front on.
What are the proper mechanics for playing this chord?
Comment: Possible duplicates:
http://music.stackexchange.com/questions/1767/tips-playing-f-barre-chord
http://music.stackexchange.com/questions/1419/how-can-i-best-learn-to-play-barre-chords
Comment: I would like to redirect you to my answer to this other similar question : http://music.stackexchange.com/a/10120/5937
Answer: This comes down to mechanics - what physical positions can you change?

position of the guitar: you can angle the neck up more, or raise the entire guitar
position of your elbow: you can move it forwards or sideways away from your body
position of your wrist: pushing it forwards brings the hand over the fretboard more

The F barre chord at the first fret is one of the more annoying ones, though. It is a strange position that is hard work until your muscles have developed to support it, so don't be disheartened. Sticking your elbow out is what some folks do, and others twist their wrists, and yet others cheat and don't use the barre properly at all :-)
I would suggest that in addition to @Another's answer, you try angling the neck up so you play the guitar similarly to how you would hold a flamenco guitar when seated. As you practice, you can start to lower the neck.
Answer: It sounds as though you have the fundementals correct. Bar chords become harder the closer you get to the machine heads due to the change in angles you mention.
The easiest way to attain proficiency is to practice the chord fingering at the most comfortable position on the fingerboard for you. Once you master the chord at this position move the whole hand down 2 frets towards the machine heads, and so on. Remember only move to a harder location when all of the notes of the chord ring like 'bells'.
Practice this in 10 mins blocks, to avoid injury, 10 times a day for a week and you will master it.
Answer: There are three tips on barre mechanics that are really helpful:

Maintaining your forearm and lefthand in-lined in the same plane as much as possible so that the biggest ammount of strenght that you use to grip the F chord doesn't come from your poor tiny hand muscles, but from your whole shoulder and back. Having a sharp angle at your left wrist makes you loose all that valuable force.
Using gravity's force to help you grip the chord. If you imagine your arm like hanging from the fretboard as if you were hanging from a branch there's a way to relax your arm to the limit where it doesn't drop and also you can feel it's own weight pushing down for the chord grip.
Imagining that your left hand index finger it's somehow like six fingers, since it's possible to figure out ways to discriminate how much strenght you apply to individual strings. In most chords you need to press just two or three strings with the barre, either by curving a little your index finger so that it only presses individual strings (only the 6th, 2nd and 1st, in the case of the F major chord, being sure that you are not wasting force on the other strings, which in F major should sound muted if fingers 2, 3 and 4 aren't on the fretboard) or by not covering all six strings with your index finger in the case you don't need to.

I learned this some time after I actually could play barre chords, but it made me look over my technique again and now barre chords feel lighter to play. The exact position of every part of your body is up to every individual player, so if you think these tips might be useful, you'll have to figure out by your own the specific application of them to your playing.


How to strike any letter using Unicode in Java

Question: In my Java application I want to output striked letters (like html tag  do). Is there any way to do this using Unicode (combine )
Answer: You can use U+0336, the combining long stroke overlay, to accomplish this task.
The official Combining Diacritical Marks unicode chart lists "strikethrough" as an 'informative alias', meaning that this is is the official specified purpose of this character.
0336 ̶◌ COMBINING LONG STROKE OVERLAY
       = strikethrough
       • connects on left and right

For comparison, here is U+0336 compared to the html  tag:

U̶n̶i̶c̶o̶d̶e ̶c̶o̶m̶b̶i̶n̶i̶n̶g̶ ̶l̶o̶n̶g̶ ̶s̶t̶r̶o̶k̶e̶ ̶o̶v̶e̶r̶l̶a̶y̶
Hypertext strike tag

Note that many font rendering engines do not render U+0336 correctly, and when possible one should use markup formatting or another mechanism. Depending on your browser, the above text likely has a large gap in the line around the "m" in combining, and @Alex78191 reports that it renders so low for them that it looks more like an underline than a strikethrough.
For this reason, one should still prefer HTML another markup technology over U+0336 for this purpose, given the option.
Comment: it looks like underline
Comment: @Alex78191 Thank you for the information, I've added your observation to my answer. Unfortunately, most font renderers have only incomplete or flawed support for combining characters.
Answer: No, this is not possible. While there is the concept of a stroke as diacritic, it's not available as a separate Unicode character, probably because the various letters that use a stroke diacritic do not place it at the same height or even angle. So the result would not resemble strikethrough markup anyway.
To output strikethrough text in Java, you need to use an output format that allows you to use explicit markup. If you have a Swing app, you're in luck as many Swing components support HTML. Otherwise it depends on what presentation technology you're using.
Comment: You've given a good answer why the WITH STROKE code points have no decompositions that include any sort of stroke combining character, like **ø** U+00F8 `LATIN SMALL LETTER O WITH STROKE` or **đ** U+0111 `LATIN SMALL LETTER D WITH STROKE` (not to be confused with **ð** 00F0 `LATIN SMALL LETTER ETH`).  Interestingly, these *are* considered "the same letters" as **o** and **d** respectively and yes even in the ETH, as shown by the UCA DUCET. So a primary-strength UCA would count them as the base chars they don't decompose to.
Comment: Unicode does actually define a combining strikethrough character as a separate codepoint, at U+0336.
Comment: @tchrist : OP was not looking for _letters with stroke_ (like ĐđØø etc), but for strikethrough that can be happily simulated using U+0336 as other answers state.
Answer: As said before, Unicode doesn't do that, but a lot of Swing components understand basic HTML tags.
JLabel label = new JLabel("<s>My stroke</s>")

Answer: No. Unicode does not define a combining strikeout mark. Unicode's view is that this is the job of markup -- like HTML.
Comment: This is precisely wrong - Unicode DOES define a combining strikeout mark, as I discuss in my answer.


Prometheus client integration

Question: I'd like to integrate Prometheus into my system and am wondering about the amount of work that needs doing. I already have the ability to present JSON formatted data to HTTP endpoints (so external systems can currently GET a limited amount of information already) - is it just a case of adding a new 'prometheus formatted' endpoint so the prometheus server can scrape from it? I'm not worried about pushing
Answer: If you already have the metrics, then exposing it over HTTP in the Prometheus text format will do the trick.
If possible you should use one of the existing client libraries to do so for you, as it'll handle the little details like escaping.

Prometheus client integration


C++ Pointer Dereferenced Assignment

Question: I am trying to learn C++ by firstly going through the low level details before I start using abstractions such as std::copy or memcpy. Currently I am stuck in trying to figure out why this code is never assigning into "sortedArray" variable, when looking with debugger I dereference the value from "data" correctly but it is never assigned to "sortedArray". I see value such as "-842150451" instead of "14" for first value. Can you please help me figure out what I am doing wrong ? And any other issues there may be that I do not see or advice would be greatly appreciated !
void swap(int* bigger, int* smaller){
    *bigger += *smaller;
    *smaller = *bigger - *smaller;
    *bigger = *bigger - *smaller;
}

int* bubbleSort(int *data, int size){
    bool swapped = true;
    int *sortedArray = (int*)malloc(size*sizeof(int));
    for (int i = 0; i < size;i++){
        *(sortedArray++) = *(data++);
    }

    while (swapped){
        swapped = false;
        for (int i = 1; i <= size - 1; i++){
            if (sortedArray[i - 1] > sortedArray[i]){
                swap(&sortedArray[i - 1], &sortedArray[i]);
                swapped = true;
            }
        }
        size--;
    }
    return sortedArray;
}

Comment: Here's another one: you are not using `std::vector`.
Comment: you are not learning C++, this is C code.
Comment: Heres your problem: `*(sortedArray++) = *(data++);`
Comment: Here's another one: `swap(&sortedArray[i - 1], &sortedArray[i]);`
Comment: `I am trying to learn C++ by firstly going through the low level details` While you're doing that, person B *is* learning the higher abstractions, thus producing productive, non-buggy programs.
Comment: What is the issue in *(sortedArray++) = *(data++); ? I am dereferencing source and target array for values, copying the value across, and incrementing pointer. I cannot put parenthesis any other position otherwise it throws error and if I don`t have it then I have same issue.
Comment: @0x499602D2 What is the error there?
Comment: `What is the issue in *(sortedArray++) = *(data++); ` Which side of the `=` gets incremented first?
Comment: @PaulMcKenzie "Which side of the = gets incremented first?" Why would it matter?
Comment: @IgorTandetnik - I guess it doesn't matter in the long run, since the pointer to the allocated memory is now gone anyway.
Comment: @user3722518 - in the code where you called this function, did you attempt to `free` the data allocated by that call to `malloc`?  If you did, what happened?  If you didn't, then that is another issue you need to take heed of, and that is causing memory leaks.
Comment: ...Why didn't you just sort with `data`?
Answer: *(sortedArray++) = *(data++); modifies the pointer so it no longer points to the start of the allocated memory.  So, later on sortedArray[i] is whatever happens to be in memory past the array, and accessing it is undefined behavior.
If you must use pointers, a quick fix is to use a temporary one, like:
int *sortedArray = (int*)malloc(size*sizeof(int));
int* s = sortedArray;
for (int i = 0; i < size;i++){
    *s++ = *data++;
}

Another way would be:
int *sortedArray = (int*)malloc(size*sizeof(int));
for (int i = 0; i < size;i++){
    sortedArray[i] = data[i];
}

But, the best way would be to use standard containers and algorithms, like vector and sort.
Here's a demo of the first fix in action.
Comment: Thank you for the explanation, seems quite obvious now ... I plan on looking at the containers shortly, thank you :)
Comment: `error: 'malloc' was not declared in this scope`
so just one string should be added `#include `
Comment: @RuslanGerasimov Ah, in the demo you mean.  It compiles on both ideone and visual studio without it, but I added it anyway to be safest.  I use `malloc` so infrequently I forgot that.  Thanks for pointing it out.
Answer: Change
*(sortedArray++) = *(data++);

to
sortedArray[i] = data[i];

You need to leave intact the pointer to the block of memory you allocated, so you can use it (and free it) later.
Note, there is nothing to be gained by using the *(x+y) syntax instead of x[y], they are equivalent but the latter is easier to read.
In C++ you should not use malloc. Instead use new int[size].  For int there is no difference other than reduced risk of making a typo, however for non-trivial types malloc will not construct them correctly.
Comment: Thank you for the advice regarding new [], I will use it from now on.
Answer: That is not C++ at all. You can write generic code that takes a begin iterator and an end iterator in order for it to work with any kind of container that supports such semantic.
template<typename IT>
void bubble_sort(IT begin, IT end) {
    while (true) {
        bool swapped = false;
        for (IT i = begin; i != end-1; i = i+1) {
            if (*i > *(i+1)) {
                std::iter_swap(i, i+1);
                swapped = true;
            }
        }
        if (swapped == false) return;
    }
}

Live demo
Where std::iter_swap is like std::swap but works on iterators. You can see iterators as a pair of pointers to the beginning and (past the) end of a container.
Comment: It has an error , which can be fixed with a single line.
Comment: @self. Marking a question with C **and** C++ makes absolutely no sense at all. We are allowed to just assume he meant C++. It introduces templates because they are a good choice and invites the user to learn about them. If he is just going to copy and paste the code, there's not much I (or you for that matter) that can do for him.
Comment: Can you get even more cryptic, this is not going to help OP.
Comment: @self. That doesn't change the fact that 1) that's not C++; 2) that code should not be perpetuated; 3) he can learn much more from the above code than to an "easy" fix to his.
Comment: OP marked the question with c, c++ and posted some code. Your code is not just diverging from his style, but is completely different, even introducing templates(?) which are completely unnecessary for the problem. You also posted a complete code example which OP can now happily copy/paste. What will he learn from that?
Comment: Sure there is, look at all other answers.
Answer: You first pointer sortedArray points to some allocated memory.
Then in the first for loop you increment the pointer. not it doesn't point to that memory anymore.
Simply use a temporary pointer for the memory copy.
int* t = sortedArray ;

And now use t in your for loop which copies the data.
Instead of the temporary variable, you can rather count the number of times you called sortedArray++ in your for loop.
If you take a look: for (int i = 0; i < size;i++) you will see that the loop took exactly size number of iterations.
Just subtract size from the pointer after the loop and you point back to your allocated memory.
sortedArray -= size ;

Comment: Thank you for your answer as well which doesn`t make use of a auxiliary variable, I didn`t notice this detail.
Comment: Are you actually recommending pointer arithmetics? Is that the kind of the answer the OP (or any new programmer) should learn from? I doubt so.
Comment: @Jefffrey Yes, because he is using pointer arithmetic in his code and that is where the problem was. This was the perfect time to give him some more information on the subject.
Comment: @self. No wonder. Pointer arithmetics often introduce bugs and runtime errors. It is also unreadable and there are way better ways to approach the problem. It is well known in the C++ community that working with pointers is the last thing you want to do. Simple answer is not always the correct one.
Comment: @self. Where have I misinterpreted anything, exactly?
Comment: @Jefffrey Or in other words a logical fallacy.
Comment: @self. You haven't answered my direct question. Is that a logical fallacy?
Comment: @Jefffrey You obviously didn't understand the wikipedia article you have been hastily reading.
Comment: @self. Yes, I've looked on Wikipedia what the straw argument is. I've heard it before on the [Lounge](http://chat.stackoverflow.com/rooms/10/loungec) but I don't always remember it's exact meaning, so I've informed myself on it. You are still not answering my question.
Comment: @Jefffrey Yes I choose not to answer pointless and illogical questions.
Comment: @self. Best argument ever. Have a nice day.
Comment: @Jefffrey You even have problems with the basics. That was not an argument but a simple statement.
Comment: @Jefffrey From what I have read there is no mention that pointers are frowned upon, actually I am led to believe they are used in many applications as well as favorite for interviewers to triage with ?
Comment: @user3722518 - It depends on the interview.  If it is for a C++ position, showing off your usage of pointers instead of displaying a working knowledge of the standard library could be a minus, not a plus.

C++ Pointer Dereferenced Assignment


FatFS - Cannot format drive, FR_MKFS_ABORTED

Question: I am implementing a file system on SPI flash memory using a w25qxx chip and an STM32F4xx on STM32CubeIDE. I have successfully created the basic i/o for the w25 over SPI, being able to write and read sectors at a time.
In my user_diskio.c I have implemented all of the needed i/o methods and have verified that they are properly linked and being called.
in my main.cpp I go to format the drive using f_mkfs(), then get the free space, and finally open and close a file. However, f_mkfs() keeps returning FR_MKFS_ABORTED. (FF_MAX_SS is set to 16384)
  fresult = FR_NO_FILESYSTEM;
  if (fresult == FR_NO_FILESYSTEM)
  {
      BYTE work[FF_MAX_SS]; // Formats the drive if it has yet to be formatted
      fresult = f_mkfs("0:", FM_ANY, 0, work, sizeof work);
  }

  f_getfree("", &fre_clust, &pfs);

  total = (uint32_t)((pfs->n_fatent - 2) * pfs->csize * 0.5);
  free_space = (uint32_t)(fre_clust * pfs->csize * 0.5);

  fresult = f_open(&fil, "file67.txt", FA_OPEN_ALWAYS | FA_READ | FA_WRITE);
  f_puts("This data is from the FILE1.txt. And it was written using ...f_puts... ", &fil);
  fresult = f_close(&fil);

  fresult = f_open(&fil, "file67.txt", FA_READ);
  f_gets(buffer, f_size(&fil), &fil);
  f_close(&fil);

Upon investigating my ff.c, it seems that the code is halting on line 5617:
if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
n_clst is calculated a few lines up before some conditional logic, on line 5594:
n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
Here is what the debugger reads the variables going in as:

This results in n_clst being set to 4294935040, as it is unsigned, though the actual result of doing the calculations would be -32256 if the variable was signed. As you can imagine, this does not seem to be an accurate calculation.
The device I am using has 16M-bit (2MB) of storage organized in 512 sectors of 4kb in size. The minimum erasable block size is 32kb. If you would need more info on the flash chip I am using, page 5 of this pdf outlines all of the specs.
This is what my USER_ioctl() looks like:
DRESULT USER_ioctl (
    BYTE pdrv,      /* Physical drive nmuber (0..) */
    BYTE cmd,       /* Control code */
    void *buff      /* Buffer to send/receive control data */
)
{
  /* USER CODE BEGIN IOCTL */
    UINT* result = (UINT*)buff;
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_11, GPIO_PIN_SET);

    switch (cmd) {
        case GET_SECTOR_COUNT:
            result[0] = 512; // Sector and block sizes of
            return RES_OK;
        case GET_SECTOR_SIZE:
            result[0] = 4096;
            return RES_OK;
        case GET_BLOCK_SIZE:
            result[0] = 32768;
            return RES_OK;

    }
    return RES_ERROR;
  /* USER CODE END IOCTL */
}

I have tried monkeying around with the parameters to f_mkfs(), swapping FM_ANY out for FM_FAT, FM_FAT32, and FM_EXFAT (along with enabling exFat in my ffconf.h. I have also tried using several values for au rather than the default. For a deeper documentation on the f_mkfs() method I am using, check here, there are a few variations of this method floating around out there.
Comment: I've used FatFS to access a SPI flash chip I made available over USB. Clifford is right, if you only want internal access, other filesystems are better.
Answer: Here:
fresult = f_mkfs("0:", FM_ANY, 0, work, sizeof work);

The second argument is not valid.  It should be a pointer to a MKFS_PARM structure or NULL for default options, as described at http://elm-chan.org/fsw/ff/doc/mkfs.html.
You should have something like:
MKFS_PARM fmt_opt = {FM_ANY, 0, 0, 0, 0};
fresult = f_mkfs("0:", &fmt_opt, 0, work, sizeof work);

except that it is unlikely for your media (SPI flash) that the default option are appropriate - the filesystem cannot obtain formatting parameters from the media as it would for SD card for example.  You have to provide the necessary formatting information.
Given your erase block size I would guess:
 MKFS_PARM fmt_opt = {FM_ANY, 0, 32768, 0, 0};

but to be clear I have never used the ELM FatFS (which STM32Cube incorporates) with SPI flash - there may be additional issues.  I also do not use STM32CubeMX - it is possible I suppose that the version has a different interface, but I would recommend using the latest code from ELM rather than ST's possibly fossilised version.
Another consideration is that FatFs is not particularly suitable for your media due to wear-levelling issues.  Also ELM FatFs has not journalling or check/repair function, so is not power fail safe.  That is particularly important for non-removable media that you cannot easily back-up or repair.
You might consider a file system specifically designed for SPI NOR flash such as SPIFFS, or the power-fail safe LittleFS.  Here is an example of LittleFS in STM32: https://uimeter.com/2018-04-12-Try-LittleFS-on-STM32-and-SPI-Flash/
Comment: @JonathanJust - same library different version; I am using an even older version that lacks the opt parameter altogether.   Good decision on LittleFS.  I would generally avoid most all of the STM32Cube nonsense.  It is a collection of poorly documented parts from various sources and varying quality - the worst being the parts contributed by ST themselves.  Their HAL is a dog made worse by the documentation.  You can write your own bugs, you don't need the chip vendor to do it for you ;-)
Comment: Thank you so much for your help! I have decided to switch to littleFS. As for the bad parameter in the method, I think you are referring to a different distribution of FatFS. The one I am using came with STM32CubeIDE, and is documented in the link.
Answer: Ok, I think the real problem was that the IOCTL call GET_BLOCK_SIZE to get the block size was returning the sector size instead of the number of sectors in the block.  Which is usually 1 for SPI Flash.


Lycoris models fail in Stable Diffusion with error "size of tensor a (768) must match size of tensor b (1024)

Question: I am using AUTOMATIC111/stable-diffusion-webui on my PC (Window 10, Intel Cor i9, 64GB RAM, Nvidia RTX 3060).  I have successfully installed the LoRA and LyCORIS extensions in Stable Diffusion, and both have tabs in Extra Networks. All of the LoRA models that I have downloaded from civiai.com work, but only one of the 10 LyCORIS models work.  For example, colouredglazecd-000006.safetensors works.  I got this image using img2img with a picture of a pink rose and the prompt: lyco:colouredglazecd-000006:1.0rose. glazed rose
However, when I try to use  lyco:CenturyBotanicalIllustration:1.0rose or any of the other 9 Lycoris models I downloaded, I get the error message:  RuntimeError: The size of tensor a (768) must match the size of tensor b (1024) at non-singleton dimension 1.  Below is a sample of the beginning of the webui-user.bat output and a sample from the end of the code.  Changing the width or height of the output image doesn't help.  Any help with this will be greatly appreciated
Zaffer
Code from beginning of webui-user.bat
<code>key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc1.alpha████████████████| 16/16 [00:06<00:00,  3.09it/s]
key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc1.lora_down.weight
key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc1.lora_up.weight
key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc2.alpha
key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc2.lora_down.weight
key failed to match: lora_te_text_model_encoder_layers_12_mlp_fc2.lora_up.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_k_proj.alpha
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_k_proj.lora_down.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_k_proj.lora_up.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_out_proj.alpha
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_out_proj.lora_down.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_out_proj.lora_up.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_q_proj.alpha
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_q_proj.lora_down.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_q_proj.lora_up.weight
key failed to match: lora_te_text_model_encoder_layers_12_self_attn_v_proj.alpha

Code from end of webui-user.bat
File "G:\GenAI\venv\lib\site-packages\transformers\models\clip\modeling_clip.py", line 268, in forward
        query_states = self.q_proj(hidden_states) * self.scale
      File "G:\GenAI\venv\lib\site-packages\torch\nn\modules\module.py", line 1501, in _call_impl
        return forward_call(*args, **kwargs)
      File "G:\GenAI\extensions-builtin\Lora\lora.py", line 400, in lora_Linear_forward
        return torch.nn.Linear_forward_before_lora(self, input)
      File "G:\GenAI\extensions\a1111-sd-webui-lycoris\lycoris.py", line 739, in lyco_Linear_forward
        lyco_apply_weights(self)
      File "G:\GenAI\extensions\a1111-sd-webui-lycoris\lycoris.py", line 706, in lyco_apply_weights
        self.weight += updown
    RuntimeError: The size of tensor a (768) must match the size of tensor b (1024) at non-singleton dimension 1
</code>
Answer: I think your locon model based different SD model. Let's say your trying to create image with sd v1.5 and your locon (or lycoris) model is based sd v2.1


Somewhat powerful server needed for computationally expensive stuff

Question: So here's my problem.
My Dad runs a company that does some rather computationally expensive stuff. This is not supercomputer level stuff, but it does take several hours to run the average job on his Core i7 desktop.
He asked me to look into a way to have his customers use the code on an hourly basis, namely via a server. Ideally he'd be able to buy a box for about $1000, and hook it right up to our home connection. Unfortunately, the data that needs to be both sent and received is on the order of several hundred megs. We live in a rural area, and the fastest connection offered is 1.5Mbit/s. Download. It's like .3Mbit/s upload.
Not workable.
What are the options for this kind of thing? Ideally, we'd have about 2GB of ram, 300-500GB of storage, and a nice dual core, and it has to run some flavor of Linux.
Any suggestions? Thanks in advance
EDIT: Also, ideally the monthly price would be < $100 per month.
Comment: Your budget is too low even for decent colo in a datacenter.
Answer: think about how to break the problem into separate independent threads/processes and go cloud - eg with amazon or rackspace virtual servers. spin up as many vms as you need for the time of computation and then shut them down. you pay per gig of storage and per cpu/hour. they are quite cheap if you use them rarely [ not 24x7 ].
you might be interested in this comparison of different offers in terms of efficiency.
Comment: Happy 10K! Which answer pushed you over the edge?
Comment: @Wesley 'Nonapeptide' - thanks. from stats it seems to be this one: http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket/124518#124518 ; not inventive really.
Answer: You can rent by-the-U space in a colo for about $100 a month. That can include a monthly bandwidth cap of about 1Tb and will have a certain cap on burstable and sustained bandwidth speeds.
From there you can hack together a halfway decent server using a supermicro case and some Opterons. However, for $1000 you'd be hard pressed to outperform a decent i7. I think you may need to bump the initial budget up to at least $2000 to get a server.
Here's a by-the-U pricing page for a colo in my area just for reference.
Comment: depends on your standards.. i'm using http://www.dediserv.eu/ - they rent servers at leasweb in amsterdam and netdirekt in frankfurt. work reasonably well [ for that price.. ], no problems with bandwidth, avg monthly usage is at 3-4TB, but there were cases where it was exceeded. 5TB + hardware for 75$/month.
Comment: @pQd Thanks for the link! I'll keep them in mind for my own usage.
Answer: Look into a Rackspace Cloud Server (http://www.rackspacecloud.com/cloud_hosting_products/servers/pricing).
Don't listen to the commenter who said your budget is too low. $100 will buy you six thousand hours of time on a basic 256MB server... or 104 hours on a quad-core 15.5GB "monster"... or anything in-between.
I have used their service. It's easy to get started, and it works well. I've also looked into the Amazon EC2 but didn't like it... YMMV.
Answer: It seems to me that You would like to keep processing inhouse.
It also seems that You are pulling datasets and transmit them back processed. If that is the case, then latency is not a problem, so You could look at satellite internet. I've been told it gets up to 1,5 Mbits upstream. There are areas where satellite internet is not dead expensive.
Also, if Your area is not too rural, You might have the chance to set up long range WiFi to a neighbour that has broadband (if there are neighbours with broadband).
Just wanted to add those possibilities.


Choices in django

Question: My Models:
class Book(models.Model):
    # book types and placed
    BIOGRAFIA = 1
    FANTASTYKA = 2
    HISTORYCZNY = 3
    HORROR = 4
    POEZJA = 5
    PRZYGODA = 6
    ROMANS = 7
    DRAMAT = 8
    BRAK = 0
    B00K_CHOICES = (
        (BIOGRAFIA, 'Biografia'),
        (FANTASTYKA, 'Fantasy/Sci-Fi'),
        (HISTORYCZNY, 'Historyczny'),
        (HORROR, 'Horror'),
        (POEZJA, 'Poezja'),
        (PRZYGODA, 'Przygoda'),
        (ROMANS, 'Romans'),
        (DRAMAT, 'Dramat'),
        (BRAK, 'Brak informacji'),
    )
    tytul = models.CharField(max_length=60, unique=True)
    autor = models.ForeignKey(Author, on_delete=models.CASCADE)
    opis = models.TextField(null=True, blank=True)
    gatunek = models.IntegerField(choices=B00K_CHOICES, default=BRAK)
    cena = models.DecimalField(max_digits=400, decimal_places=2)
    rok_wydania = models.DateField(null=True, blank=True)
    liczba_stron = models.PositiveIntegerField(null=True, blank=True)
    zdjecie = models.ImageField(null=False, blank=True, upload_to='zdjecia_ksiazek')
    przecena = models.BooleanField()

    def __str__(self):
        return self.tytul

My View:
def Gatunek(request, gatunek_id):
    ksiazki = Book.objects.filter(gatunek=gatunek_id)
    return render(request, 'ksiazki.html', {'ksiazki': ksiazki})

I don't think my view is too good, I don't know if it should also be {{gatunek. gatunek}}
My template HTML:
                     {% for ksiazki in ksiazki  %}

{{ksiazki}}

{{ ksiazki.gatunek }}

{{ ksiazki.opis }}

                        {% endfor %}

It seems to me that I have a problem in Django when I am looking for a field that has a selection parameter. I don't get the field names, but instead I get the number for a strange reason.
Please Help
Answer: In order to obtain the textual representation of a choice, you can use the get_fieldname_display() method [Django-doc], so here, .get_gatenuk_display(). In your template, you render this with:
{{ ksiazki.get_gatunek_display }}
You should not include parenthesis. Django's template language does not allow this, but will automatically call callables.
Answer: I have one more question how to make my template (html) in navbar (boostrap) show all your choices = B00K_CHOICES

Choices in django


Send Mail From Another Server

Question: I have a server that has been sending email for the past 2 years, using PHP's mail() function. It runs Windows Server 2003. I have another server, on the same local network as it, running Ubuntu 10.10. Is there a way I could tell a PHP script executed to dump the email into the Windows' SMTP folder to go out?
UPDATE: I'll leave the above, so the other answers make sense, but just for some clarification, here is what I was trying to do. Execute a PHP script via cron on the Ubuntu server that would read a database and dump the emails into its SMTP queue via PHP's mail(), which would in turn relay the emails to a Windows server, which would actually send the emails out.
Answer: You can configure the windows box to allow the mail relay from the ubunto box rather than dump files into the smtp folder
Comment: @Jim: Can you perhaps give me a link explaining that? I'm just a programmer, not exactly sure how to set that that up on a server.
Comment: @Jim B: Something like this? http://technet.microsoft.com/en-us/library/aa998368%28EXCHG.65%29.aspx How would I then tell the Ubuntu box to dump to that server instead then?
Comment: @josh, No take a look at http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/58f05ef9-55a3-42b3-9f57-27fdc8723b8a.mspx?mfr=true
Comment: @Jim B: Just glancing through that, it looks like the doc describes how to configure one IIS instance to forward to another. I need to configure an Ubuntu SMTP to relay to an IIS. Is that possible?
Comment: @so you question is morphing from how to get mail from PHP to how to get mail from ubunto to windows.  I'm sure it's possible to relay mail from 2 different servers but I'm not sure that's the approach I would take.  That aside, setting the relay resctictions are the same regardless of source system in IIS, there is nothing specifically requiring windows in order to allow relay.
Comment: @Jim B: Sorry I may not have been clear, but I have the emails in a db on the ubuntu server. I want to execute a php script via cron, and have that php script send the mail either directly, or via an ubuntu relay it sounds like, to the windows server's smtp queue.
Answer: Looking down http://php.net/manual/en/function.mail.php (under "Notes") you can make the mail() function talk directly to a Mail Transfer Agent running on a remote host (although bizarrely this functionality appears to be unique to the Windows implementation, based on the documentation, so if you ever need to move the script to another platform you'll need to bear this in mind...)
Try this, in php.ini on the Windows host:
[mail function]
SMTP = yourubuntumachine.domain.com; for Win32 only
smtp_port = 25

You'll need some kind of MTA running on the Ubuntu host, of course, but it's simple enough to install (say) Exim (in the exim4-daemon-light package) and configure it to relay mail only from your Windows box.
Comment: I need to send from an Ubuntu box, but mail from a Windows box, so I don't think this will work then, will it?
Comment: Sorry, I thought the PHP was running on Windows and the mail server on Linux -- is this the opposite way round?
Comment: Yes, there is a db of emails on the linux box, that will be hit by a cron'd php script, which needs to send the emails to the window's smtp, either directly, if possible, or apparently via a relay in the ubuntu smtp server.
Comment: Ah - apologies, I have answered the exact opposite of the question then, sorry!
Answer: Here is what I did to solve this, since I wasn't clear, and the other answers were backwards (my fault).
I setup ssmtp on the Ubuntu box as per this guide: http://www.davidhurst.co.uk/2007/06/19/php-mail-and-ssmtp-on-debian-linux/ . It involved editing the ssmtp.conf file, and editing php.ini to use a different sendmail_path.
I then configured MailEnable, the SMTP server running on Windows to allow incoming relay connections.
I restarted Apache, and now when I PHP mail() from the Ubuntu box, they get relayed to the Windows SMTP server and sent out.

Send Mail From Another Server


Creating Virtual Proxy Server

Question: I know this is not this kind of forum, but I can't find anything in google that really answers my question.
Is there possible to create a Proxy server running in a Virtual Machine using only 1 Physical Network Adapter (1gb Ethernet port) that manage the connections of more Physical Clients?
Thanks for taking your time in reading this and once again sorry for posting this here guys.
The virtual machine would be running over a Domain Windows Server 2008 R2
Answer: If by "proxy server" you mean a web proxy, yes of course you can. Some commercial products aren't certified to be run as VM guests, but there's no technical reason that it can't be made to work, in most cases.
Answer: There is no reason why that wouldn't work. You have a few open source solutions for a software reverse proxy/load balancer on windows. e.g. Nginx and apache. I like HAProxy in linux but that is not what you are asking for.
Don't expect the best performance though, you are using it on your windows server (i.e. not even a dedicated VM) and you are not taking advantage of the hardware acceleration that physical load balancers have.
Comment: The main system is Running Windows, but the VM can be running anything, I just wonder if it would work, I want the physical Clients to enter credencials in order to navigate and so be able to manage what, where, when can they access to the Intranet and the Internet.

Creating Virtual Proxy Server


Services Views and combine different field values into one?

Question: I got a site with a profile2 type and a content type that uses the same field containting coordinates (field_coordinates).
I'm using Services Views to show these coordinates in JSON but this is where I ran into some problem. I want only one field set of these coordinates visible, but I have to chose the relationship of the field: either no releatinship shows the node coordinates, or the relationship with the profile shows the profiles coordinates.
There will never be two sets of coordinates per output node (in one case the are requested from the node, and the other case from the profile). The JSON output cant show two fields with the same label so I have to have two different names: one for profile coordinates and one for node coordinates.
The issue is that I want only one coordinate field, and therefore added a global text field, where I put both of the place holders from the other coordinates. But this global text field output wont show in my Services view. Why is that?
Answer: Try taking one field and hiding it with views then if the next field is empty pull that one in there?
Comment: Sorry I don't have an answer to the issue but this seems like it could be a workaround.
Comment: I cant hide it. It still shows..
Comment: I've added a (hopefully) helpful image to my answer. Any field in any view should have this option.


Redirect NGINX HTTPS domain to new HTTPS domain

Question: After spending hours using duckduckgo, this was the best answer I arrived at and it's still not working to redirect a currently HTTPS domain to a new HTTPS domain.
server {
    listen 80;
    listen 443 ssl;
    server_name www.olddomain.com olddomain.com;
    rewrite 301 https://newdomain.com$request_uri;
}

Browser gives Insecure Connection error.
I have also tried things like
server {
    listen 443 ssl;
    server_name olddomain.com;
    ssl on;
    ssl_certificate /etc/ssl/certs/OLD.crt;
    ssl_certificate_key /etc/ssl/private/OLD.key;

    #enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated.
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    ssl_ciphers "ALLLLLLTTHHISSSS";
    ssl_prefer_server_ciphers on;

    rewrite 301 https://newdomain.com$request_uri;
}

Although this option stops giving an error the rewrite is not working and it goes to a "Welcome to NGINX Page."
Comment: `return 301` not rewrite.  SSL connects first, you need a valid SSL even to redirect... Look at letsencrypt
Answer: If you want to redirect https requests from an old to a new domain name you'll need a certificate for the old website configured inside that Nginx server block.
You'll need to cater for https://example.com and https://www.example.com
This is a basic config that should do the job. IMHO you don't need to worry about SSL versions for a server that just does forwarding, just use the defaults.
server {
  server_name www.example.com;

  listen 443 ssl;

  ssl_certificate /var/lib/acme/certs/***CERT_DIRECTORY/fullchain;
  ssl_certificate_key /var/lib/acme/certs/***CERT_DIRECTORY/privkey;

  return 301 https://www.example2.com$request_uri;
}

Comment: This will give Cert Error if
1. the domains are on the same host/IP
2. the certs don't support both the old and new domain

The only way the above may work is if the old domain is on a different IP/Host to the new one.

For a solution that works with the first scenario see this: https://serverfault.com/questions/633168/nginx-redirect-from-old-domain-to-new-with-ssl
Comment: This works across domains on my own server. I haven't tried cross servers so you may be correct.
Answer: When I need to redirect an entire domain, I usually just forward the domain at the domain name registrar level. Here's how to forward your domain if you're using GoDaddy. Most registrars will allow you to do this.
Benefits of setting forwarding at registrar level:

You don't have to worry about getting things right on your server
You won't accidentally forget to set up your Apache (or other web server) redirects if you move to a new server

Drawbacks to server-level forwarding:

Less control if you're just forwarding say port 80 but not 443

Sometimes the simplest answer is best... took me a while to think of this the first time :)
Comment: I don't think using registrar specific solutions is a great idea.
Comment: @tim, can you provide your specifics on why registrar forwards are not a good idea? I already noted some of them but will add more if they are not just personal preference.
Comment: Vendor specific solutions can create unexpected and difficult to solve problems.
Answer: If you have a 301 redirect on the new domain from http to https you can avoid the certificate problem by redirecting from the old-domain to the http version of the new domain. eg:
On the old domain
server {
    server_name old-domain.com www.old-domain.com;
    return 301 http://new-domain.com/$request_uri;
}

On the new domain
server {
    listen 80
    server_name new-domain.com www.new-domain.com;
    return 301 https://new-domain.com/$request_uri;
}


Utilizar valor de um select com JavaScript

Question: Preciso utilizar o valor de um select em um if, no momento tenho isso:
Esse seria o HTML:

Quantidade de vidas?

    <select>
    <option value="vidas1" id="vidas">Mais 1000</option>
    <option value="vidas2" id="vidas">Mais 5000</option>
    <option value="vidas3" id="vidas">Menos 1000</option>
    </select>

Importancia ?

    <select>
    <option value="marca1" id="marca">Pouco Importante</option>
    <option value="marca2" id="marca">Importante</option>
    </select>

    <input type="button" id="resposta" value="Calcular"/>

Resultado:

Tendo isso, eu utilizo o JS para pegar o valor do que foi selecionado no select
Esse seria o JS:
window.onload = function(){
var btn = document.getElementById("resposta");
btn.addEventListener("click",function(){

var nomedoCliente = parseFloat(document.getElementById("nmCliente").value)
calcular(nomedoCliente);
},false);
function calcular(a){

var clienteNm = document.getElementById("nmCliente").value
var qtdeVidas = document.getElementById("vidas").value
var importanciaOp = document.getElementById("marca").value

if (qtdeVidas == "vidas1" && importanciaOp == "marca1" ) {
document.getElementById("resultado").innerHTML="
 "+clienteNm+", identificamos que você se encontra no nivel 1
"
}
else {
document.getElementById("resultado").innerHTML="
 "+clienteNm+"
"
}

Porém, não importa o valor que eu coloque selecionado, ele sempre entra no primeiro if onde diz que ele se encontra no nivel1, e não sei o que está acontecendo.
Answer: Você está utilizando getElementById(). O método getElementById() retorna o elemento que possui o atributo ID com o valor especificado. Porém um ID deve ser exclusivo em uma página. No entanto, se houver mais de um elemento com o ID especificado, o método getElementById() vai retornar o primeiro elemento somente. No seu caso retornando apenas vidas1 que é o primeiro ID que ele encontrou na pagina.

Você pode utilizar outro método para obter os valores, como querySelectorAll(), ou pode editar o seu código da seguinte maneira.
<select id="vidas">
  <option value="vidas1" >Mais 1000</option>
  <option value="vidas2">Mais 5000</option>
  <option value="vidas3">Menos 1000</option>
</select>

E na hora de manipular o select você pode fazer dessa forma utilizando o getElementById()
var e = document.getElementById("vidas");
var strVidas = e.options[e.selectedIndex].value;

Answer: Opa, o id do options, deve estar no select, e não no option.
Assim:
<select id="vidas">
    <option value="vidas1">Mais 1000</option>
    <option value="vidas2">Mais 5000</option>
    <option value="vidas3">Menos 1000</option>
</select>


How to split aggregated variance of one random variable into multiple random variables?

Question: I apologize if this question is trivial, but I didn't come to a conclusion by myself.
I have an aggregated forecast for a group of $n$ items, normally distributed with mean and standard deviation.  $(\mu_F, \sigma_F) $ From this bulk forecast I am trying to go backwards to single item forecasts.
From historical data I know, that the means of the $n$ items follow a known distribution. I can also assume independence. For simplicity let's imagin $n=3$:
We know that $\mu_1+\mu_2+\mu_3=\mu_F$ and $\sqrt(\sigma_1^2+\sigma_2^2+\sigma_3^2)=\sigma_F$
We also know the means follow the following distribution:
$\mu_1 = 0.2\mu_F ,$
$\mu_2=0.5\mu_F,$
$\mu_3=0.3\mu_F$
From the given information above, is it possible to assume $\sigma_1 = \sqrt(0.2)\sigma_F,    \sigma_2 = \sqrt(0.5)\sigma_F,    \sigma_3 = \sqrt(0.3)\sigma_F$ ?
If no, what assumptions have to be made? Is there a term for splitting the variance according to the weights of the means? Are there other methods to apply instead? I am grateful for any help or further resources. Does anyone know any academic papers, where something like this is applied?
edit:
Maybe it helps to give some more context. I am forecasting shoe sales. I therefore do my forecasting on an aggregated set of data. I combine all sizes of the same model. After I get my results I thought I could split the mean and the standard deviation back to the size level. I want to do this according to the average size distribution for the specific category of shoes.
Answer:
From the given information above, is it possible to assume $$\sigma_1
= \sqrt{0.2\sigma_F},    \sigma_2 = \sqrt{0.5\sigma_F},    \sigma_3 = \sqrt{0.3\sigma_F}$$

No, not at all. There's no reason the variance should partition in the same way the mean does. In a normal distribution, the two are totally separate from each other.


Is it possible to calculate inversion and retrograde in guitar pro?

Question: I want to select a portion out of a guitar pro tab and i want to modify that with the inversion and the retrograde of that specific selection.
The inversion means that the order of the intervals based of the root note changes.
Retrograde means you play that portion backwards basically.
So is it possible to do it in Guitar Pro?
Answer: No sorry, none of those features are available in Guitar Pro.
There are not a lot of assistants to help creating tabs faster in GP, the only ones I found are for transposition (but only straight ones, by x semi-tones) and assistants for let rings and palm mutes.
But they are always looking for new feature ideas so you should suggest them (email@example.com). You won't have them soon though, if ever.


ASP.NET Core 3.0 - Model Binding not inferred?

Question: According to the documentation, complex types should automatically be handled as "FromBody" without the need to decorate the parameter with an attribute. For whatever reason it isn't working for me. What am I missing? Thanks.
ASP.NET Core 3, Content Type of the Header is "application/json".
Comment: You need `[FromBody]` specifically for json. If you pass data as `key=value&..` it's not needed
Comment: Do you have any idea why this happens? I have the same issue and I'm stuck with it.
Answer: From the Microsoft documentation

The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.

The complex types could automatically be handled as "FromBody" when you use the <code>[ApiController]</code> attribute on the controller .


Insert form fields into form

Question: i have a form inside an .inc file. That form i'm calling it inside a new form i'm making, using form_load_include, so far is working but its rendering the external form outside the new form. this is the code that does that:
<code><?php
// start form to create projects
function project_creator_form($form, &$form_state) {
    global $user;
    $uuid = $user->uid;

  form_load_include($form_state, 'inc', 'lc_core', 'location'); //here i call the form
  $renderable = drupal_get_form('location_form', $form_state);
  $location = render($renderable);
  print $location; //here i print the included form

  $form['u_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Identificador de Usuario'),
    '#size' => '6',
    '#attributes' => array('readonly' => 'readonly'),
    '#default_value' => $uuid,
    '#description' => "Este es su identificador de usuario, (no se puede modificar)",
    );

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Nombre de Proyecto'),
    '#required' => TRUE,
    '#description' => "Introduzca el nombre del proyecto.",
    );

    $form['p_type'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione tipo de proyecto'),
    '#options' => array(
      'Obra Nueva' => t('Obra Nueva'),
      'Adecuación' => t('Adecuación'),
      'Remodelacion' => t('Remodelación'),
      'Ampliación' => t('Ampliación'),
      'Refuerzo estructural' => t('Refuerzo estructural'),
      'Mantenimientos' => t('Mantenimientos'),
  ),
    '#required' => TRUE,
    '#description' => t('Seleccione el tipo de intervención a relizar.'),
    );

    $form['p_area'] = array(
    '#type' => 'textfield',
    '#title' => t('Area del proyecto (m2)'),
    '#required' => TRUE,
    '#description' => "Ingrese la cantidad de metros cuadrados (m2) del proyecto.",
    '#size' => '6',
    );

  $form['p_desc'] = array(
    '#type' => 'textarea',
    '#title' => t('Descripción'),
    '#description' => "Describa de que se trata el proyecto a ejecutar, puede especificar algunos detalles e información que considere necesaria.",
    '#rows' =>4,
    '#resizable' => FALSE,
    '#required' => TRUE,
    );

    $form['buttons'] = array(
    '#type' => 'submit',
    '#value' => t('Guardar proyecto'),
    );
  return $form;

}

function project_creator_form_submit($form, &$form_state) {

    db_set_active('civilproconstru'); //OPEN alter DATABASE.
    db_insert('project_info')
        ->fields(array(
        'u_id' => $form_state['values']['u_id'],
        'p_name' => $form_state['values']['p_name'],
        'p_type' => $form_state['values']['p_type'],
        'p_area' => $form_state['values']['p_area'],
        'p_ctry' => $form_state['values']['p_ctry'],
        'p_dept' => $form_state['values']['p_dept'],
        'p_city' => $form_state['values']['p_city'],
        'p_desc' => $form_state['values']['p_desc'],

        ))->execute();
$p_name=$form_state['values']['p_name'];
$loglink = l("Ver Proyectos", 'admin/lista_de_proyectos');
$msg= "El proyecto $p_name ha sido indexado, continue ingresando información del proyecto en $loglink o puede seguir indexando nuevos proyectos.";
drupal_set_message($msg);

db_set_active(); //CLOSE alter DATABASE.
}
</code>
And this is the output i'm getting:

Despite i'm printing inside the function that is creating the form drupal it's rendering outside of it...
HOW CAN I FIX THIS???? thanks for the help!...
Answer: Instead of printing the form when you load it, create a new form item of type markup and add your subform there as markup.
<code>$form['subform'] = array(
  '#type' => 'markup',
  '#markup' => $location,
);
</code>
This would fix the display order but your submit handler will need to handle the extra items.

Insert form fields into form


Will the Yamaha PM7X trumpet mute work stand-alone or do I need the Personal Studio SBX2 as well?

Question: I bought a PM7X trumpet mute, the one with a jack input for headphones. I tried pluging in headphones and I can't hear anything. I then looked for info, and I think I need an extra piece of hardware called "personal studio" that uses batteries.
Do I need that as well? I think I messed up by buying only the one thing.
Answer: You need the other half too :\
Clearest response from the Q&A section on Yamaha PM7X SILENT Brass Pickup Mute for Trumpet & Cornet

The PMX Series Silent Brass Pickup Mutes aren't designed for use
  without the SBX2 Personal Studio. If you don't already have an SBX2,
  we'd advise choosing the SB7X Silent Brass Kit for Trumpet and Cornet
  - this includes both the mute and Personal Studio:

It's probably cheaper to buy the pair as a kit, so if you can, I'd send the single piece back [In the EU you have a no-quibble right to return within 7 days if you bought it online.]
Comment: That's another reason to send back the first purchase.
Comment: I can't find the SBX2 without the mute on Amazon.
Answer: The socket on the mute is a microphone output jack not a headphone output jack, which is why you need the personal studio box in-between the mute and your headphones.
FWIW, I bought the Yamaha Silent Brass PM7 (mute) + ST7 (personal studio) for my trumpet years back, and although I still use the physical mute every day when I practise at home, I long ago stopped using the electronics part. Both PM7 and ST7 are now discontinued.
Part of the problem was one of expectation - I thought I could plug the mute and personal studio together and I'd sound like I was playing in front of one of those expensive studio capacitor microphones. The reality is far short of that, unfortunately.
Whilst the physical mute reduces the volume considerably, it's not 'Silent' by any stretch. And it does change the intonation and feel (back pressure) of the instrument, but considerably less than the other practice mute I have, a Denis Wick. Plus the mute makes the trumpet bell-heavy.
And the electronics in the belt pack were audibly hissy, and the reverb was too flattering - when you practice you need something forensic that doesn't hide your flaws. After all, you practise to eliminate those flaws so you need to be able to hear them.
And I found it a minor faff plugging everything together at the start of each practice session.
I'd suggest keep the mute, and don't buy the electronics as they're not worth the outlay.
Comment: what if I plug it into an audio interface? Will it work?


A metric between functions on $\mathbb{R}^2$

Question: I want to measure the distance between functions $f$ and $g$ (not necessarily continuous) on a bounded subset $M\subset\mathbb{R}^2$. I assume $f$ and $g$ are locally integrable and bounded on $M$. Then I define:
$$d(f,g)=\left|\iint_M \left(f(x,y)-g(x,y)\right)dxdy\right|$$
I believe that requiring locally integrability and boundedness is enough to show that $d$ is a metric. Clearly, $d(f,g)\geq 0$, $d(f,g)=d(g,f)$, and $d(f,g)=0$ if and only if $f=g$.
I am struggling to prove the triangle inequality. This question shows that Riemann integrability is not strong enough for a similar function to be a metric because distinct points can have zero distances. Given that I've assumed local integrability and boundedness, does the triangle inequality hold for $d$?
Comment: Have you looked at $L^p$-spaces?
Comment: You should consult the answers to the question that you are referring to. The problem there is not the triangle inequality but the condition that distinct points have positive distances.
Comment: @Justpassingby Thanks, fixed.
Answer: You need to put the absolute value sign within the double integral. It is well possible for the integral of $f-g$ to be zero without $f$ being equal to $g,$ even for the nicest imaginable continuous functions with compact support.
You also need to account for functions that are almost everywhere equal - in fact the usual procedure is to define a pseudometric, then factor out the zero distances by considering a metric on equivalence classes (modulo equality almost everywhere).
After that the triangle inequality follows from the triangle inequality for the usual absolute value metric on the real numbers and the fact that the integral of a nonnegative function is nonnegative.
As commenter abcdef pointed out, this metric space is a subspace of the complete normed vector space known by the standard name of $L^1(M).$
Comment: A function that is zero everywhere except at one point has distance zero from a function that is zero everywhere. Both are locally integrable (even globally Riemann integrable).
Comment: So $d$ is a pseudo-metric if the absolute values appear inside the integral, correct?
Comment: Yes it is. (If the absolute values are outside the integral, it is a pseudometric in a near-trivial way, with an excessive number of functions having zero distance to each other)
Comment: Can you also include an example case to demonstrate your point in the 2nd paragraph? I'm wracking my  brain to understand how local integrability doesn't account for that. I probably just don't understand local integrability well, but an example would definitely help.
Comment: Perhaps, then I am interested instead with functions that are piecewise continuous. If $f$ and $g$ are piecewise continous functions, then $d$ is a metric (not a pseudo metric), correct?


didSelectRowAtIndexPath not being called because of UITapGestureRecognizer

Question: I'm using UITapGestureRecognizer to end editing (because that's the workaround I found useful to end editing on input keyboards that have no other way to do so, like the Decimal Pad). The problem is that inside that viewController I have a tableView (the UITableViewDataSource and UITableViewDelegate of that tableView are set to the viewController) and the method didSelectRowAtIndexPath is not being triggered.
Code:
viewDidLoad {
   ...
   UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
   [self.view addGestureRecognizer:tapRecognizer];
   ...
}

- (void)tap:(UIGestureRecognizer*)gr {
   [self.view endEditing:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSLog(@"Help!");
}

I know the UITapGestureRecognizer is catching the selection, because if I comment out as following:
viewDidLoad {
   ...
   UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
   //[self.view addGestureRecognizer:tapRecognizer];
   ...
}

now the method the didSelectRowAtIndexPath finally triggers out.
I need help with some good practices on how to workaround the "endEditing" or how to forward the tap gesture to the tableView so that the didSelectRowAtIndexPath triggers out.
Thanks!
Answer: I assume that you haven't a tableView that takes all the screen, otherwise you can close the keyboard in didSelectRowAtIndexPath.
Any way, you can do your stuff and the pass the event to the next responder (that is kind of class UITableViewCell if there is, so if user tap on the tableView):
- (void)tap:(UIGestureRecognizer*)gr {
   [self.view endEditing:YES];

   UIResponder *responder = self;
    while (responder.nextResponder != nil){
        responder = responder.nextResponder;
        if ([responder isKindOfClass:[UITableViewCell class]]) {
            break;
        }
    }
    [responder touchesBegan:touches withEvent:event];
}

Comment: I really like your idea, but not working right now... I tried debugging it, and it never reaches the "break;" and that means it doesn't find a UITableViewCell. So I printed each responder in the while cycle before the if statement with this result:
Comment: Pur the result yes. Maybe is a UITableView class the responder
Comment: (Yeah sorry, accidentally entered the comment before putting the result)

My storyboard hierarchy is the following:
UINavigationController->UIViewController->UITableView (exactly, not 100% of screen)

Maybe the UITableView is inside the UIView... Not really sure :P
Comment: I wished comment would maintain form so the former one would me easier to read :(
Comment: So, probably you have to consider the `UIViewControllerWrapperView `. Did you try?


Convergence/absolute convergence of $\sum_{n=1}^\infty \left(\sin \frac{1}{2n} - \sin \frac{1}{2n+1}\right)$

Question:
Does the following sum converge? Does it converge absolutely?
$$\sum_{n=1}^\infty \left(\sin \frac{1}{2n} - \sin
 \frac{1}{2n+1}\right)$$

I promise this is the last one for today:
Using Simpson's rules:
$$\sum_{n=1}^\infty \left(\sin \frac{1}{2n} - \sin
 \frac{1}{2n+1}\right) = \sum_{n=1}^\infty 2\cos\frac{4n+1}{4n² + 2n}\sin\frac{1}{8n² + 4n}$$
Now, $$\left|2\cos\frac{4n+1}{4n² + 2n}\sin\frac{1}{8n² + 4n}\right| \leq \frac{2}{8n² + 4n}$$
hence by the comparison test, the series converges absolutely, and hence it also converges. Is this correct?
Comment: Absolutely yes.
Comment: Looks just fine to me...yet the cosine's argument's denominator should be $\;\frac{4n+1}{8n^2+4n}\;$ ...like the sine's, of course. +1
Comment: Can it be studied by? $$\sin \frac{1}{2n} - \sin
 \frac{1}{2n+1}=\frac{1}{2n}-\frac{1}{2n+1}+o\left(\frac{1}{n^2}\right)=\frac{1}{2n(2n+1)}+o\left(\frac{1}{n^2}\right)$$
Comment: You have to get explicit bounds on the coefficient of the little-oh term in order to prove convergence. I think it is enough if you use $x > \sin(x) > x-x^3/6$.
Answer: As an alternative, since:
$$\sin \frac{1}{2n} - \sin
 \frac{1}{2n+1}=\frac{1}{2n}-\frac{1}{2n+1}+o\left(\frac{1}{n^2}\right)=\frac{1}{2n(2n+1)}+o\left(\frac{1}{n^2}\right)$$
the series converges by limit comparison with:
$$\sum_{n=1}^\infty \frac{1}{2n(2n+1)}$$
Answer: It's simpler still with equivalents:
$$\sin \frac{1}{2n} - \sin \frac{1}{2n+1}=2\sin\frac1{4n(2n+1)}\underbrace{\cos\frac{4n+1}{4n(2n+1)}}_{\substack{\downarrow\\\textstyle1}}l\sim_\infty2\,\frac1{4n(2n+1)}\cdot 1\sim_\infty\frac1{4n^2},$$
which converges.
Answer: It may be easier to prove a stronger result: Suppose $f$ is increasing on $[0,b].$ Let $b\ge b_1 > a_1 > b_2>a_2  > \cdots \to 0^+.$ Then
$$\sum_{n=1}^{\infty}(f(b_n)- f(a_n)) <\infty.$$
Proof: The $n$th partial sum is
$$S_n = f(b_1)-f(a_1) + f(b_2)-f(a_2)+ \cdots + f(b_n)-f(a_n)$$ $$\le\, f(b_1)-f(b_2) + f(b_2)-f(b_3)+ \cdots + f(b_n)-f(b_{n+1})$$ $$ = f(b_1)-f(b_{n+1}) \le f(b_1) - f(0).$$
Thus the sequence $S_n,$ which is increasing, is bounded above. Therefore $S_n$ converges. By definition, this implies the series converges (absolutely of course).
Answer: Another proof: The partial sums are the same as the even partial sums of the alternating series$$\sum (-1)^n\sin \frac{1}{n}$$ which converges by the Leibniz test.
Comment: Nice observation.
Answer: Since $|\sin t|\le |t|$ we have
 $$|\sin(a)-\sin(b)|= 2\left|\sin\left(\frac{a-b}{2}\right)\cos\left(\frac{a+b}{2}\right)\right|\le |a-b|=  \frac{1}{2n}-\frac{1}{2n+1}\sim \frac{1}{n^2}$$
with $a= \frac{1}{2n}$ and $b=\frac{1}{2n+1}$
Hence, the series is absolutely convergent.
Answer: $$|\sin(\frac{1}{2n})-\sin(\frac{1}{2n+1})| = |cos(\xi)(\frac{1}{2n}-\frac{1}{2n+1})|$$
The above is followed by mean value theorem, then
$$|\sin(\frac{1}{2n})-\sin(\frac{1}{2n+1})| \leq \frac{1}{2n}-\frac{1}{2n+1}$$
So the series is absolutely convergent.


Storing Android system icons in my own app

Question: I've read that the references to the android system icons aren't fixed / could be changed and therefore it would be better to save them as a resource of your application. I once found a guide showing how to get the icons from the android repository but I can't find it again.
So my question is: How do I get the android system icons from the repository? Which path are they in? I am confused by all the git files and stuff on https://android.googlesource.com
Comment: Duplicate of http://stackoverflow.com/questions/6177462/fetching-of-non-public-android-images/6177572#6177572
Comment: Yes and no. The thread doesn't include the correct solution, the ldpi folder is missing (probably depends on where you got the source)
Comment: Yes you are right. But if you know about path of hdpi its not that difficult to get the path of mdpi or ldpi.
Answer: Android built-in system resources are stored with your Android SDK under
<SDK_path>/platforms/android-<API_version>/data/res

Since you want an icon, you should look into various drawable subfolders there and take the images you'd like to use.
Comment: oh great, didn't even know they are also on my hard disk :-) thank you very much!
Comment: update: unfortunately I am missing drawable-ldpi ): As far as I can remeber they were in the repo, but I don't have them on my HDD.
Comment: update 2: I found the link I mentioned: http://blog.vertile.com/nathan/2011/02/default-android-menu-icons-in-your-app/
Comment: @stefan.at.wpf Now link is http://nathan.vertile.com/default-android-menu-icons-in-your-app/


Does MS Word have an equivalent to ExecuteExcel4Macro

Question: Chip Pearson RIP documented a feature in Excel Application.ExecuteExcel4Macro(HiddenName).
This feature provides a nicely hidden application level space for addins to store information... have a look: http://www.cpearson.com/Excel/hidden.htm
Is there something similar available for MS Word?
I tried intellisense but there is nothing that starts with Application.Ex
Comment: no. you can use custom xml parts. read this :https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/customxmlparts-object-office here is a full read/write example http://ashuvba.blogspot.com/2018/01/embedding-and-retrieving-information-in.html
Comment: @cyboashu thanks for the suggestion. To be honest I'd not be surprised if the answer is NO. That said I already use custom xml parts but they are part of a specified document, becoming unavailable when that document is closed.
Comment: Other than what @cyboashu said, you'd need to write to a file, or to the Registry. Word does have System.PrivateProfileString (I think that's the name - I'm typing from memory on a mobile device) which Excel does not have :-)
Comment: @CindyMeister thank you for clarifying. I also use system profile string. Actually I use it to store a pointer to the Ribbon (for those times when things `End` unexpectedly); I was hoping something like _ExecuteWord4Macro_ could replace that workaround.
Answer: It would seem that the answer is No
Thank you cyboashu and Cindy Meister for your comments. The nice thing about ExecuteExcel4Macro is that it allows developers to place content in a very private space; apparently it is not possible (or extremely difficult) to read from this hidden space unless you know exactly what you're looking for, and it persists until all documents are closed.
There are various workarounds for MS Word:

ini file (system.PrivateProfileString) (not private, file persists when application closes)
customXML parts (tied to an instance of a document, dies with document)
document variables (tied to an instance of a document, dies with document)

Good as they are, these approaches are not quite what I was after (my question was more out of interest than actual need).

I had also thought of:
Creating an Excel object in Word and using the feature that way, but I think the same issue remains if things End suddenly. Similarly, I think a purpose built DLL would also fall victim to End.


polar Laplace equation solution:

Question: Question: $    \frac{\partial^2 u}{\partial r^2}
      + \frac{1}{r}\frac{\partial u}{\partial r}
      + \frac{1}{r^2}\frac{\partial^2 u}{\partial {\theta}^2} = 0,\:\:\:\: 0\leq r \leq 3 \:\:\:\: -\pi \leq \theta \leq \pi  $
with the boundary condition : $u(3,\theta) = 2 + \theta $ and the periodicity conditions : $u(r,\pi) = u(r,-\pi)$  and $u_{\theta}(r,\pi) = u_{\theta}(r,-\pi)$   :
My solution:
I assumed $u(r,\theta) = \psi(\theta)R(r) $
I solved for $\psi(\theta)$ and $R(r)$   and got $R(r)=c r^n$  and $\psi(\theta) = Asin(\lambda \theta) + Bcos(\lambda \theta)$
Solving the two periodicity condition just told me that $\lambda$ ( the separation constant) is $n$
My final answer is $u(r,\theta) = 2 + \sum\limits_{n=1}^\infty \frac{2}{n}(\frac{r}{3})^n (-1)^{n+1} sin(n\theta) + \frac{2}{3^n\pi n^2}((-1)^n - 1)cos(n\theta)$
But the final correct solution is : $u(r,\theta) = 2 + \sum\limits_{n=1}^\infty \frac{2}{n}(\frac{r}{3})^n (-1)^{n+1} sin(n\theta) $
so obviously the cosine coefficient (B) is $0$ according to one  of the conditions, but I don't know how or where that happens.
Comment: ${\rm u}\left(r = 3^{-},\theta\right) - 2 = \theta$ is an odd function of $\theta$. This symmetry vanishes out the $B_{n}$ coefficients since $\cos\left(n\theta\right)$ is an even function of $\theta$.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
The general solution, which is finite when $r \to 0^{+}$, has the form:
$$
{\rm u}\pars{r,\theta} = A_{0}\theta + B + \sum_{n = 1}^{\infty}
\bracks{A_{n}\sin\pars{n\theta} + B_{n}\cos\pars{n\theta}}\pars{r \over 3}^{n}\tag{1}
$$
When $r \to 3^{-}$, we'll have:
$$
2 + \theta = A_{0}\theta + B + \sum_{n = 1}^{\infty}
\bracks{A_{n}\sin\pars{n\theta} + B_{n}\cos\pars{n\theta}}\tag{2}
$$
$$
\int_{-\pi}^{\pi}\pars{2 + \theta}\,\dd\theta
=
\int_{-\pi}^{\pi}\braces{A_{0}\theta + B + \sum_{n = 1}^{\infty}
\bracks{A_{n}\sin\pars{n\theta} + B_{n}\cos\pars{n\theta}}}\,\dd\theta
$$
That yields $4\pi = 2\pi B\quad\imp\quad B = 2$ such that $\pars{2}$ is reduced to
$$
\pars{1 - A_{0}}\theta =\sum_{n = 1}^{\infty}
\bracks{A_{n}\sin\pars{n\theta} +B_{n}\cos\pars{n\theta}}\tag{3}
$$
This expression leads to:
\begin{align}
\int_{-\pi}^{\pi}\bracks{\pars{1 - A_{0}}\theta}\sin\pars{m\theta}\,\dd\theta &=\sum_{n = 1}^{\infty}
\int_{-\pi}^{\pi}\!\!\!\!\!\sin\pars{m\theta}\braces{%
\bracks{A_{n}\sin\pars{n\theta} +B_{n}\cos\pars{n\theta}}}\,\dd\theta\tag{4}
\\[3mm]
\int_{-\pi}^{\pi}\bracks{\pars{1 - A_{0}}\theta}\cos\pars{m\theta}\,\dd\theta &=\sum_{n = 1}^{\infty}
\int_{-\pi}^{\pi}\!\!\!\!\!\cos\pars{m\theta}\braces{%
\bracks{A_{n}\sin\pars{n\theta} +B_{n}\cos\pars{n\theta}}}\,\dd\theta\tag{5}
\end{align}
$\pars{4}$ and $\pars{5}$ yield:
\begin{align}
2\pars{1 - A_{0}}\
\overbrace{\int_{0}^{\pi}\theta\sin\pars{m\theta}\,\dd\theta}
^{\ds{{\pars{-1}^{m + 1} \over m}\,\pi}} &= 2A_{m}\int_{0}^{\pi}\sin^{2}\pars{m\theta}\,\dd\theta = \pi A_{m}
\\[3mm]
\pars{1 - A_{0}}\
\underbrace{\int_{-\pi}^{\pi}\theta\cos\pars{m\theta}\,\dd\theta}_{\ds{0}} &= 2B_{m}\int_{0}^{\pi}\cos^{2}\pars{m\theta}\,\dd\theta = \pi B_{m}
\end{align}
$\ds{\imp\quad A_{m}
     = 2\pars{1 - A_{0}}\,{\pars{-1}^{m + 1} \over m}
     \quad\mbox{and}\quad B_{m} = 0}$. $\pars{1}$ is reduced to:
$$
{\rm u}\pars{r,\theta}
=
A_{0}\theta + 2 + 2\pars{1 - A_{0}}\sum_{n = 1}^{\infty}{\pars{-1}^{n + 1} \over n}\,
\pars{r \over 3}^{n}\sin\pars{n\theta}
$$
where $A_{0}$ satisfies
$$
A_{0}\pars{-\pi} + 2 = A_{0}\pi + 2\quad\imp\quad A_{0} = 0
$$
$$
\color{#0000ff}{\large{\rm u}\pars{r,\theta}
=
2 - 2\sum_{n = 1}^{\infty}{\pars{-1}^{n} \over n}\,
\pars{r \over 3}^{n}\sin\pars{n\theta}}
$$

Also,
$$
{\rm u}\pars{r,\theta}
=
2 - 2\Im\overbrace{\sum_{n = 1}^{\infty}{\pars{-1}^{n} \over n}\,z^{n}}
^{\ds{\equiv\ \varphi\pars{z}}}\quad\mbox{where}\quad
z = {r \over 3}\,\expo{\ic \theta}
$$
$$
\varphi'\pars{z} = -\sum_{n = 1}^{\infty}\pars{-z}^{n - 1}
=
-\,{1 \over 1 - \pars{-z}}\,,\qquad\varphi\pars{0} = 0
$$
$$
\varphi\pars{z} = -\ln\pars{1 + z} = -\ln\pars{1 + {r \over 3}\,\cos\pars{\theta}
+ {r \over 3}\,\sin\pars{\theta}\ic}
$$
$$
\Im\varphi\pars{z} =
-\arctan\pars{r\sin\pars{\theta}/3 \over 1 + r\cos\pars{\theta}/3}
$$
$$
\color{#0000ff}{\large{\rm u}\pars{r,\theta}
=
2 + 2\arctan\pars{r\sin\pars{\theta}/3 \over 1 + r\cos\pars{\theta}/3}}$$

Notice that $\pars{~\mbox{when}\ r \to 3^{-}~}$ we'll have:
\begin{align}
\arctan\pars{r\sin\pars{\theta}/3 \over 1 + r\cos\pars{\theta}/3}
&\to\arctan\pars{\sin\pars{\theta} \over 1 + \cos\pars{\theta}}
=
\arctan\pars{1 - \cos\pars{\theta} \over \sin\pars{\theta}}
\\[3mm]&=
\arctan\pars{2\sin^{2}\pars{\theta/2} \over 2\sin\pars{\theta/2}\cos\pars{\theta/2}}
=
\arctan\pars{\sin\pars{\theta/2} \over \cos\pars{\theta/2}}
\\[3mm]&=
\arctan\pars{\tan\pars{\theta \over 2}} = {\theta \over 2}
\end{align}
such that $\ds{\lim_{r \to 3^{-}}{\rm u}\pars{r,\theta} = 2 + \theta}$.
Comment: @user120404 Don't you like exact answers ?.

polar Laplace equation solution:


Using Arrow Function with addEventListener gives an error: Uncaught TypeError: Cannot read property 'undefined' of undefined at onChangeHandler

Question:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JavaScript Essentials</title>

  <select id="mySelect" name="cars">
   <option disabled selected='selected'>Select your option</option>
   <option value="Lamborghini Aventador">Lamborghini Aventador</option>
   <option value="Ferarri LaFerarri">Ferarri LaFerarri</option>
   <option value="McLaren LP">McLaren LP</option>
   <option value="Audi R8">Audi R8</option>

  </select>

djfh

sdjfdf

djshf

  Also try to dynamically add the pics below here

I am trying to make use of the arrow functions but it gives me an error. It doesn't give an error when I define my function like this: function onChangeHandler() {...} why is that?
I've also tried this:
options.addEventListener('change',onChangeHandler.bind(this); But it also doesn't work. What is the correct method?
Also arrow functions aren't hoisted right?

    var select = document.getElementsByName('cars');

    const options = document.getElementById("mySelect");
    var picture = document.getElementById("picture");

    options.addEventListener('change',onChangeHandler);

    onChangeHandler = () => {
     var value = this.options[this.selectedIndex].value
     console.log(value);
     picture.innerHTML = '';

     var img = document.getElementsByName("image")[0].style.cssText='width: 800px; height: 400px';
    }
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JavaScript Essentials</title>

  <select id="mySelect" name="cars">
   <option disabled selected='selected'>Select your option</option>
   <option value="Lamborghini Aventador">Lamborghini Aventador</option>
   <option value="Ferarri LaFerarri">Ferarri LaFerarri</option>
   <option value="McLaren LP">McLaren LP</option>
   <option value="Audi R8">Audi R8</option>

  </select>

Comment: Reading [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is always useful.
Answer: You need to assign a value to onChangeHandler before you try to read that value by passing onChangeHandler to addEventListener.
Assignments are not hoisted.
Comment: It looks like the order is correct in OP's real code, the error message comes from insde the function (`this.options[this.selectedIndex].value`).
Answer: Look at the error message

Cannot read property 'addEventListener' of null

your options variable is null. are you sure you have an element with id mySelect and have waited for the page to load before executing your javascript?
Comment: The options variable is null because the live demo is missing its HTML (which makes it a terrible live demo). I don't think that is the error the question is asking about.
Comment: Then use a comment. Don't use answers to comment about problems that aren't what the question is about.
Comment: I'm aware. I was socratically guiding OP to write better questions
Comment: that's a fair point
Comment: Sorry, I added the HTML. But someone suggested an answer from a different post so I'll take a look at that.


Is the following use of indices correct?

Question: Is the following use of indices correct? A vector $\langle x_i, x_{i+1},...,x_{i+k}\rangle$ is given. For  every such vector a function is defined through
$$\mu=\frac{\sum_{j=0}^k I_A(x_{i+j})}{k+1}\,,$$
where $I_A$ is the indicator function of some set A. Is it mathematically correct notation? In particular the use of $i+j$ as sub index.
Comment: Yes, it is correct. But as you're doubting, you can also choose to use:
\begin{equation}
\mu = \frac{\sum_{j = i}^{i+k} I_A(x_j)}{k+1}
\end{equation}
Comment: Perfectly correct.
Comment: Thanks. Which is more correct --- to use $x_{i+j}$ or double indexing $x_{i_j}$ and again sum over $j$?
Comment: Double indexing is incorrect, as the elements of the vector are 1-dimensional.
Comment: $x_{i_j}$ can be used, but this if you define $i_j:=i+j$. However... why writing this complex $i_j$ instead of its definition $i+j$? Don't make things complex. Good mathematics is characterized by simplicity.
Comment: I was afraid to use as a sub index sum of two natural numbers --- $i+j$ --- because I have not seen it before...
Comment: Well. The first step is meeting it. The next is getting accustomed and familiar to it, especially by using it and discovering its profits. Good luck. :)
Answer: As mentioned in the comments above, the notation is correct.
Comment: An upvote to this answer is needed to remove this question from the unanswered list.


extract repeated phrase from text file Python

Question: I have a huge text file of conversation (block of text), i want to extract repeated phrases (more than one word) to another text file, sorted in order of frequency
input:
text block, single line,Word Wrapped
output:
 I don't know 7345
 I want you to 5312
 amazing experience 625

I'm looking for a python script

i have tried this script, but i could get only single word , sorted from highest to lowest occurence
    from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')
import collections
import pandas as pd
import matplotlib.pyplot as plt

# Read input file, note the encoding is specified here
# It may be different in your text file
file = open('test2.txt', encoding="utf8")
a= file.read()

# Stopwords
stopwords = set(line.strip() for line in open('stopwords.txt'))
stopwords = stopwords.union(set(['mr','mrs','one','two','said']))

# Instantiate a dictionary, and for every word in the file,
# Add to the dictionary if it doesn't exist. If it does, increase the count.
wordcount = {}

# To eliminate duplicates, remember to split by punctuation, and use case demiliters.
for word in a.lower().split():
    word = word.replace(".","")
    word = word.replace(",","")
    word = word.replace(":","")
    word = word.replace("\"","")
    word = word.replace("!","")
    word = word.replace(""","")
    word = word.replace("'","")
    word = word.replace("*","")
    if word not in stopwords:
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1

# Print most common word
n_print = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n_print))
word_counter = collections.Counter(wordcount)
for word, count in word_counter.most_common(n_print):
    print(word, ": ", count)

# Close the file
file.close()

# Create a data frame of the most common words
# Draw a bar chart
lst = word_counter.most_common(n_print)
df = pd.DataFrame(lst, columns = ['Word', 'Count'])
df.plot.bar(x='Word',y='Count')

Comment: Can you show us an example of what you've tried? SO is a place to help with code and issues, not to request someone does work for you..
Comment: This type of problems is generally solved by exploiting the functionalities present in regex module. Provide an example of input and desired output to get a complete answer
Comment: I propose to read about Markov chains to get an idea on how to tackle this task.
Answer: I think you can use nltk.ngrams from nltk package.
text = 'I have been I have I like this I have never been.'

ngrams = tuple(nltk.ngrams(text.split(' '), n=2))

ngrams_count = {i : ngrams.count(i) for i in ngrams}

Out:
 {('I', 'have'): 3, ('have', 'been'): 1, ('been', 'I'): 1,
('have', 'I'): 1, ('I', 'like'): 1, ('like', 'this'): 1,
('this', 'I'): 1, ('have', 'never'): 1, ('never', 'been.'): 1}

And then you can save it with pandas/txt/json etc.
You can change n in nltk.ngrams and your ngrams will be another length.
It can be modify to this:
text = 'I have been I have I like this I have never been.'
lenght = [2, 3, 4]
ngrams_count = {}
for n in lenght:
    ngrams = tuple(nltk.ngrams(text.split(' '), n=n))
    ngrams_count.update({' '.join(i) : ngrams.count(i) for i in ngrams})

df = pd.DataFrame(list(zip(ngrams_count, ngrams_count.values())),
                  columns=['Ngramm', 'Count']).sort_values(['Count'],
                                                           ascending=False)

Out:
                Ngramm  Count
0               I have      3
1            have been      1
26   this I have never      1
25    like this I have      1
24       I like this I      1
23    have I like this      1
22       I have I like      1
21       been I have I      1
20    have been I have      1
19       I have been I      1
18    have never been.      1
17        I have never      1
...

Now we can enter n and then make a sorted dataframe. If you want, you can save it as df.to_csv('file_name.csv') or can take a head before that - df.head(10).
For use this solution you should install nltk and pandas.
Comment: can you change the code to list only the instances where the phrase is repeated atleast twice
Comment: @SyedOmer it's easy to change. Just add `df = df[df.count > 1]`. Pandas is a very good library. As example you also can extract ngrams with count 10 as `df[df.count == 10]`.
Comment: TypeError: '>' not supported between instances of 'method' and 'int'
Comment: @SyedOmer I'm sorry. Change to `df = df[df.Count > 1]`. Because we have a column named `'Count'`. But `count` is function of dataframe = )
Comment: do you know how to change it to C? the script is perfect but its taking way too long.
Comment: @SyedOmer Unfortunately, I don't
Answer: You can just use str.count() and count the phrase in the string
s = 'vash the vash the are you is he where did where did'

print('the how: {}'.format(s.count('where did')))
print('vash the: {}'.format(s.count('vash the')))

the how: 2
vash the: 2


Problema com ponto flutuante Python 3

Question: Estou escrevendo um algoritmo onde incremento variáveis float em 0.2, porém, depois de alguns incrementos ao invés de incrementar 2.2 para 2.4, por exemplo, o programa incrementa para 2.4000000000000004
Já li sobre esse "bug" do Python (eu sei que não é bug, mas não consegui encontrar uma palavra melhor), mas não consigo encontrar a referência para estudar uma solução. Segue o algoritmo:
J1, J2, J3, I = 1.0, 2.0, 3.0, 0

while I <= 2:
    print('I={} J={}'.format(I, J1))
    print('I={} J={}'.format(I, J2))
    print('I={} J={}'.format(I, J3))
    J1 += 0.2
    J2 += 0.2
    J3 += 0.2
    I += 0.2

E a saída:
Comment: Se for só questão de exibição, você pode formatar a saída com `{:.2}`, limitando, assim, apenas duas casas decimais. Se for utilizar para operações matemáticas, utilize o módulo `decimal` como já respondido.
Comment: Relacionada: https://pt.stackoverflow.com/q/219211/64969
Comment: Nessa resposta eu exibo um exemplo de cálculo com uma classe de números que compartilha o mesmo problema dos números de ponto flutuante: https://pt.stackoverflow.com/a/272376/64969
Comment: Relacionada: https://pt.stackoverflow.com/q/273728/64969
Comment: Leia [Aritmética de ponto flutuante: problemas e limitações](https://docs.python.org/pt-br/3/tutorial/floatingpoint.html).
Answer: Não é um bug do Python, e sim um problema inerente de como computadores representam ponto flutuante.
>>> 0.1 + 0.3
0.4
>>> 0.1 + 0.2
0.30000000000000004

Felizmente, o Python nos oferece um jeito simples de resolver o problema: o módulo decimal.
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.2')
Decimal('0.3')

É importante notar que usando o Decimal, devemos iniciar o número como uma string. Senão, ele interpreta o argumento como ponto flutuante e temos o mesmo problema:
>>> Decimal(0.1) + Decimal(0.2)
Decimal('0.3000000000000000166533453694')

Essa página mostra a reação de diversas linguagens ao problema.
Comment: Outra sugestão é deixar o numero em questão em float mesmo, e cuidar do arreondamento só no momento de exibir o número (exibir = qualquer saída: tela, arquivo, HTML, etc...)
Answer: Embora a resposta do @Pedro tenha sido de grande ajuda, encontrei a resposta com exemplos e tudo mais na SO em inglês. Aqui está o link
Meu código, agora funcionando perfeitamente, ficou da seguinte maneira a quem interessar:
from decimal import Decimal as D

J1, J2, J3, I = D(1.0), D(2.0), D(3.0), D(0)

while I <= 2:
    print('I={} J={}'.format(I, J1))
    print('I={} J={}'.format(I, J2))
    print('I={} J={}'.format(I, J3))
    J1 += D("0.2")
    J2 += D("0.2")
    J3 += D("0.2")
    I += D("0.2")

Answer: Como Pedro disse, não é um bug do Python.
Se você sabe que o incremento sempre será de 0.2 (ou cualquer número fixo), pode simplesmente guardar os valors multiplicados por 5 (o inverso multiplicativo do incremento) como integros e dividir por 5.0 quando precisa do valor como float. Isso evite problemas com sumar erros de arredondamento.

Como foi pedido, um exemplo simples:
J1, J2, J3, I = 5, 10, 15, 0

while I <= 10:
    print( 'I={} J={}'.format(I/5.0, J1/5.0) )
    print( 'I={} J={}'.format(I/5.0, J2/5.0) )
    print( 'I={} J={}'.format(I/5.0, J3/5.0) )
    J1 += 1
    J2 += 1
    J3 += 1
    I += 1

Com um resultado de:
I=0.0 J=1.0
I=0.0 J=2.0
I=0.0 J=3.0
I=0.2 J=1.2
I=0.2 J=2.2
I=0.2 J=3.2
I=0.4 J=1.4
I=0.4 J=2.4
I=0.4 J=3.4
I=0.6 J=1.6
I=0.6 J=2.6
I=0.6 J=3.6
I=0.8 J=1.8
I=0.8 J=2.8
I=0.8 J=3.8
I=1.0 J=2.0
I=1.0 J=3.0
I=1.0 J=4.0
I=1.2 J=2.2
I=1.2 J=3.2
I=1.2 J=4.2
I=1.4 J=2.4
I=1.4 J=3.4
I=1.4 J=4.4
I=1.6 J=2.6
I=1.6 J=3.6
I=1.6 J=4.6
I=1.8 J=2.8
I=1.8 J=3.8
I=1.8 J=4.8
I=2.0 J=3.0
I=2.0 J=4.0
I=2.0 J=5.0

Provavelmente seria melhor encapsular o código para fazer a multiplicação de divisão dentro de uma classe, mas não conheço Python tanto para dar um exemplo bom disso.
Tambem já ouvi falar de classes que guardem frações em vez de pontos flutuantes para guardar (quase) qualquer número racional sem perder precisão.
Eu acho que a classe Decimal do Python já faz uma coisa semelhante ao que eu estou descrevendo, mas quarda um número integro e guarda um poder de dez para fazer a divisão (ou multiplicação). Assim eu acho que Decimal é parecido com ponto flutuante, mas com poderes de dez em vez de poderes de dois.

Problema com ponto flutuante Python 3


VBA script not saving first mail

Question: first of all i'll say that i'm not an expert in coding but i do have a basic understanding.
i have a script that saves all unread mails as txt and marks them as read.
It works fine, but when i set up a rule with it to run every time i get a mail from a specific person it doesn't effect the first mail.
 Example: i get a mail, the script runs but doesn't save anything (as long as there is no other mail from the same person and isn't Unread).
then i get a second mail from the same person, the script will run and save the previous mail but not the latest one.
Here a sample of the code:
Public Sub TestEnvMacro()
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objMailbox = objNamespace.Folders("your email goes here")
Set objFolder = objMailbox.Folders("Inbox")
Set colItems = objFolder.Items

Dim NewMsg
Dim dtDate As Date
Dim sName As String

Const OLTXT = 0

Pause (5)

For Each objMessage In colItems.Restrict("[Unread] = True")
      If objMessage.UnRead = True Then
         Pause (5)
         Set NewMsg = objMessage
         sName = NewMsg
         dtDate = NewMsg.ReceivedTime
         sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
         vbUseSystem) & Format(dtDate, "-hhnnss", _
         vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & ".txt"

         NewMsg.SaveAs "G:\" & sName, OLTXT
         NewMsg.UnRead = False
    End If
Next

End Sub

I didn't include the pause Sub since it's pretty self explanatory what it does, also i've had a problem with getting the script to show up in the "Rules" so I added this Sub:
Public Sub SaveAsTextMod(msg As MailItem)
Dim strID As String
Dim olNS As NameSpace
Dim olMail As MailItem
strID = msg.EntryID

Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)

Call TestEnvMacro

Set olMail = Nothing
Set olNS = Nothing

End Sub

Comment: Wow thanks Eugene Astafiev, that worked like a charm.
Answer: When you create a rule to apply for incoming emails, the mail item is passed as a parameter to the macro sub. There is no need to search for unread emails in Outlook. You just need to define the function with a MailItem parameter do the required actions against that objects.
Public Sub SaveAsTextMod(msg As MailItem)

    Dim dtDate As Date
    Dim sName As String

     dtDate = msg.ReceivedTime
     sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
     vbUseSystem) & Format(dtDate, "-hhnnss", _
     vbUseSystemDayOfWeek, vbUseSystem) & "-" & msg.Subject & ".txt"

     msg.SaveAs "G:\" & sName, OLTXT
     msg.UnRead = False

End Sub

You may find the Getting Started with VBA in Outlook 2010 article helpful.

VBA script not saving first mail