text:
Q: SAPPER - MikroORM: Circular dependency, Cannot access 'Person' before initialization I am unable to make relationships work with MikroORM
I keep getting this error
ReferenceError: Cannot access 'Person' before initialization
    at Object.<anonymous> (/Users/mauroinsacco/Documents/tests/svelte/my-site/__sapper__/dev/server/server.js:74:31)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

This is the source code where the problem lies, they rely on each other

import { Connection, IDatabaseDriver, MikroORM } from "@mikro-orm/core";
import { Entity, Property, OneToOne, PrimaryKey } from "@mikro-orm/core";

export class BaseEntity {
  @PrimaryKey()
  id!: number;
}

@Entity()
export class Account extends BaseEntity {
  @Property()
  username: string;

  @OneToOne(() => "Person", "account")
  person: Person;
}

@Entity()
export class Person extends BaseEntity {
  @Property()
  name!: string;

  @OneToOne("Account")
  account: Account;

  constructor() {
    super();
  }
}

export let orm: MikroORM<IDatabaseDriver<Connection>>;
export async function initDatabase() {
  orm = await MikroORM.init({
    entities: [Person, Account],
    dbName: "postgres",
    type: "postgresql", // one of `mongo` | `mysql` | `mariadb` | `postgresql` | `sqlite`
    clientUrl: "connectionstring", // defaults to 'mongodb://localhost:27017' for mongodb driver
  });
}

This is the generated build/devbuild output
class BaseEntity {
}
__decorate([
    core.PrimaryKey(),
    __metadata("design:type", Number)
], BaseEntity.prototype, "id", void 0);

let orm;
let Account = class Account extends BaseEntity {
};
__decorate([
    core.Property(),
    __metadata("design:type", String)
], Account.prototype, "username", void 0);
__decorate([
    core.OneToOne(() => "Person", "account"),
    __metadata("design:type", Person) // <------------ IT CRASHES HERE, PERSON IS NOT DEFINED
], Account.prototype, "person", void 0);
Account = __decorate([
    core.Entity()
], Account);
let Person = class Person extends BaseEntity {
    constructor() {
        super();
    }
};
__decorate([
    core.Property(),
    __metadata("design:type", String)
], Person.prototype, "name", void 0);
__decorate([
    core.OneToOne("Account"),
    __metadata("design:type", Account)
], Person.prototype, "account", void 0);
Person = __decorate([
    core.Entity(),
    __metadata("design:paramtypes", [])
], Person);

I'm using the default sapper rollup configuration and default typescript configuration with added     "experimentalDecorators": true, "emitDecoratorMetadata": true, "esModuleInterop": true
I cant seem to find any solution online, I've no clue if its a sapper problem or rollup problem and have no idea what to touch, any help is highly appreciated

A: I think you need to decorate the BaseEntity with @Entity()

A: The local variable Person is defined below then it is used.
    __metadata("design:type", Person) // <------------ IT CRASHES HERE, PERSON IS NOT DEFINED
...
    let Person = class Person extends BaseEntity {
        constructor() {
            super();
        }
    };

Also you can try to use types IdentifiedReference<Person> and IdentifiedReference<Account>.
See https://mikro-orm.io/docs/entity-references/#what-is-identifiedreference


text:
Q: Using sql data base in c# class Library

I have a problem, that I can't reference SQL Server database project in a class library project to manage database (insert, delete and more...).
I want to build "book store system" solution with uwp project, class library project that holds base classes and derives classes, and another class library that holds manager class with functions that manage the system.
I tried to create new SQL Server database project and succeeded to access a database that I created in SSMS. But when I tried to reference it from the class library by using Publish command it didn't work.
I didn't use actually code but I tried to use the buttons
I expected that it will open me the option to call reference

A: I Think you can use EF with code first application or database first style if you like to manage database by your self and easily deal with context classes that mapping database tables you can find full example here

redpajama_set_name: RedPajamaStackExchange


text:
Q: If a finite group has exactly $2$ maximal subgroups, then it is $3$-cyclic Prove that if a finite group has exactly $2$ maximal subgroup, then it is $3$-cyclic.
I tried using the same method as here:
Finite groups with exactly one maximal subgroup
but it leads nowhere.

A: For finite groups, this below is maybe a partial answer, but provides you with some insight. You probably know that a group with only one maximal subgroup must be cyclic of prime power order. A group with exactly two maximal subgroups must also be cyclic and has precisely two different primes dividing its order:
Proposition If $G$ is a group with exactly two maximal subgroups, then it must be nilpotent.
Proof Let $M$ be one of the two maximal subgroups. We have to show that $M$ is normal in $G$. Since $M$ is maximal, we have either $G=N_G(M)$ (equivalent to $M \lhd G)$ or $M=N_G(M)$. In the latter case, and because $|G:N_G(M)|$ is exactly the number of conjugates of $M$, we have $|G:N_G(M)|=2=|G:M|$. And it is well-known that a subgroup of index $2$ is normal.
Note In this proposition one can replace "two" by $p$, where $p$ is the smallest prime dividing the order of $G$.
Proposition There exists no $p$-group which has exactly two maximal subgroups.
Proof Let $G$ be a $p$-group with exactly two maximal subgroups, and let $\Phi(G)$ be its Frattini subgroup. Then $G/\Phi(G)$ has exactly two maximal subgroups, namely the canonical images of the maximal subgroups of $G$. But $G/\Phi(G)$ is an elementary abelian group say of order $p^n$. If $n=1$ then $G/\Phi(G)$ is cyclic, implying $G$ is cyclic and a cyclic $p$-group has a unique maximal subgroup. Hence $n \geq 2$ and we can find an $N \lhd G$ with $G/N \cong C_p \times C_p$. But then $G/N$ has $p+1$ maximal subgroups and the preimages of those in $G$ yield a contradiction.
Corollary If $G$ is a group with exactly two maximal subgroups, then $G \cong C_{p^{a}q^{b}}$, with $p$ and $q$ two different primes.
For this $G$ has to be nilpotent, say $G=P_1 \times \cdots \times P_k$, the direct product of its different Sylow subgroups. It is not difficult to see that the number of maximal subgroups is the sum of the number of maximal subgroups of each of the factors. By the previous propositions and the fact that a $p$-group with only one maximal subgroup must be cyclic, the corollary now follows. The last proposition also implies the following.
Proposition Let $p$ be an odd prime. There exists no $p$-group which has exactly three maximal subgroups.
Proof Let $M_1, M_2$ and $M_3$ be the maximal subgroups. These all have index $p$ and are normal. Put $N=M_1 \cap M_2$, and assume $N=1$. Then we have $G=M_1M_2$, so $|G|=p^2$, which group has $p+1$ maximal subgroups. So $p+1=3$, a contradiction. Observe that $N \subseteq M_3$, for if not, then $G/N$ has exactly two maximal subgroups, which is impossible by the previous proposition. So $N=M_1 \cap M_2 \cap M_3=\Phi(G)$. Hence $G/N \cong C_p \times \cdots \times C_p $ and this group has $\frac{p^n-1}{p-1}=3$ maximal subgroups (with $n \geq 2$). It follows that $p=2=n$ again a contradiction.

Note that $V_4$ and also $Q_8$, the quaternion group of order $8$, have exactly $3$ maximal subgroups. What remains is to classify all $2$-groups with exactly $3$ maximal subgroups.


text:
Q: Pipe Broken with PipeInputStream with kubernetes-client exec() I'm using the kubernetes-client to try copy a directory from a pod, but I'm doing something wrong with the input stream from stdout.  I get a java.io.IOException: Pipe broken exception when it tries to read().  I'm pretty sure that no data flows at all.  I'm half wondering if I need to read the InputStream on a separate thread or something?
The stream is created like this:
public InputStream copyFiles(String containerId,
                             String folderName) {

    ExecWatch exec = client.pods().withName(containerId).redirectingOutput().exec("tar -C " + folderName + " -c");

    // We need to wrap the InputStream so that when the stdout is closed, then the underlying ExecWatch is closed
    // also. This will cleanup any Websockets connections.
    ChainedCloseInputStreamWrapper inputStreamWrapper = new ChainedCloseInputStreamWrapper(exec.getOutput(), exec);

    return inputStreamWrapper;
}

And the InputStream is processed in this function
void copyVideos(final String containerId) {
    TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
    TarArchiveEntry entry;
    boolean videoWasCopied = false;
    try {
        while ((entry = tarStream.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }
            String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
            testInformation.setFileExtension(fileExtension);
            File videoFile = new File(testInformation.getVideoFolderPath(), testInformation.getFileName());
            File parent = videoFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(videoFile);
            IOUtils.copy(tarStream, outputStream);
            outputStream.close();
            videoWasCopied = true;
            LOGGER.log(Level.INFO, "{0} Video file copied to: {1}/{2}", new Object[]{getId(),
                    testInformation.getVideoFolderPath(), testInformation.getFileName()});
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, getId() + " Error while copying the video", e);
        ga.trackException(e);
    } finally {
        if (!videoWasCopied) {
            testInformation.setVideoRecorded(false);
        }
    }

}

The InputStream Wrapper class is just there to close the ExecWatch at the end once the InputStream is closed, it looks like this:
private static class ChainedCloseInputStreamWrapper extends InputStream {

    private InputStream delegate;
    private Closeable resourceToClose;

    public ChainedCloseInputStreamWrapper(InputStream delegate, Closeable resourceToClose) {
        this.delegate = delegate;
        this.resourceToClose = resourceToClose;
    }

    @Override
    public int read() throws IOException {
        return delegate.read();
    }

    public int available() throws IOException {
        return delegate.available();
    }

    public void close() throws IOException {
        logger.info("Shutdown called!");
        delegate.close();

        // Close our dependent resource
        resourceToClose.close();
    }

    public boolean equals(Object o) {
        return delegate.equals(o);
    }

    public int hashCode() {
        return delegate.hashCode();
    }

    public int read(byte[] array) throws IOException {
        return delegate.read(array);
    }

    public int read(byte[] array,
                    int n,
                    int n2) throws IOException {
        return delegate.read(array, n, n2);
    }

    public long skip(long n) throws IOException {
        return delegate.skip(n);
    }

    public void mark(int n) {
        delegate.mark(n);
    }

    public void reset() throws IOException {
        delegate.reset();
    }

    public boolean markSupported() {
        return delegate.markSupported();
    }

    public String toString() {
        return delegate.toString();
    }

}

A: Turns out I had the tar command wrong, so it was causing a failure and the stdout PipeInputStream was dead locking. I managed to find a workaround for the deadlock. But the main reason for the failure was that I forgot to tell tar to actually do something! I at least needed a "." to include the current directory.


text:
Q: How can I programmatically pass log-in credentials to site Following this answer to a similar question, I am trying to scrape a site that provides the content I need to retrieve directly after logging-in:
import requests
creds = {'username_key': 'username_value', 'pw_key': 'pw_value'}
url = 'https://mollybet.com/beta/trade'
response = requests.post(url, data=creds)

But I cannot find out from the log-in page's html what the username's and password's key values need to be and the status_code I keep getting in the response object is 405 (Not Allowed).

*

*Is it obvious from the tags in the html code what the key values need to be or am  I completely off in the way I am trying to resolve this issue?

I also tried logging-in with selenium (chromedriver) and, again, I cannot I identify the input field elements. For example, although this code does locate the element I am targeting in the log-in page
from selenium import webdriver
webdr_browser = webdriver.Chrome()
webdr_browser.get(url)
soup = bs.BeautifulSoup(webdr_browser.page_source,'lxml')

>>> soup.find('input', class_='jss91 jss76')
<input aria-invalid="false" class="jss91 jss76" type="text" value=""/>

But when I am trying to locate the element in order to click it:
>>> webdr_browser.find_element_by_class_name('jss91 jss76')
Traceback (most recent call last):
...
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".jss91 jss76"}

Other find_element_by_ methods also fail so,

*Any idea why?

A: I would suggest just using selenium to fill out the info for you. I've never really trusted searching by class unless it was truly necessary. I figure they are likely to change and don't tell you much about the structure. But since the page is fairly simple, searching by tag name seems to do the trick.
from selenium import webdriver
driver = webdriver.Chrome()

driver.get('https://mollybet.com/beta/login')

# Locate input and password fields
fields = driver.find_elements_by_tag_name('input')
fields[1].send_keys('USERNAME')
fields[2].send_keys('PASSWORD')

# Click the submit button
driver.find_element_by_tag_name('button').click()

From here, you can use selenuim or BeautifulSoup to parse the page contents going forward.
The issue you were having was with trying to locate on two classes at the same time. You need to modify your selector to
driver.find_element_by_class_name('jss91.jss76')

But make sure you pay attention to the elements because both the user name and password fields have the same two classes.
for field in fields:
    print(field.get_attribute('class'))

# jss91 jss76
# jss91 jss76 jss94 jss79

To do it with requests, I monitored the traffic as I sent the request to the site. It looks like the form submits to https://mollybet.com/s/weblogin/. The payload sent was {'username': "user", 'password': "pass", 'lang': "en"}. So in theory, the following should work, but I'm getting a 400 error. I also tried to add the headers from the original request. If the credentials were wrong, it should be a 401 error, but perhaps it would work with your login.
headers = {
    'Host': 'mollybet.com',
    'Connection': 'keep-alive',
    'Content-Length': '49',
    'Origin': 'https://mollybet.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',  # noqa
    'content-type': 'application/json',
    'Accept': '*/*',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'cors',
    'Referer': 'https://mollybet.com/beta/login',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
}

response = requests.post(
    'https://mollybet.com/s/weblogin/',
    data={'username': "user", 'password': "pass", 'lang': "en"},
    headers=headers,
    verify=False)


text:
Q: Finding the mean length of an array in a string Python I am a student VERY new to python and I have no idea how to write a function that calculates the mean length of an array in a string. Any help or guidance would be greatly appreciated.
We are given
def mean_length(lst):

The tests are
assert mean_length(['fee','freed',free']) == 4
assert mean_length(['alpha', 'beta', 'gamma', 'delta', 'epsilon']) == 5.2
assert mean_length([]) == 0

I have tried
def mean_length(lst):
    x = lst.count(''.join(lst))
    y = int(3)
    mean = x / y
    return mean

A: There's already a function in the statistics library that can do this just map len to the list so you supply it the lengths.
l = ['fee','freed','free']
statistics.mean(map(len, l))

A: The answer is just a one-liner:
def mean_length(l):
    return len(''.join(l))/len(l)

Here we are joining all the string in the list and counting the total number of characters and finally dividing it by the total number of elements in the list, thereby, giving us mean length of words.


text:
Q: Error updating custom Salesforce object using Talend ETL - Status Code: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY I am trying to update the name of one of the Salesforce Custom Objects, and using Talend Data Integration tool for the same. The action on the salesforce Object is 'Update' and I only have two columns specified in this schema, Id & Name. There are around 1500 records in the Salesforce Object and getting this error when it tries to update the 203rd record.
Getting the below error when I run the Talend Job to update the Name:

Exception in component tSalesforceOutput_1  java.lang.Exception:
  RollupRefresh_Deal: execution of AfterUpdate
caused by: System.NullPointerException: Attempt to de-reference a null
  object
Class.Utilities.combineAccountStatistics: line 160, column 1
  Trigger.RollupRefresh_Deal: line 61, column 1
at
  org.talend.salesforce.SforceManagementImpl.update(SforceManagementImpl.java:416)
    at
===================================================
Status Code: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
RowKey/RowNo:  ID# of the 203rd record.
Message: RollupRefresh_Deal: execution of AfterUpdate
caused by: System.NullPointerException: Attempt to de-reference a null
  object
Class.Utilities.combineAccountStatistics: line 160, column 1
  Trigger.RollupRefresh_Deal: line 61, column 1

I tried to filter out NULL ID's/ Name records, but still get the same error as above.
Thanks in advance
Sr

A: This error doesn't appear to have anything to do with Talend or ETL as such, and it needs to be fixed in your code - not your ETL or your incoming data.
RollupRefresh_Deal is an Apex trigger in your Salesforce organization. You can use the stack trace information in the error report to review the code (line 61 of RollupRefresh_Deal) to determine why your code is trying to dereference an object that is null.
Once you identify the issue, this is a good opportunity to write some unit tests for RollupRefresh_Deal to make sure it doesn't happen again by covering the relevant code and testing with null values.
You can, as you've found, turn off the "all or nothing" setting to allow the other records to go through. However, this error will continue happening until the root cause - the bug in that Apex trigger - is found and fixed.


text:
Q: How to input text into tinceMCE editior using selenium/webdriver I am trying to automatically insert some text using Selenium/Webdriver into a text box created using tinymce
The text box is not a plain vanilla textbox so following is not working:
System.out.println("Finding text input element");
    WebElement element =  inputWebDriver.findElement(By.xpath("//html/body/div/form/div/div/div[2]"));  //not working
    //WebElement element = inputWebDriver.findElement(By.tagName("form"));  // not working
    //WebElement element = inputWebDriver.findElement(By.id("tinymce"));  // not working

    System.out.println("Entering something in text input");
    element.sendKeys("Test text");

like it is working fine with plain text box https://code.google.com/p/selenium/wiki/GettingStarted
Here is screenshot how the textarea element's location is seen in browser's element tab:
http://imageshack.com/a/img812/9341/1zau.png
Note: Through selenium, I am not able to get any element inside the 'embedded' html doc ( i get element not found error)
I have found a python equivalent to get done above, but, still looking to get it done in my java code:
browser.execute_script("tinyMCE.activeEditor.setContent('{}')".format(testTextVar))

A: There are multiple ways of doing it. Here's an article you might want to have a look.
Test WYSIWYG editors using Selenium WebDriver
Code snippets below are not tested, only provide the logic in Java.

*

*Send keys directly. Same as Richard's answer above.

inputWebDriver.switchTo().frame("input-data_ifr");
WebElement element = inputWebDriver.findElement(By.cssSelector("body"));
element.sendKeys("Send keys");

*

*Set innerHTML

inputWebDriver.switchTo().frame("input-data_ifr");
WebElement element = inputWebDriver.findElement(By.cssSelector("body"));
(JavascriptExecutor)driver.executeScript("arguments[0].innerHTML = '
Set text using innerHTML
'", element);

*

*Use TinyMCE's native API

// no need to switch iframe
(JavascriptExecutor)driver.executeScript("tinyMCE.activeEditor.setContent('
Native API text
 TinyMCE')");

A: The element is inside of an iframe.
You'll need to use:
inputWebDriver.switchTo().frame("input-data_ifr");
WebElement element = inputWebDriver.findElement(By.id("tinymce"));
System.out.println("Entering something in text input");
element.sendKeys(Keys.CONTROL + "a");
element.sendKeys("Test text");

Then use the following to switch back to the top of the document when you're finished.
inputWebDriver.switchTo().defaultContent();

A: From @user1177636's answer above, I found that --in the Firefox driver-- I could only get the "Use TinyMCE's native API" option to work. However, that really was not what I wanted because that would overwrite everything in the textbox with the string provided to that API method. That was detrimental for me since I had a bunch of content in the editor I did not want to lose.
However, I am happy to inform you that simply using activeEditor.selection.setContent gets it to simply insert some text instead of overwriting all of it. Yeap, that extra "selection" is what I needed.
So, here is my solution, which is just a slight variation on @user1177636's tinyMce API on above and which prepends the word "changed! ":
((JavascriptExecutor)driver).executeScript("tinyMCE.activeEditor.selection.setContent('changed! ')");

Do not forget that you'll need this import for that to work
import org.openqa.selenium.JavascriptExecutor;

Hope this helps someone else who might have the same predicament I had and saves them some time (not having to hunt as long as I did to discover this).


text:
Q: Sphinx deleted documents I have this problem for a long time, and can't find a solution.
I guess this might be something everybodys faced using Sphinx, but I cnanot get any
usefull information.
I have one index, and a delta.
I queried in a php module both indexes, and then show the results.
For each ID in the result, I create an object for the model, and dsiplay main data for
that model.
I delete one document from the database, phisically.
When I query the index, the ID for this deleted document is still there (in the sphinx
result set).
Maybe I can detect this by code, and avoid showing it, but the result set sphinx gaves me
as result is wrong. xxx total_found, when really is xxx-1.
For example, Sphinx gaves me the first 20 results, but one of this 20 results doesn't
exists anymore, so I have to show only 19 results.
I re-index the main index once per day, and the delta index, each 5 minutes.
Is there a solution for this??
Thanks in advance!!

A: Maybe this fits better to my needs, but involves changing the database.
http://sphinxsearch.com/docs/current.html#conf-sql-query-killlist

A: What I've done in my Ruby Sphinx adapter, Thinking Sphinx, is to track when records are deleted, and update a boolean attribute for the records in the main index (I call it sphinx_deleted). Then, whenever I search, I filter on values where sphinx_deleted is 0. In the sql_query configuration, I have the explicit attribute as follows:
SELECT fields, more_fields, 0 as sphinx_deleted FROM table

And of course there's the attribute definition as well.
sql_attr_bool = sphinx_deleted

Keep in mind that these updates to attributes (using the Sphinx API) are only stored in memory - the underlying index files aren't changed, so if you restart Sphinx, you'll lose this knowledge, unless you do a full index as well.
This is a bit of work, but it will ensure your result count and pagination will work neatly.

A: I suppose you could ask for maybe 25 results from sphinx and then when you get the full data from your DB just have a limit 20 on the query.


text:
Q: How download package from unpkg or add in dependencies unpkg package? problem
I try install ipfs from unpkg site.

*

*https://www.unpkg.com/browse/ipfs@0.36.3/
Project
It is React project.
But i can't download this package or install in package.json
Main page unpkg
On main page write this

unpkg is a fast, global content delivery network for everything on npm. Use it to quickly and easily load any file from any package using a URL like:
unpkg.com/:package@:version/:file

Solution
I try install

*

*package.json

"ipfs": "unpkg.com/:ipfs@0.36.3"

*

*module

import IPFS from 'https://unpkg.com/ipfs@0.36.3';

it is not work.
How can i download from unpkg page this package ?

A: As per documentation, you either need to install the package globally using following command
$ npm install -g ipfs

Or install ipfs-core as lighter package using following command.
$ npm install ipfs-core


text:
Q: Kivy AttributeError: 'super' object has no attribute '__getattr__' (Tried all previous solutions) This Has To One OF The Most Annoying Errors In Python That Have So Many Solutions Depending On The Question
My Files

Main.py

# imports
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager

# Defining Screen, ScreenManager And App Classes:
class MainScreen(Screen):
    pass

class ShortCuts(Screen):
    pass

class WindowManager(ScreenManager):
    pass

# Kivy Lang Builder Packed As A Variable
BLD = Builder.load_file("KV_FILE.kv")

class OnlineClassMacros(App):

    # Initializing The App
    def __init__(self, **kwargs):
        super(OnlineClassMacros, self).__init__(**kwargs)

    # Defining The App By Referencing The Packed Kivy.Lang.Builder Variable Created At The Start Of The .py File
    def build(self):
        return BLD

    @staticmethod
    def Get():
        query = BLD.ids.SearchEngine.text

        print(query)

# ToDo: Monetize The >>Online Class Macros<< Application By Using KivMob

# MainLooping The Application Using  [if __name__ == "__main__":]
if __name__ == "__main__":
    OnlineClassMacros().run()

KV_FILE.kv

# Importing Our Function.py As A Python Module Into Kivy-Lang\

#######################################################
#:import redirect Function.redirect
#######################################################

# Pre-Styling Widgets
<Label>
    halign: 'center'
    valign: 'center'
    background_color: '0', '.4', '.3', '.4'
<Button>
    halign: 'center'
    valign: 'center'
    background_color: "0", ".1", ".1", ".8"

# Configuring The Screens And The Screen Manager
WindowManager:
    MainScreen:
    ShortCuts:

# Building All The Classes In Our "Main.py" File

<MainScreen>:
    name: "MainScreen"

    canvas.before:
        Rectangle:
            size: self.size
            pos: self.pos
            source: "Images/background 2.png"
    BoxLayout:
        orientation: "horizontal"
        BoxLayout:
            size_hint: .2,1
            orientation: "vertical"
            Button:
                text: "Google\nDocs"
                on_release: redirect("https://www.docs.google.com")
            Button:
                text: "Google\nSlides"
                on_release:
                    redirect("https://slides.google.com/u/0/h")
            Button:
                text: "Gmail"
                on_release:
                    redirect("https://www.gmail.com")
            Button:
                text: "Google\nClassroom"
                on_release:
                    redirect("https://classroom.google.com/u/0/")
        BoxLayout:
            size_hint: .6,1
            BoxLayout:
                orientation: "vertical"
                TextInput:
                    size_hint: 1, .2
                    multiline: True
                    hint_text: "Search here"
                    background_color: 1,1,1,.78
                    id: SearchEngine
                GridLayout:
                    cols: 3
                    Button:
                        text: "Google Scholar\nSearch"

                    Button:
                        text: "Wikipedia\nSearch"
                        on_release:
                            app.Get()
                    Button:
                        text: "Google\nSearch"
                    Button:
                        text: "RefSeek\nSearch"
                    Button:
                        text: "Microsoft Academic\nSearch"
                    Button:
                        text: "Hyper Search"
                        background_color: 1,0,0,.99
        BoxLayout:
            size_hint: .2,1
            orientation: "vertical"
            Button:
                text: "Google\nSpreadSheets"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")
            Button:
                text: "MicroSoft\nTeams"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")
            Button:
                text: "OutLook"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")

<ShortCuts>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.pos
            source: 'Images/ Background 3.png'

Error:
C:\Users\mayan\AppData\Local\Programs\Python\Python39\python.exe "C:/Online Class Macros ;)/Main.py"
[INFO   ] [Logger      ] Record log in C:\Users\mayan\.kivy\logs\kivy_21-06-13_7.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.9.4 (tags/v3.9.4:1f2e308, Apr  6 2021, 13:40:21) [MSC v.1928 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\mayan\AppData\Local\Programs\Python\Python39\python.exe"
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.0.0 - Build 10.18.10.5059'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) HD Graphics'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 0
[INFO   ] [GL          ] Shading version <b'4.00 - Build 10.18.10.5059'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <16>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [GL          ] Unpack subimage support is available
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Base        ] Start application main loop
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "kivy\properties.pyx", line 861, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'SearchEngine'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:\Online Class Macros ;)\Main.py", line 46, in <module>
     OnlineClassMacros().run()
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\base.py", line 308, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\mayan\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Online Class Macros ;)\KV_FILE.kv", line 70, in <module>
     app.Get()
   File "C:\Online Class Macros ;)\Main.py", line 36, in Get
     query = BLD.ids.SearchEngine.text
   File "kivy\properties.pyx", line 864, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

Process finished with exit code 1

This error has happened to me before and I solved it but as I said the answer is question-dependent.
I Would Really Appreciate it If No One Delete My Question Saying It's a Duplicate.

A: The cryptic error message is of little help, but the stack trace shows that the error occurs in the line:
query = BLD.ids.SearchEngine.text

The reason that this line fails is that you are trying to access an id (SearchEngine) that does not exist in the BLD object. The BLD object is the root of your kv, which is the WindowManager, but the SearchEngine id is defined in the <MainScreen>: rule. So the fix is to access that id through the correct object:
def Get():
    app = App.get_running_app()  # get a refrence to the running App
    main_screen = app.root.get_screen('MainScreen')  # get a reference to the MainScreen
    query = main_screen.ids.SearchEngine.text  # now use the id

    print(query)

Note that the documentation says:

When the kv file is processed, weakrefs to all the widgets tagged with
ids are added to the root widget's ids dictionary.

That documentation is incorrect. The ids are actually added to the base object of the rule that contains the id, not to the root widget of the kv file.


text:
Q: C# UWP WebView NavigationStarting - Get Request Post data I'm wondering if I can get POST data of the WebView request in UWP.
I'm using WebView_NavigationStarting event to get information about URI, but I have custom page which sent some information back to the app inside the POST request. Ideally I want to do this:
    private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        Stream receiveStream = args.Request.InputStream;
    }

But args doesn't have Request, only Uri. I was able to do this trick in iOS and Android (iOS, for example, pass the whole request to the similar event so why it's possible). Is there way to do so in UWP C# app ?

A: You can try listen to WebResourceRequested, the args contains both request and response object. It should be in args.request.Content. But so far I cannot access those content too.
private void WebView_WebResourceRequested(WebView sender, WebViewWebResourceRequestedEventArgs args)
{
    if (args.request.Method.Method == "POST")
    {
        HttpStreamContent content = (HttpStreamContent) args.request.Content;
        var contentBuffer = content.ReadAsBufferAsync().GetResults();
        byte[] buffer = contentBuffer.ToArray();
    }
}


text:
Q: Cursor in the middle of a textarea box? In a very simple HTML form I've created, I've asked the user to provide additional details and have coded this section as:
<textarea rows="1" cols="50" wrap="physical" name="comments">

</textarea>

Any idea why the cursor starts off at the middle of this box? Well, it's not directly at the middle, but it's definitely not at the start (top left) corner of the box. I see a lot of solutions here and they all require Javascript to correct this. Is there a way to do this with just html?

A: What happens when you change it to:
<textarea rows="1" cols="50" wrap="physical" name="comments"></textarea>

I think it's not starting at the beginning because you've got whitespace inside the tag.

A: The reason that this happens is because you have white space in between the <textarea> tag. Try this
<textarea rows="1" cols="50" wrap="physical" name="comments"></textarea>

A: That generally happens when we enter a space between two opening and closing "textarea" tag for readibility.
i.e your opening <textarea> tag and Closing </textarea> tags are on different lines or there are some white spaces between them.

A: That does sound strange. Have you looked in firebug to see what CSS effects it? The only thing that comes to mind is that it's under the influence of text-align: center


text:
Q: Node handlebars adds extra text node before rendered view I have the following issue:
When rendering a view in a layout with handlebars, the engine adds an extra text node before the rendered view body

{{{body}}}

results in

"
[empty text node here]
                      "
<rendered view>

That empty text node has its own height and breaks my CSS margins and paddings. Note that if I put the view HTML directly in the layout without using handlebars templating, there is no text node and everything is fine.
Any ideas why is this happening and how to solve it?

A: @leoyoo answer is the right one.
I was about to post same question and found this.
On Chrome, source shows that white space character as seen below (red dot):

...and stringifies to
I'm on Visual Studio and this is the default setting when files are saved:

When I change it to UTF-8 without signature (as seen below) that whitespace character dissapears.

On Visual Studio you do: File>>Save fileName.ext As and then drop-down next to Save button.

A: I think I found the reason, please check your partial view file, whether there is BOM inserted in file, some editors will insert this in file with UTF-8, UTF-16 and UTF-32 format. so if you are using UTF-8, just remove the BOM will be good.


text:
Q: how to find the radix complemnt for integer in java? I need a function that could find the radix complement for any given integer
public static int findRadixComplement(int num) {
    // write your code here
    int count = 0, a = 10;
    int numy = num;
    while (numy != 0) {
        numy /= 10;
        ++count;
    }
    int rad = (int) Math.pow(a, count) - num;
    return rad;
}

I assume the problem is when I try to input "10", it will output "90"
I also try to use for loop instead of math.pow, it didn't work
there isn't much time left before the deadline

A: To get radix complement, you need to add 1 to rad.


text:
Q: IOS Orientation with FlipViewController and a master view I use two ViewControllers. A MainView and a FlipViewController. The MainView contains a bunch of buttons and controls, and a graphics display, and the FlipView contains the settings.
The MainView loads a different XIB depending on orientation to facilitate the variety of buttons I support and the graphics screen. This allows great flexibility to lay things out differently. The project was created initially before the StoryBoarding features were added to Xcode.
The normal usecase is I start in Portrait mode on the MainView, and then touch a button that rotates the FlipView into view. I do things on the FlipView (configure aspects of the program) and then commit the change, which rotates me back to the MainVIew. All is good so far.
The problem happens when I enter the FlipView and then rotate the device so the FlipView takes a different orientation. Lets say I rotate Portrait to Lanscape. Then return from the FlipView to the MainView. At this point, the MainView does not know about the Rotation that FlipView performed. So it is still showing the MainView in Portrait with the Portrait XIB.
The MainView's willRotateToInterfaceOrientation never gets called after returning from the FlipViewController. Thus it never finds out about the orientation change, and consequently, retains the incorrect XIB for that orientation. Here is a sample of the orientation handler in willRotateToInterfaceOrientation...
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration    {

// if portrait, load the portrait XIB for Pad or Phone

if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {

    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

        [[NSBundle mainBundle] loadNibNamed:@"MainViewiPad" owner:self options:nil];

    }else{

        [[NSBundle mainBundle] loadNibNamed:@"MainView" owner:self options:nil];

    }

    [self viewDidLoad];

    intorient = 1;
 else.... handle Landscape...

So I have been experimenting with the viewWillAppear routine trying to find ways to cause the MainView to find out about the rotation and perform it in a system-wise manner. But so far I do not know how to cause the system to work in this manner. I suspect I will have to generate code that forces a reload of the correct orientation when viewWillAppear gets called. But this is not working correctly, because I never seem to get the change loaded in time, and it seems incorrect to try to reload a new XIB from within the viewWillAppear message.
Any help in understanding this behavior is much appreciated.

A: OK. I found the issue here. The problem was that the information about rotation was not getting sent back to the MainView. This is easily handled by having the FlipView (who will be reacting to these orientation messages) resend the message down to the MainView. My code inside the FLipView was not doing anything before for the rotation messages (it was auto handling the rotation), but now I add the handler in the FlipView like this:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
        [mainView willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

Which is essentially passing the message for rotation back to the MainView. This works because the MainView does not go away when the FlipView is opened. It stays in back, and can still respond to the messages it gets.
One thing to notice is that I have a reference to mainView in the code above. You will need to pass this in after the FlipView alloc-init to ensure you can make this call if required. This means adding a new property to the MainView class in the Flipview code.
I do something like this in MainView prior to opening the FlipView:
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];

controller.delegate = self;
controller.mainView = self;
controller.lastIndexPath = lastIndex;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];

Hope this helps others having this type of trouble. I noticed the same behavior when I opened a web viewer modally as well. I used the same technique there to handle the same type of issue.


text:
Q: Applying "not" across brackets in natural deduction for propositional logic I have a quick question. How can I simplify
$\neg(\neg P \lor (\neg Q \land \neg R))$ to $P \lor \neg(\neg Q \land \neg R))$
in natural deduction for propositional logic, and is this even allowed? What kinds of proofs would I have to use?
Thanks in advance.

A: Here is a proof in a Fitch-style proof checker to show how one can start with $\neg(\neg P \lor (\neg Q \land \neg R))$ as a premise and derive $P \land (Q \lor R)$. This will show how to approach applying not across sentences within brackets or parentheses. Also this may be what the OP intended to derive.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


text:
Q: Why does a closure passed to flat_map without a type annotation compile, while one with an annotation does not? Why does this, with no type annotation on the closure, compile?
fn transform(input: &Vec<Vec<String>>) {
    input.iter().flat_map(|words| words.iter());
}

But this doesn't?
fn transform(input: &Vec<Vec<String>>) {
    input.iter().flat_map(|words: &Vec<String>| words.iter());
}

Is the inferred type not &Vec<String>? Or do I need to annotate the lifetime too, as this seems to be about the closure not living long enough?
The error for in the latter snippet is
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
 --> src/main.rs:2:55
  |
2 |     input.iter().flat_map(|words: &Vec<String>| words.iter());
  |                                                       ^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 2:48...
 --> src/main.rs:2:49
  |
2 |     input.iter().flat_map(|words: &Vec<String>| words.iter());
  |                                                 ^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:2:49
  |
2 |     input.iter().flat_map(|words: &Vec<String>| words.iter());
  |                                                 ^^^^^
note: but, the lifetime must be valid for the method call at 2:4...
 --> src/main.rs:2:5
  |
2 |     input.iter().flat_map(|words: &Vec<String>| words.iter());
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so type `fn(std::slice::Iter<'_, std::vec::Vec<std::string::String>>, [closure@src/main.rs:2:27: 2:61]) -> std::iter::FlatMap<std::slice::Iter<'_, std::vec::Vec<std::string::String>>, std::slice::Iter<'_, std::string::String>, [closure@src/main.rs:2:27: 2:61]> {<std::slice::Iter<'_, std::vec::Vec<std::string::String>> as std::iter::Iterator>::flat_map::<std::slice::Iter<'_, std::string::String>, [closure@src/main.rs:2:27: 2:61]>}` of expression is valid during the expression
 --> src/main.rs:2:5
  |
2 |     input.iter().flat_map(|words: &Vec<String>| words.iter());
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A: The compiler is worried that your code can produce dangling pointers. When you leave off the type annotation, the compiler correctly infers the lifetime of the inner references in relation to the outer references.
However, when you annotate the type and don't explain to the compiler how the lifetimes of the internal references relate to the outer references (that is, how the words: &Vec<String>/internal references relate to the input: &Vec<Vec<String>>/outer references), the compiler freaks out.
The easy fix, is to let the compiler know that the inner references live at least the same lifetime as the outer one:
fn transform<'a>(input: &'a Vec<Vec<String>>) {
    input.iter().flat_map(|words: &'a Vec<String>| words.iter());
}

Hopefully that makes sense. In Rust, a reference can't outlive what it references. In the eyes of the compiler, your input reference might go away before your words references do (which is bad because words references items inside input). So if you're not going to let the compiler infer the lifetimes, you need to be explicit about it.


text:
Q: Meaning of "would that I might forget him"
"Would that I might forget him," Ned said bluntly.
  — A Song of Ice and Fire

Does the sentence in quotes mean, "I would forget him if I could"?

A: Welcome to EL&U!
Yes, it's a dated way of saying,

"I'd forget him if I could."

Perhaps a little less dated, but still quite rare, is the expression "would to God," as in

"Would to God I could forget him,"

which means, I wish I could forget him [but I can't, even with God's help!].
Or,

"Would to God I could get him out of my head," Ned said bluntly.


text:
Q: How can I learn to read formulas with greek symbols? I suppose maybe it's because I don't know the keywords to google for, but I can't find any sources on how to read those formulas you see on wikipedia, like this for instance:
Erlang Distribution
I've searched in the math world and computer science world. It feels like it is assumed that we're supposed to understand it out of thin air. Beginner lessons seem scarce.
So far I know how sigma works. And that upside-down shape that is used as the half-life logo is called lambda. But what the heck is it trying to say?? Why is there a semi-colon in the function, etc..
If there is a book on this stuff I'd buy it in an instant. It is probably very basic stuff but I never had experience in theoretical math or even know where to look.
Does anyone know what this subject is called, and what to google for?

A: Formulas with this symbols usually are statistics or probability notations.
Greek letters (e.g. θ, β) are commonly used to denote unknown parameters (population parameters).
Greek letters used in mathematics, science, and engineering
you can find info here
Notation in probability and statistics
here

A: Check out the resources list here: http://en.wikipedia.org/wiki/Greek_alphabet

A: I would say your best bet is still searching in Google (or other search engine, whatever float your boat) about the specific formula you are trying to learn. Sometimes a symbol may be used in different meaning in different formula.
Anyway, there is a good resource in here that explained a lot of math symbols, not just the Greek symbol.
Some link that may interest you here and here.

A: I think the colon in alt.: \scriptstyle \theta \;=\; \frac{1}{\lambda} > 0\, scale (real) in the box in Wikipedia is just saying that there is an alternative definition, in which you specify theta rather than lambda, and in that definition what is called theta is the reciprocal of lambda in the other definition.
I once complained to a much better mathematician than I was that I came unstuck with formulas with some of the weirder greek letters in because I couldn't write them recognisably in my handwriting (which is bad enough for the latin alphabet). He said a lot of the people he knew simply said "let x be funny-squiggle-thing" and rewrote with sensible letters. I really wish I'd thought of that.
In general, letters in weird alphabets behave pretty much like sensible letters, at least in the sort of thing you are pointing at. It's done as a sort of type-checking - usually all of the letters pinched from some particular foreign language are related in some way - e.g. all parameters. Unfortunately that doesn't hold exactly in the Wikipedia example you quote, where two of the greek letters stand for functions - one is definitely the Gamma function. I suspect the other is http://en.wikipedia.org/wiki/Digamma_function, but I'm not really sure.

A: First, find a Greek alphabet (upper and lower case) to refer to, so that you can at least call lambda by it's name.  No one starts out knowing automatically what the various Greek characters are, not even Greeks.
Second, Read the actual article, usually either the character is defined (as lambda happens to be in the Wikipedia page you references) or it's standard nomenclature (in which case you've done the right thing by looking for a basic article on the function in question-- I do this all the time so don't feel bad.)  Or, as a third option, it's a crappy paper.  Happens sometimes.  It's kind of a pain, though, since you can't just do a text search on the lambda character in a PDF.
(Someone educate me on that if I'm wrong....)
Third, try to pick out which unfamiliar symbols are variables (like lambda) and which are operators (like sigma, and it's helpers.)  It's the operators that can sometimes cause real trouble.  A variable is just a name for something, but operators come freighted with more meaning, more rules, and more syntax.  It's not always obvious which symbols are operators, either.
Finally, and specifically for computer science, a good introductory book (college freshman/sophomore level) on discrete math will hopefully treat most of the basic notations and operators to at least get your feet on the ground.  Nowadays, you kids and your newfangled internet might be able to get something similar from Udacity, Edx, Course RA, or the Khan Academy.
Basically, it's a lot of hard work, especially on your own, but you're already doing most of the right things.


text:
Q: $\int_{0}^{1}{(1-x)(1-2x^{\phi})+\phi(x-x^{\phi})\over (1-x)^2}\cdot{\left(1-x^{\phi}\over 1-x\right)^{1\over \phi}}\mathrm dx=\phi^{\phi}$ How can we show that?

$$\int_{0}^{1}{(1-x)(1-2x^{\phi})+\phi(x-x^{\phi})\over (1-x)^2}\cdot{\left(1-x^{\phi}\over 1-x\right)^{1\over \phi}}\mathrm dx=\phi^{\phi}\tag1$$
  Where $\phi$;Golden ratio

This integral look too complicated. I try and make a $u=1-x$ still not simplified
$$\int_{0}^{1}{u[1-2(1-u)^{\phi}]+\phi[1-u-(1-u)^{\phi}]\over u^2}\cdot\left[1-(1-u)^{\phi}\over u\right]^{1\over \phi}\mathrm du$$
$$\int_{0}^{1}{\phi-{u\over \phi}-(1-u)^{\phi}(2u+\phi)\over u^2}\cdot\left[1-(1-u)^{\phi}\over u\right]^{1\over \phi}\mathrm du$$
Simplifed $(1)$:
$$\int_{0}^{1}{1+{x\over \phi}+x^{\phi}(2x-\phi{\sqrt{5}})\over (1-x)^2}\cdot\left({1- x^\phi}\over 1-x\right)^{1\over \phi}\mathrm dx=\phi^{\phi} \tag2$$
I have no idea where to go from here.

A: Using the relation $\phi - 1 = 1/\phi$, we find that
\begin{align*}
&\int_{0}^{1} \frac{(1-x)(1-2x^{\phi})+\phi(x-x^{\phi})}{(1-x)^2}\cdot\left(\frac{1-x^{\phi}}{1-x}\right)^{1/\phi} \, \mathrm{d}x \\
&= \int_{0}^{1} \left( 2 - \frac{\phi^2}{1-x^{\phi}} + \frac{\phi}{1-x} \right) \left(\frac{1-x^{\phi}}{1-x}\right)^{\phi} \, \mathrm{d}x \\
&= \bigg[ x \left(\frac{1-x^{\phi}}{1-x}\right)^{\phi} \bigg]_{0}^{1} \\
&= \phi^\phi.
\end{align*}
As a corollary, we have
$$ \int \frac{(1-x)(1-2x^{\phi})+\phi(x-x^{\phi})}{(1-x)^2}\cdot\left(\frac{1-x^{\phi}}{1-x}\right)^{1/\phi} \, \mathrm{d}x = x \left(\frac{1-x^{\phi}}{1-x}\right)^{\phi} + C. $$

Here is my line of reasoning that led to this solution:

*

*I tried to simplify the integrand so that it minimizes the amount of cancellation as well as mimics partial fraction decomposition.

*Now, the integrand in the second line looks similar to what we obtain when we apply the logarithmic differentiation
$$ \frac{d}{dx}\left(\frac{1-x^{\phi}}{1-x}\right)^{\phi} = \left( \frac{\phi}{1-x} - \frac{\phi^2 x^{\phi-1}}{1-x^\phi} \right) \left(\frac{1-x^{\phi}}{1-x}\right)^{\phi}. \tag{1} $$
Although this is not exactly the same as what we want, it hints that we might actually compute the antiderivative.

*Playing a little bit, we find that
$$ \frac{d}{dx}\frac{(1-x^{\phi})^{\phi}}{(1-x)^{\phi-1}} = \left( -2 -\frac{\phi^2 x^{\phi-1}}{1-x^{\phi}} + \frac{\phi^2}{1-x^{\phi}} \right) \left(\frac{1-x^{\phi}}{1-x}\right)^{\phi}. \tag{2}$$
Bingo! $\text{(1)} - \text{(2)}$ gives exactly what we want and we are done.


text:
Q: Incorporating scalar covariate in regression I have a set of subjects, each associated with a data vector $\mathbf{y}$ and a scalar covariate $z$. To each $y$ corresponds an $x$, and I wish to regress $y$ on $x$ across subjects: domain knowledge tells me that this association exists. To my surprise, on top of this association, I observe strong differences between subjects (see examples below).

When I run lm(y ~ x) by subject (this was just a quick approximation), I find that the coefficient of $x$ correlates very well with that subject's $z$ value.
Hence my question: is there a way of running the regression across all subjects incorporating $z$ among the predictors?
I am confused as to how that would actually be implemented in R: per subject, $x$ and $y$ are both vectors while $z$ is a scalar, so lm(y ~ x + z) wouldn't fly. Not only that, but $z$ is more or less a multiple of the slope of y ~ x. How can this information be encoded, with an eye towards polynomial expansions?


text:
Q: Multi-Tenant physical isolation We have a multi-tenant Asp.Net MVC 4 web application with each tenant having its own repository of files (a folder in the file-system). We took the shared database, shared schema approach and we identify tenants by their subdomain.
What is the best way to ensure that a tenant can only access his repository folder and no other folder in the file-system? we check it in the application business logic, but what if we make a mistake...?
When running the application, all tenants run under the same user (which is defined in IIS application pool).
Do we need to serve each tenant as a separate user - using impersonation? do we need to impersonate each time a request is made to the server - in order to fill it?
I've heard this has performance drawbacks and is not the prefered way, but what is?
We also have a windows service which fills requests in the background (for all tenants), sent to it through MSMQ. Does this service also needs to change its identity every time it gets a request?
Edit:
In addition, we need a type of isolation which if someone uploads a file infected with a virus - it will affect only this tenant's files, and not every tenant on the server. We use ant-virus software, but we need this separation also in case the antivirus software will not identify the virus.
Thank you

A:
all tenants run under the same user

If each tenant has a separate IIS Web App and identity (whether app pool or "normal" user), then you can use NTFS access control.
These does not depend on having all users having a local or domain user accounts on the web servers to allow impersonation (and this NTFS access control).
However it will add memory overhead on the servers of course – each tenant will have their own worker process.

[…]MSMQ. Does this service also needs to change its identity every time it gets a request?

I'm not sure you can do impersonation based on MSMQ messages, I would expect this not to work (MSMQ messages do not carry the necessary identity information).
Anything shared is going to need to be implemented to check all access: depending on the nature of the processing this may be more difficult (eg. if client requests can be something of the order "get information from the file" for an arbitrary file: the service would need to do the access checks1).

1 There are Win32 functions that will do the heavy lifting.


text:
Q: Not passing a value for a placeholder in tensorflow, why isn't it allowed? I had 3 models that use the same input but produce 3 unique outputs (1 classifier, 2 regression). 2 of the 3 I combined into 1 model with 2 loss functions and saw a significant improvement in accuracy/RMSE.
I'm trying to combine the 3rd loss function into the model, so I have 1 model with 3 loss functions that share many parameters.
The 3rd loss function only applies to half the data though. I tested standardizing the labels to 0-mean-unit-variance and using 0 for the labels where they don't apply to loss function C, but that biased results towards 0 in some cases.
I'm now experimenting with alternating optimization on loss functions A & B together with a batch from the full dataset, vs all 3 loss functions A, B, & C with a batch appropriate for loss C (and A&B). In the context of my problem this is logical to do.
My Question:

*

*Tensorflow requires all placeholders that are defined in the graph to be passed in. However, I'm not using that tensor in this particular optimization step. Is this expected behavior? And should I just pass in a dummy variable to appease TF here? I wonder if I'm missing an important detail.

A: The dependency was with tensorboard, I had a summary operation on all loss functions, forcing them to be executed.
I split out my summary operations into groups using tf.add_to_collection() to gather different summary ops, then used a for loop to add them to the list of tensors to process as appropriate.
It was that and one other dependency that was just a bug that I found. @Sygi and @Fake are correct, you shouldn't need to pass in a value that isn't used in a particular computation just because it exists in the graph.


text:
Q: Defining a triangle with vertices $a$, $b$, $c$ by $t_1a+t_2b+t_3c$, where $0\leq t_1, t_2, t_3\leq 1$ and $1=t_1+t_2+t_3$. Why does this work? For $a$, $b$, $c$ in $\mathbb{R}^2$, I know that the set
$$A=t_1a+t_2b+t_3c$$
with $0\leq t_1,t_2,t_3\leq 1$ and $1=t_1+t_2+t_3$
is a triangle with vertices $a$, $b$, $c$.
Could someone explain to me how we came up with those parameters geometrically? How could you explain it and why do they work?
Thank you in advance.

A: You forgot to add that $a,b,c\in\Bbb R^2$. Clearly, $a,b,c\in A$; for intance, $a=1\times a+0\times b+0\times c$. Furthermor, the line segment that goies from $a$ to $b$ is a subset of $A$, since any $p$ from that line segment can be written as $(1-t)a+tb$, for some $t\in[0,1]$, and therefore $p=(1-t)a+tb+0\times c$. For the same reason, $A$ contains the line segments joining $a$ and $c$ and joining $b$ and $c$.
Let $p$ be an element of $A$. If $t_1,t_2,t_3\in[0,1]$ are such that $t_1+t_2+t_3=0$, and if $p=t_1a+t_2+t_3c$, then\begin{align}p&=t_1a+t_2b+\bigl(1-(t_1+t_2)\bigr)c\\&=(t_1+t_2)\left(\frac{t_1}{t_1+t_2}a+\frac{t_2}{t_1+t_2}b\right)+\bigl(1-(t_1+t_2)\bigr)c.\end{align}Since$$\frac{t_1}{t_1+t_2}+\frac{t_2}{t_1+t_2}=1\quad\text{and}\quad\frac{t_1}{t_1+t_2},\frac{t_2}{t_1+t_2}\geqslant0,$$the point$$\frac{t_1}{t_1+t_2}a+\frac{t_2}{t_1+t_2}b\tag1$$belongs to the line segment joining $a$ to $b$, and therefore $p$ belongs the line segment joining $(1)$ to $c$; so, $p$ belongs to the triangle.
This works in the opposite direction too: if $p$ belongs to the trangle, find the point $q$ of the line segment joining $a$ to $b$ such that $q$ $p$ and $c$ are collinear. Then $q=(1-t)a+tb$, for some $t\in[0,1]$, and $p=(1-t')q+t'c$ for some $t'\in[0,1]$. So\begin{align}p&=(1-t')\bigl((1-t)a+tb\bigr)+t'c\\&=\bigl((1-t')(1-t)\bigr)a+(1-t')tb+t'c\\&\in A.\end{align}


text:
Q: how to make vuetify dialog draggable I need to make a draggable dialog. But I'm using Vue2 & Vuetify.
I tried using jquery but doesn't work.
index.html
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
  <script>
    $(function () {
      $(".my-custom-dialog").draggable();
    });
  </script>
</head>

App.vue
<v-dialog v-model="isOpen" content-class="my-custom-dialog">
  <!-- dialog content-->
</v-dialog>

I thought using content-class to give my dialog class name and using jquery as above would work. But it doesn't. Any Ideas?

A: You can use vue-dialogue-drag, it is a pretty small package, and I usually recommend avoiding those (read about it at the end of the comment).
It's relatively easy to use, and you can follow the instruction in its GitHub readme.
if you would like to implement a solution written by you, you can use this as a template:
(function () { // make vuetify dialogs movable
    const d = {};
    document.addEventListener("mousedown", e => {
        const closestDialog = e.target.closest(".v-dialog.v-dialog--active");
        if (e.button === 0 && closestDialog != null && e.target.classList.contains("v-card__title")) { // element which can be used to move element
            d.el = closestDialog; // element which should be moved
            d.mouseStartX = e.clientX;
            d.mouseStartY = e.clientY;
            d.elStartX = d.el.getBoundingClientRect().left;
            d.elStartY = d.el.getBoundingClientRect().top;
            d.el.style.position = "fixed";
            d.el.style.margin = 0;
            d.oldTransition = d.el.style.transition;
            d.el.style.transition = "none"
        }
    });
    document.addEventListener("mousemove", e => {
        if (d.el === undefined) return;
        d.el.style.left = Math.min(
            Math.max(d.elStartX + e.clientX - d.mouseStartX, 0),
            window.innerWidth - d.el.getBoundingClientRect().width
        ) + "px";
        d.el.style.top = Math.min(
            Math.max(d.elStartY + e.clientY - d.mouseStartY, 0),
            window.innerHeight - d.el.getBoundingClientRect().height
        ) + "px";
    });
    document.addEventListener("mouseup", () => {
        if (d.el === undefined) return;
        d.el.style.transition = d.oldTransition;
        d.el = undefined
    });
    setInterval(() => { // prevent out of bounds
        const dialog = document.querySelector(".v-dialog.v-dialog--active");
        if (dialog === null) return;
        dialog.style.left = Math.min(parseInt(dialog.style.left), window.innerWidth - dialog.getBoundingClientRect().width) + "px";
        dialog.style.top = Math.min(parseInt(dialog.style.top), window.innerHeight - dialog.getBoundingClientRect().height) + "px";
    }, 100);
})();

*

*According to deps.dev vue-dialogue-drag has a 4.8/10 safety rate though there are no dangerous workflows within it, I believe that the reason for the low score is lack of updates :)

A: To make Vuetify 3.+ dialogs movable you may use solution earlier suggested by tipsy at https://github.com/vuetifyjs/vuetify/issues/4058 (identical to the accepted answer) but tailored as Vue component movable.vue which you import into your App.vue.
<script>
/* add class .vss-movable to <v-card-title> to make a dialog movable */

(function () {
  const d = {}
  const isMovable = (targ) => {
    return targ.classList?.contains("vss-movable")
  }
  document.addEventListener("mousedown", e => {
    const closestDialog = e.target.closest(".v-overlay__content")
    const title = closestDialog?.querySelector(".v-card-title")
    if ( e.button === 0 && closestDialog != null && (isMovable(e.target)) || isMovable(e.target.parentNode) ) {
      d.el = closestDialog // movable element
      d.handle = title // enable dlg to be moved down beyond bottom
      d.mouseStartX = e.clientX
      d.mouseStartY = e.clientY
      d.elStartX = d.el.getBoundingClientRect().left
      d.elStartY = d.el.getBoundingClientRect().top
      d.el.style.position = "fixed"
      d.el.style.margin = 0
      d.oldTransition = d.el.style.transition
      d.el.style.transition = "none"
    }
  })
  document.addEventListener("mousemove", e => {
    if (d.el === undefined) return
    d.el.style.left = Math.min(
      Math.max(d.elStartX + e.clientX - d.mouseStartX, 0),
      window.innerWidth - d.el.getBoundingClientRect().width
    ) + "px"
    d.el.style.top = Math.min(
      Math.max(d.elStartY + e.clientY - d.mouseStartY, 0),
      window.innerHeight - d.handle.getBoundingClientRect().height
    ) + "px"
  })
  document.addEventListener("mouseup", () => {
    if (d.el === undefined) return
    d.el.style.transition = d.oldTransition
    d.el = undefined
  })
})()
</script>

<style>
.v-overlay.v-dialog .vss-movable {
  cursor: grab;
}
.v-overlay.v-dialog .vss-movable:hover {
  background-color: #eee;
}
.v-overlay.v-dialog .vss-movable:active {
  cursor: grabbing;
}
</style>


text:
Q: In Winter's Heart and Crossroads of Twilight, what chapters can I skip? Winter's Heart and Crossroads of Twilight are much too slow paced for my tastes, but I want to get through them so I can read final few, faster-paced entries in the series.
What chapters can I skip while still being be able to understand the overarching story, as well as later books in the series?
Please use spoiler tags!

For whatever it's worth: I previously stumbled upon a GameFAQs post (that I can no longer find the source of) which said that everything in Crossroads of Twilight could be skipped EXCEPT for the prologue, chapters 1-3, 5-9, and 22-29, and the epilogue. This sounds promising, but I'm not sure I want to trust a single, random internet comment.

A: This is pretty tough to be objective about. Everyone has their own preferences as to what is important (or enjoyable) to read. As a result, I've attempted to provide very general statements for each book about what you'll be reading (or listening to in your case) and what you'll be skipping.
As a more general note: If you're REALLY pressed for time, the absolute minimum to read would be: The prologue and Ch35 of Winter's Heart, and you can skip Crossroads of Twilight entirely except for the epilogue.

Winter's Heart:
Read -> Prologue, Chapters 11-19, 22, 25, 28-35.
In very general terms, this gets you: [minimal spoilers below]

 Some key info that sets the tone of the book, almost all of the chapters to do directly with Rand, almost all the chapters about Mat, and a very important event for the series as a whole.

You will miss out on: [minimal spoilers below]

 Perrin's story, Elayne's story, minor flavor chapters from other points of view.

Crossroads of Twilight:
The recommended chapters you found are not bad, but I would take them a step further.
Read -> Prologue, Ch1-4, Ch16-20 (these are fairly tedious, but plot important), Ch21-24, Ch28-30 and the Epilogue.
This gets you [minor spoilers]:

 Mat's continuing story, Egwene and the rebel Aes Sedai, Ongoing stories regarding the major event of Winter's Heart, Enough interstitial bits to keep everything tied together. These chapters serve to set the stage for the next two books.

You skip [minor spoilers]:

 Perrin's chapters again, Elayne's chapters

For the sake of other people looking to try to answer this, here is my logic:
[Beware that this will have FULL SPOILERS]

 Perrin's whole "saving Faile" plotline is probably the most slowly paced part of both of these books and fails to progress in any significant way throughout. Just skipping his chapters saves a lot of time. It also ends up being pretty unimportant in the long run. Elayne's politics are probably the second most tedious aspect of the two books and the end result of the whole Andor subplot is fairly moot in the long run. Mat's story with Tuon is typically considered very entertaining, though there might be some way to minimize the number of chapters devoted to it (I just included them all). The Rebel Aes Sedai also tend to have boring chapters, but Egwene's rise to the control of the White Tower is a pretty big deal... so I kept them in. Overall the most important bits in my mind are Rand's madness and cleansing of Saidin, some evil characters getting offed (Forsaken for the most part), and the change in how the rebel Aes Sedai think about and do things. Knife of Dreams and Sandersons novels focus for the most part on Rand, Egwene and Mat, basically wrapping up the dull Perrin and Elayne bits in short order.


text:
Q: Voyager get records from another database and show in table. (customized view) There are two databse one is used for voyager and another is exiting database which filled data, I have to show in table form same as voyager do, I am newby and searched about to connect another database in voyager.
Customized controller to show listinf of domains
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use Illuminate\Routing\Controller as BaseController;
use TCG\Voyager\Http\Controllers\VoyagerBaseController as BaseController;
use TCG\Voyager\Facades\Voyager;
use App\Models\Domain;
class DomainController extends BaseController {
    //

    public function domainListing(){
      dd(Domain::limit(5)->get()->toArray());
      $data['abc'] = 'test';
      return view('domain-list');
    }
}

Routing file where I have wrote routing which is showing correctly,
Route::group(['prefix' => 'admin'], function () {
    Voyager::routes();
    Route::get('domains', ['uses' => 'App\Http\Controllers\DomainController@domainListing', 'as' => 'domains']);
});

Domain Model from another database
<?php

namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Domain extends Model {
    protected $connection = 'mysql-connection2';
    protected $table = 'domain';
    protected $guarded=[];
    public $timestamps = true;


text:
Q: Is the frequency of photon invariant? I saw a stackexchange answer that says the energy of photons is dependent on the reference frame. I did some digging and found that this is because the frequency of photons is dependent on the reference frame.
I am looking for an intuitive explanation as to why. So far I have considered Doppler effect as the main culprit - wherein the photon's wavelength changes based on how fast you are moving relative to the source of emission. Obviously, this means the frequency of the photon changes accordingly.
However, this explanation feels incomplete.

A: A light-signal has a lightlike 4-momentum $\tilde \omega$ where $\tilde \omega \cdot \tilde \omega=0$. So, its energy-component is equal to the magnitude of its momentum-component.
For simplicity, consider the $(1+1)$-case so that all motion is along the  x-axis.
The Lorentz boost has eigenvectors along the light-cone (so that a light-signal remains a light-signal) and has eigenvalues are equal to the Doppler factor $k=\sqrt{\frac{1+v}{1-v}}$ and its reciprocal (since the determinant of the boost is equal to the product of its eigenvalues, and the determinant is equal to 1). Check this... set up the eigenvalue problem for the boost.
Thus, in a new frame, energy of the light-signal (and thus the frequency) is multiplied by the doppler factor.

UPDATE: Note that "length contraction" does not directly apply to the Doppler effect. The length-contraction factor and the time-dilation factor are even functions of V-- that is, they depend on speed... but not direction.

*

*Length contraction depends on relative-speed and applies to the spacelike-separation between parallel timelike-worldlines.

*Doppler effect on wavelength depends on the relative-velocity (including approaching vs receding) and applies to the spacelike-separation between parallel lightlike-worldlines.

See: my answer https://physics.stackexchange.com/a/337804/148184 to Deriving Relativistic Doppler Effect through length contraction )

UPDATE2: Hopefully, this diagram will provide some spacetime-geometric intuition.
Regard the diagram below as a spacetime-diagram (with time running upwards).
The effect of an active Lorentz boost transformation takes
the pink diamond with the red diagonal
to the cyan diamond with the blue diagonal.

*

*O gets mapped to itself, A gets mapped to B (another point on a hyperbola [of radius 5]), and L gets mapped to M (along the light cone, a hyperbola of radius 0).

*The velocity $v=(3/5)c$, which corresponds to time-dilation factor $\gamma=\frac{1}{\sqrt{1-(v/c)^2}}=\frac{5}{4}$ and Doppler factor $k=\sqrt{\frac{1+(v/c)}{1-(v/c)}}$=2. These numerical values can be read off the diagram: $(v/c)=\frac{AQ}{OA}=\frac{3}{5}$, $\quad$ $\gamma=\frac{OA}{OQ}=\frac{5}{4}$, and $\quad$ $k=\frac{OM}{OL}=2$. (Note the diamond area is unchanged since the determinant of the boost (which equal the product of the eigenvalues) equals 1. So, the stretch by $k=2$ in one lightlike direction has a shrinking by the same factor along the other lightlike direction).

Now regard this as an energy-momentum diagram (with energy running upwards).

*

*$OA$ is a momentum 4-vector of a particle with invariant mass 5 units.
$OL$ is a momentum 4-vector of a photon with relativistic energy 2.5 units [and relativistic momentum 2.5 units, so its invariant mass is zero units].

*Under an active boost, the corresponding momentum 4-vector of the photon is scaled by the Doppler factor $k$ (that is, $OM=k(OL)$) so that the boosted photon has relativistic energy of $k(2.5)=2(2.5)=5$ units. Since the relativistic energy is proportional to its frequency ($E=\mbox{(const)}\omega$), the frequency of the boosted photon is now $k$ times its frequency in the original frame.

Interpret it this way.

If the forward-directed photon in the rocket frame had relativistic energy 2.5 units, then in the lab frame (where the rocket has velocity $(3/5)c$), that forward-directed photon has relativistic energy $k(2.5)=5$ units.

I hope this gives some quantitative intuition.
(See my other answer to directly connect with "period" and "wavelength".)

A:
Is the frequency of photon invariant

The photon is an elementary quantum mechanical point particle of the standard model of particle physics.
As it has no space dimension, it is a point in (x,y,z,t), there is no wave to have a length in space. It has a quantum mechanical wave function which has a wavelength but for a single photon the only meaning is that it is connected to the probability to be found in (x,y,z,t).
What depends on the reference frames as far as space waves go, is the classical electromagnetic light wave, as discussed in the other answers, not photons. Photons just change energy in differently moving inertial frames.
Photons carry the energy $h*ν$ where $ν$  is the frequency of the classical beam which is built up by very many photons and $h$ the Planck constant.
In quantum mechanics the wavefunction $Ψ$ models the probability of finding a single  photon at (x,y,z,t), by $Ψ^*Ψ$
See this answer of mine to get an intuition of how photons build up the classical wave of light.

A: Photons move along lightlike geodesics regardless of the observer, so although energy $E=h\nu$ and momentum $\boldsymbol{p} = (h/\lambda)\boldsymbol{\hat{n}}$ depend on the observer, the following quantity is invariant:
$$\frac{E^2}{c^2} - \boldsymbol{p}\cdot \boldsymbol{p} = 0$$
In special relativity theory, Lorentz transformations imply that for two observers O and O' with relative velocity $V$ along X axis (assume O is static withe respect to the light source, and O' is approaching the source), we have the relations:
$$E' = \frac{E-V p_x}{\sqrt{1-V^2/c^2}}, \quad p'_x = \frac{p_x - EV/c^2}{\sqrt{1-V^2/c^2}},\quad p'_y = p_y, \quad p'_z = p_z $$
where $(E/c,p_x,p_y,p_z)$ and $(E'/c,p'_x,p'_y,p'_z)$ are the energy-momentum componentes measured by O and O'. These two expressions in turn imply that:
$$\nu' = \nu \sqrt{\frac{1+V/c}{1-V/c}}, \qquad \lambda' = \lambda \sqrt{\frac{1-V/c}{1+V/c}}$$
The the light velocity for both observers are:
$$c = \lambda\nu, \qquad c' = \lambda'\nu' = \left(\lambda\sqrt{\frac{1-V/c}{1+V/c}}\right)\ \left(\nu \sqrt{\frac{1+V/c}{1-V/c}}\right) = c$$
Thus, since the wavelength contracts as an observer moves toward the wave source (Lorentz distance contraction), there must be a time dilation to compensate for it, otherwise some observer would see the light moving at a speed different from $c$.

A: Lots of answers have provided details, but perhaps more complexity than you were looking for. There are two simple points that answer your question:
(1) Energy is always frame dependent. For example, in a frame where an object is at rest it has no kinetic energy; in a frame where it is moving, it has some, and the amount depends on the relative velocity of the object.
(2) Frequency does change based on the Doppler effect, and light's energy is directly related to its frequency, so your initial guess was correct. There are some technical issues addressed in the other answers, but basically that's it.

A: Time dialation/length contraction is the reason.
This is called the relativistic doppler effect

A: So once you consider "the source of emission", you are hampering your understanding of the problem: the source of emission is irrelevant.
A photon just exists.
It moves at $c$ in all frames, and can have any non-zero frequency (in SR...irl it's bounded above by the Planck frequency, probably).

A: Rather than add to or edit my first set of answers (which focused on the Doppler factor as an eigenvalue that was used to scale the 4-momentum of a light-signal and also emphasized that length-contraction is not directly involved), this answer tries to directly connect the Doppler factor to the properties of period and wavelength.
Consider a source with velocity $v=(3/5)c$. The corresponding Doppler factor is $k=\sqrt\frac{1+(v/c)}{1-(v/c)}=2$.
If the source emitting signals at every 4 of its ticks ($T_{src}=4$),
then the corresponding wavelength in the source frame is gotten from $\lambda_{src}/c=4$). I'm going to drop the $c$'s out of convenience.
The spacetime diagram (with "rotated graph paper" to help visualize the tickmarks along worldlines) shows the periodic source and the light-signals (which can be associated with wavefronts).
This diagram is drawn by Alice who is at rest in this frame.
She meets Bob (the source) at event $O$.

In this frame, if a receiver at rest detects the backward-directed signals,
the source is moving away from the receiver ("the separating case").

*

*Two successive backward-directed signals are detected by Alice at events $O$ and $A_{RB}$.
Alice measures a period between receptions $T_r = k T_{src}=(2)(4)=8$.
(After Bob passes Alice at O and continues to separate, Alice takes 8 hours to watch [in slow motion] a 4-hour show broadcasted by Bob.)
Alice measures a spatial separation $\lambda_r =k \lambda_{src}=(2)(4)=8$ (along a line of events simultaneous with the second reception event $A_{RB}$ according to Alice). As a check, Alice measures the speed of the light-signal to be $\lambda_r/T_r=c$.

*Since the observed-period is longer by the factor $k$, the observed-frequency
is lower $f_{r}=\frac{1}{k}f_{src}$, which corresponds to a "redshift".
Since the energy is proportional to the frequency, the observed-energy is lower.
Similarly, the observed-wavelength is longer by the factor $k$, which also corresponds to a redshift. Since the momentum is inverse-proportional to the wavelength, the observed-momentum is also lower.

*We will argue that, on an energy-momentum diagram, the 4-momentum of the light-signal for a separating source is proportional to the shorter edge of the blue causal diamond in this frame,
which corresponds to a less-energetic light-signal compared to the energy in the source-frame.

In this frame, if a receiver at rest detects the forward-directed signals,
the source is moving toward the receiver ("the approaching case").

*

*Two successive forward-directed signals are detected by Alice at events $A_{RF}$ and $O$.
Alice measures a period between receptions $T_r = \frac{1}{k} T_{src}=\frac{1}{2}(4)=2$.
(Before Bob passes Alice at O and continues to approach, Alice takes 2 hours to watch [in sped-up motion] a 4-hour show broadcasted by Bob.)
Alice measures a spatial separation $\lambda_r = \frac{1}{k} \lambda_{src}=\frac{1}{2}(4)=2$ (along a line of events simultaneous with the second reception event $O$ according to Alice). As a check, Alice measures the speed of the light-signal to be $\lambda_r/T_r=c$.

*Since the observed-period is shorter by the factor $k$, the observed-frequency
is higher $f_{r}=kf_{src}$, which corresponds to a "blueshift".
Since the energy is proportional to the frequency, the observed-energy is higher.
Similarly, the observed-wavelength is shorter by the factor $k$, which also corresponds to a blueshift. Since the momentum is inverse-proportional to the wavelength, the observed-momentum is also higher.

*We will argue, on an energy-momentum diagram, that the 4-momentum of the light-signal for an approaching source is proportional to the longer edge of the blue causal diamond in this frame,
which corresponds to a more-energetic light-signal compared to the energy in the source-frame.

Next, consider the following diagram.

*

*If the source were drawn in the source-frame, it would correspond to the red diamond. (When $v=0$, then $k=1$.)

*But since the source is drawn in Alice's frame, where Alice measures the velocity of the source to be $v_{Bob}=(3/5)c$, it corresponds to the blue diamond [here and in the previous diagram].

*The effect of the Lorentz boost transformation preserves the edges of the diamond (lightlike directions are eigenectors) and preserves the area of the diamond (since the determinant of the boost [product of eigenvalues] equals 1). The eigenvalues are $k=\sqrt\frac{1+(v/c)}{1-(v/c)}$ and $1/k$, with $k=2$ for $v=(3/5)c$.

*So,
the blue diamond edge $OF$ is the scaled up edge: it is $k$ times the corresponding vector on the red diamond,
and
the blue diamond edge $OB$ is the scaled down edge: it is $1/k$ times the corresponding vector on the red diamond.

*Thus, on a similarly-drawn energy-momentum diagram,
the 4-momentum of the more-energetic light-signal from the approaching source is proportional to $OF$ (see the vector $OM$ in my first answer),
and
the 4-momentum of the less-energetic light-signal from the separating source is proportional to $OB$.

Hopefully, this answer connects the Doppler effect
with "period" (and thus frequency)  and "wavelength", and thus the energy and momentum as components of the 4-momentum of a light-signal.

A: Let's say a photon is approaching from the left at speed c, and an object is approaching  from the right at speed -0.87 c.
When those two things collide, constant forces F and -F are exerted on them for time t.
The photon does work $ w_1=F * c/t$
The object does does work $w_2 = -F * -0.87*c/t$
So total work done in this collision is: $w=w_1+w_2=F*(1.87*c/t)$
The energy released in this collision is 1.87 times larger than energy released in a collision with an identical photon and a non-moving object.
If we change to the rest frame of the the object that moved at speed -0.87 c, all the energy released in the collision is in the photon before the collision.
Also said energy is gamma times larger in this frame.
So the energy of the photon in this new frame is: 2 * 1.87 * energy of photon measured in the old frame.
(The aforementioned collision is such that the speeds of both things can be considered to be constant during the collision, because one thing is massive and other thing is a photon, or maybe group of photons would work better in this case)


text:
Q: Network: sending a video (in theory) Context

*

*We have got un unsteady transmission channel. Some packets may be lost.

*Sending a single network packet in any direction (from A to B or from B to A) takes 3 seconds.

*We allow a signal delay of 5 seconds, no more. So we have a 5-second buffer. We can use those 5 seconds however we want.

*Currently we use only 80% of the transmission channel, so we have 1/4 more room to utilize.

*The quality of the video cannot be worsened.

Problem
We need to make the quality better. How to handle lost packets?
Solution proposition
A certain thing - we cannot use TCP in this case, because when TCP detects some problems, it requests retransmission of lost data. That would mean that a packet would arrive after 9 seconds, which is more than the limit.
Therefore we need to use UDP and handle those errors ourselves. How to do it then? How to make sure that not so many packets will be lost as currently, without retransmitting them?

A: Its a complicated solution, but by far the best option will be to add forward error correction (FEC). This is how images are transfered form space probes where the latency is measures in minutes or hours. Its also use by cell phones where delayed packets are bad for two way communication.
A not as good, but eaiser to implement option is to use UDT. This is a UDP with tcp like retranmission library, but allows you much more controll over the protocol.


text:
Q: How to set the working directory of WinGHCi I just installed WinGHCi. When I try to load an .hs file with Ctrl+L, it opens the file browser in C:\Program Files (x86)\Haskell Platform\2012.2.0.0\winghci which is where I installed this. I don't want it to go there by default, I keep my code files in a different directory on a different drive and I don't want to have to navigate to D:\MyPath\Haskell every time I load a file.
I tried to set the "Start in" field of the shortcut I use to launch WinGHCi but it changed nothing.
How can I make WinGHCi look in my own directory by default?

A: It opens in the last directory you opened a .hs or .lhs from.
Try opening something from the folder you want, exit, restart.
Did it restart where you were?
Try working like that for a while, and if you like it (I do) then you're fine.

If you really do want to go to the same place every time, perhaps there's a way.
I can't find any setting to control this, but the information is stored in the registy.
Mine is at
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Haskell\WinGHCi 1.0.6]
"WorkingDir"="D:\\Files\\Andrew\\prog\\haskell"

You can save your version of that as resetghci.reg:
To make your own, open regedit and first try the same location. If not, search for WinGHCi.
You can export that subtree but you get the whole lot including recent expressions etc, which I don't think you should reset. Save that as ghcioriginal.reg just in case. Edit away all the lines except WorkingDir and save as resetghci.reg
When you double-click it it will ask you if you're sure you want to add that info to the registry. Yes you are.

Untested:
What follows works on older versions, but Microsoft  seem to be going off .pif files and the start command, and I'm not able to test this in Windows 7.
Make a text file called ghci.bat in the same folder as the .reg you made. In it put
@echo off
regedit resetghci.reg
start WinGHCi

You might need to specify the full path to WinGHCi.
The start command is the windows equivalent of making a background process from a shell prompt, so this should terminate immediately.
Make a shortcut to ghci.bat (it will be called ghci.pif) and set it to open minimised and put a nice lambda icon on it (nick it from the winghci executable).
Pop that on your desktop, start menu or shortcut bar, and when you use it, you'll be popped back to your standard location.


text:
Q: How to remove L.rectangle(boxes[i]) I few days ago I implement a routingControl = L.Routing.control({...}) which works perfect for my needs. However I need for one of my customer also the RouteBoxer which I was also able to implement it. Now following my code I wants to remove the boxes from my map in order to draw new ones. However after 2 days trying to find a solution I've given up.
wideroad is a param that comes from a dropdown list 10,20,30 km etc.
function routeBoxer(wideroad) {
  this.route = [];
  this.waypoints = []; //Array for drawBoxes
  this.wideroad = parseInt(wideroad); //Distance in km
  this.routeArray = routingControl.getWaypoints();
  for (var i=0; i<routeArray.length; i++) {
    waypoints.push(routeArray[i].latLng.lng + ',' + routeArray[i].latLng.lat);
  }
  this.route = loadRoute(waypoints, this.drawRoute);
}; //End routeBoxer()

drawroute = function (route) {
  route = new L.Polyline(L.PolylineUtil.decode(route)); // OSRM polyline decoding
  boxes = L.RouteBoxer.box(route, this.wideroad);
  var bounds = new L.LatLngBounds([]);
  for (var i = 0; i < boxes.length; i++) {
    **L.rectangle(boxes[i], {color: "#ff7800", weight: 1}).addTo(this.map);**
    bounds.extend(boxes[i]);
  }
  console.log('drawRoute:',boxes);
  this.map.fitBounds(bounds);
  return route;
}; //End drawRoute()

loadRoute = function (waypoints) {
  var url = '//router.project-osrm.org/route/v1/driving/';
  var _this = this;
  url += waypoints.join(';');
  var jqxhr = $.ajax({
    url: url,
    data: {
      overview: 'full',
      steps: false,
      //compression: false,
      alternatives: false
    },
    dataType: 'json'
   })
  .done(function(data) {
    _this.drawRoute(data.routes[0].geometry);
    //console.log("loadRoute.done:",data);
  })
  .fail(function(data) {
    //console.log("loadRoute.fail:",data);
  });
}; //End loadRoute()

Well, my problem is now how to remove previously drawn boxes in order to draw new ones because of changing the wideroad using a dropdown list. Most of this code I got from the leaflet-routeboxer application.
Thanks in advance for your help...

A: You have to keep a reference to the rectangles so you can manipulate them (remove them) later. Note that neither Leaflet nor Leaflet-routeboxer will do this for you.
e.g.:
if (this._currentlyDisplayedRectangles) {
    for (var i = 0; i < this._currentlyDisplayedRectangles.length; i++) {
        this._currentlyDisplayedRectangles[i].remove();
    }
} else {
    this._currentlyDisplayedRectangles = [];
}

for (var i = 0; i < boxes.length; i++) {
    var displayedRectangle = L.rectangle(boxes[i], {color: "#ff7800", weight: 1}).addTo(this.map);
    bounds.extend(boxes[i]);
    this._currentlyDisplayedRectangles.push(displayedRectangle);
}

If you don't store a reference to the L.rectangle() instance, you obviously won't be able to manipulate it later. This applies to other Leaflet layers as well - not storing explicit references to Leaflet layers is a usual pattern in Leaflet examples.


text:
Q: How to get file URL using Aws::S3::Client having bucket and filename? I have the following code to get the file data:
client = Aws::S3::Client.new(***settings***)
client.get_object(bucket: Settings.aws.data_migrations.s3_bucket, key: filename)

It returns Aws::S3::Types::GetObjectOutput
Is it possible to get file URL using the bucket and filename?

A: url is:
https://.s3-.amazonaws.com/
example:
https://testbucket.s3-us-east-1.amazonaws.com/sample_folder/image.jpeg


text:
Q: What makes a god excel in a support role? As the title, what makes a god a excel in a support role?
I'm aware that support characters tend to be guardians, but there are several gods that can heal others from the mage or warrior god type which would appear to be decent support choices.
So, what do players look for in the support role?

A: The support role has 3 main jobs in Smite, each of which vary in importance as the game progresses into the later stages. It should be noted that since Season 2, the Support role is now the most difficult role to play well.
First and foremost, the Support is required to protect the very weak Hunter in the Long/Duo lane at the start of the match. This is done by having the ability to peel (which means to stop enemies attacking the Hunter) using Crowd Control abilities and your own natural tankiness in order to take damage that would otherwise be killing the Hunter. As such, one of the most important aspects of any Support character should be their Crowd Control and their health/defense capabilties.
Around 3 minutes in, the Mid Harpy camps will spawn, which offer a large amount of XP to the God(s) that kill them. These are meant to be contested by the Support on the Duo side, and in order to guarantee a kill you will almost certainly need the time and space to deal enough damage. This requires zoning in order to keep your rival Support God away from the camp long enough to secure the camp - which again relies on CC abilities, as well as being able to deal and take damage effectively. In the mid to late game, the Support will find themselves under-levelled unless they frequently take Harpy Camps, so this is very important.
Finally, the Support must be able to rotate from lane to lane quickly when needed, and must have presence in a team fight (by which I mean must be able to initiate a large battle). As such, Supports with good mobility and peel excel here, such as Athena (whose Ultimate ability allows her to teleport to any friendly God, and who has an ability that draws enemies to attack her rather than team mates).
In short, Supports require;

*

*Good Crowd Control

*Good mobility

*An ability to take a beating

This three aspects are the most important things that a Support character needs.


text:
Q: Removing AngularJS currency filter "," and replace with a space my data base doesnt allow special characters Removing AngularJS currency filter "," and replace with a space my data base doesnt allow special characters
I get this R68,993.85
I want this R68 993.85

A: You don't need to replace it. currency is a filter, it just changes how the given value look. It won't modify your model value so you won't save the formatted number in your database. If you do, then you should check how you use this filter.

A: your requirement is little weird .if you are using currency filter thern , should be there. but still if you have limitation that you cant change you database structure. then you can try this.
var str = "R12,234.60";
 var res = str.replace(","," ");


text:
Q: Can application descriptor give the other application descriptor in blackberry? I want to know that can currentApplicationDescriptor() method of ApplicationDescriptor class give the another third party application descriptor...
thanks in advance.

A: CodeModuleManager is what you want
Its not an application descriptor, since that just parses your XML into the class members. But it does read the info on other applications.