Schedule Celery task to run after other task(s) complete

Question: I want to accomplish something like this:
results = []
for i in range(N):
    data = generate_data_slowly()
    res = tasks.process_data.apply_async(data)
    results.append(res)
celery.collect(results).then(tasks.combine_processed_data())

ie launch asynchronous tasks over a long period of time, then schedule a  dependent task that will only be executed once all earlier tasks are complete.
I've looked at things like chain and chord, but it seems like they only work if you can construct your task graph completely upfront.
Answer: For anyone interested, I ended up using this snippet:
@app.task(bind=True, max_retries=None)
def wait_for(self, task_id_or_ids):
    try:
        ready = app.AsyncResult(task_id_or_ids).ready()
    except TypeError:
        ready = all(app.AsyncResult(task_id).ready()
                    for task_id in task_id_or_ids)

    if not ready:
        self.retry(countdown=2**self.request.retries)

And writing the workflow something like this:
task_ids = []
for i in range(N):
    task = (generate_data_slowly.si(i) |
            process_data.si(i)
            )
    task_id = task.delay().task_id
    task_ids.append(task_id)

final_task = (wait_for(task_ids) |
        combine_processed_data.si()
        )

final_task.delay()

Comment: Ehy great solution.. but I really don't like the 2**self.request.retries as it can literally explodes easily: that's better to use a static value. Further, there's a typo in the code: `final_task = (wait_for(task_ids) | combine_processed_data.si())` should be `final_task = (wait_for(task_ids).si() | combine_processed_data.si())`
Answer: That way you would be running your tasks synchronously.
The solution depends entirely on how and where data are collected. Roughly, given that generate_data_slowly and tasks.process_data are synchronized, a better approach would be to join both in one task (or a chain) and to group them.
chord will allow you to add a callback to that group.
The simplest example would be:
from celery import chord

@app.task
def getnprocess_data():
    data = generate_data_slowly()
    return whatever_process_data_does(data)

header = [getnprocess_data.s() for i in range(N)]
callback = combine_processed_data.s()

chord(header)(callback).get()

Comment: no, I don't want `generate_data_slowly` and `process_data` to be synchronized. `process_data` should execute by a worker while another set of data is being generated. `generate_data_slowly` involves hardware and must run in a master process, not shuffle between workers.


Force a single value base field to be in a separate table?

Question: I have a custom entity type (eg: myentitytype), and I would like to add a new base field to it via hook_entity_base_field_info(). As I understand it, single value fields (with a cardinality of 1) will create new columns in the myentitytype_field_data table, but multi-value fields will create a new table.
Is it possible to "force" a single-value field to be stored in its own database table, rather than adding columns to the myentity_field_data table?
Comment: Yes that's true - a config entity field would put it in a separate table. I was specifically curious about where the logic for base fields makes this decision, and if there were any way to specify. Thanks!
Comment: Can you not add it as config entity fields as opposed to entity base fields? I think they all have their individual tables. (Not sure about the multi / single value fields)
Comment: For anyone curious why: I am considering adding a Geofield as a base field, which has 9 columns. It may result in sparse data if its in the shared table. Other logic will depend on this field, which is why I am considering making it a base field.
Answer: \Drupal\Core\Entity\Sql\DefaultTableMapping is responsible for determining a separate field storage table; its allowsSharedTableStorage() method returns a Boolean value basing on four conditions.
public function allowsSharedTableStorage(FieldStorageDefinitionInterface $storage_definition) {
  return !$storage_definition->hasCustomStorage() && $storage_definition->isBaseField() && !$storage_definition->isMultiple() && !$storage_definition->isDeleted();
}

The only feasible solution would be to implement your own storage handler and use "custom_storage" => TRUE.
Comment: FYI: As an alternative solution, I created a proposal for Drupal core that would add a new `hasDedicatedStorage()` method to base field definitions, which would allow developers to explicitly specify that they want dedicated table storage for their single-value base field. https://www.drupal.org/project/drupal/issues/3183359
Comment: Thanks this is exactly the logic I was looking for! :-)


how to get distinct records in datatable?

Question: I am using C# + VS2008 + .Net + ASP.Net + IIS 7.0 + ADO.Net + SQL Server 2008. I have a ADO.Net datatable object, and I want to filter out duplicate/similar records (in my specific rule to judge whether records are duplicate/similar -- if record/row has the same value for a string column, I will treat them as duplicate/similar records), and only keep one of such duplicate/similar records.
The output needs to be a datatable, may output the same datatable object if filter operation could be operated on the same datatable object.
What is the most efficient solution?
Comment: Do you care *which* of the similar/duplicates you want to keep? The "first" (in storage)? Some other discriminator column? Do you want to perform an aggregate on the other column values? More specifics are required.
Comment: You're listing the whole technology stack, but it sounds like you're only interested in getting things out of a DataTable object. Is that right? Do you have control over where this data comes from? If you can only select distinct items from the database in the first place, that will be more efficient than filtering duplicate items out of a datatable afterward.
Comment: Keep any of them is ok. Any good ideas?
Comment: The datatable is an intermediate output from my business logics. We can only operate on the memory datatable, not on the database itself. You can treat is as some unclean input to my component. :-(
Answer: Are you using .NET 3.5? If you cast your data rows, you can use LINQ to Objects:
var distinctRows = table.Rows.Cast<DataRow>().Distinct(new E());

...

public class E : IEqualityComparer<DataRow>
{
    bool IEqualityComparer<DataRow>.Equals(DataRow x, DataRow y)
    {
        return x["colA"] == y["colA"];
    }

    int IEqualityComparer<DataRow>.GetHashCode(DataRow obj)
    {
        return obj["colA"].GetHashCode();
    }
}

Or an even simpler way, since you're basing it on a single column's values:
var distinct = from r in table.Rows.Cast<DataRow>()
               group r by (string)r["colA"] into g
               select g.First();

If you need to make a new DataTable out of these distinct rows, you can do this:
var t2 = new DataTable();
t2.Columns.AddRange(table.Columns.Cast<DataColumn>().ToArray());
foreach(var r in distinct)
{
    t2.Rows.Add(r);
}

Or if it would be more handy to work with business objects, you can do an easy conversion:
var persons = (from r in distinct
               select new PersonInfo
               {
                   EmpId = (string)r["colA"],
                   FirstName = (string)r["colB"],
                   LastName = (string)r["colC"],
               }).ToList();

...

public class PersonInfo
{
    public string EmpId {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
}

Update
Everything you can do in LINQ to Objects can also be done without it: it just takes more code. For example:
var table = new DataTable();
var rowSet = new HashSet<DataRow>(new E());
var newTable = new DataTable();
foreach(DataColumn column in table.Columns)
{
    newTable.Columns.Add(column);
}
foreach(DataRow row in table.Rows)
{
    if(!rowSet.Contains(row))
    {
        rowSet.Add(row);
        newTable.Rows.Add(row);
    }
}

You could also use a similar strategy to simply remove duplicate rows from the original table instead of creating a new table.
Comment: Any solution not based on LINQ?
Answer: You can do a select into with a group by clause, so not duplicates are created. Then drop the old table and rename the table into which you selected to the original table name.
Comment: Interesting! We can run SQL inside data table? Could you show me a sample please (or a document)? And I especially surprised how to use group by to filter duplicate records?
Answer: I would do this in the database layer:
SELECT Distinct...
FROM MyTable

Or if you need aggregates:
SELECT SUM(Field1), ID FROM MyTable
GROUP BY ID

Put the SELECT statement in a stored procedure.  Then in .net make a connection to the database, call the stored procedure, execute .ExecuteNonQuery().  Return the rows in a datatable and return the datatable back to your UI.
Comment: Sorry there is no database table related to the datatable, it is an intermediate output from my business logics. We can only operate on the memory datatable. So, your database based solution can not be used. Any solutions?


How to fix the error Cannot open file, path = '/storage/emulated/0/DCIM/Camera/20200818_123041.jpg' (OS Error: Permission denied, errno = 13)

Question: I'm trying to allow a user to pick an image from their photo gallery on their device.
My previous code worked fine, but now that I have to update the targetSdkVersion from 28 to 29, its not working any more.
I've tried adding
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>

But still not working. Also tried using the permission_handler flutter package.
Any help is greatly appreciated!
Thanks, Jason.
Comment: Any errors or excceptions? Please tell what is not working.
Answer:
Need to give permission on your android manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

And also use this for flutter
Follow all steps as per above link.
Answer: If you use permission_handler and you writed:
if (!status.isGranted) { await Permission.storage.request(); }
The application asks for permission?
You can write print before if statement, in conditions and after if statement
Answer: I managed to solve my problem in the end. I needed to set android:requestLegacyExternalStorage="true" in android manifest, and change the compileSdkVersion to 29 aswell (it was still on 28, even though I'd changed the targetSdkVersionto 29) - you must need to change both in the app level build.gradle.
Hope this helps someone, so glad I fixed my issue!
Comment: This is a temporary solution


export audit log from azure ad b2c

Question: I am trying to export Azure Active Directory Audit Logs from B2C Tenant (let's call it Tenant 2) to Azure Storage Account in Tenant 1 (main).
I want to collect any information about users changing passwords, users being created in AD B2C, etc. So far, I've tryed to set the export profile for Activity Logs in Tenant 1, but Activity Logs do not include such a type of information. When I'm looking at the Audit Logs of the Activity Directory in the Tenant 2, I can see all the necessary data, but I can't find a way to set the export.
Is there any way to achieve my goal with Azure's out-of-the-box functionality?
Answer: You can refer to this article for the details. Currently it looks like that we can only use Graph API or PowerShell to export the audit logs.

export audit log from azure ad b2c


iOS 11 UINavigationBar category issue

Question: When I override layoutSubviews of UINavigationbar, all the subviews are getting removed. I am trying to set custom Navigationbar height. It was working fine, but breaking in iOS 11. It is a custom category.
Answer: I have created a subclass of UINavigationBar with setFrame: and layoutSubviews methods. You need to set the subclass as NavigationController's NavigationBar in Storyboard.
<code>CGFloat const NavBarHeight = 88.0;

- (CGSize)sizeThatFits:(CGSize)size {
    return [self getNavBarSize];
}

- (void)setFrame:(CGRect)frame {
    frame.size.height = NavBarHeight;

    for (UIView *subview in self.subviews) {
        if ([NSStringFromClass([subview class])  containsString:@"UINavigationBarContentView"]) {
            subview.frame = CGRectMake(0, 20, self.frame.size.width, NavBarHeight-30);
        }
        [subview sizeToFit];
    }
    [super setFrame:frame];

}

- (void)layoutSubviews {
    [super layoutSubviews];
    for (UIView *subview in self.subviews) {
        if ([NSStringFromClass([subview class]) containsString:@"BarBackground"]) {
            subview.frame = CGRectMake(0, -20, self.frame.size.width, NavBarHeight+20);
            [subview sizeToFit];
        }else if ([NSStringFromClass([subview class])  containsString:@"UINavigationBarContentView"]) {
            subview.frame = CGRectMake(0, 20, self.frame.size.width, NavBarHeight-30);
        }
    }
}
</code>

iOS 11 UINavigationBar category issue


in react i want to select only one user my code is selecting every user

Question: im facing issue when i click add friend button every button changes to requested how can i particularly set it to one user only which i clciked i tried few things but it is not working it is selecting every other user. i used handleproductselect function but it is not working i have given them individual id still it is not working
class SearchModal extends Component {
  constructor(props){
    super(props);
    this.state = {
        Input:"Add Friend",
        backgroundColor: 'white',
        active_id: null,
    }
}

async handleProductSelect(elementid){
  const id = elementid;
  const { backgroundColor } = this.state;
  let newBackgroundColour = backgroundColor === 'white' ? 'yellow' : 'white';
  this.setState({
    Input : "Requested",
    backgroundColor: newBackgroundColour,
    active_id: id
  })
  console.log(id)
}

render() {
    const {currentUser} = this.props;
    return (

          <Modal show={this.state.show} onHide={this.handleClose}
          >
             <Modal.Header closeButton>
               <Modal.Title>
                 <input
                  type="text"
                  placeholder="Search.."
                  value={search}
                  onChange={this.onTextboxChangeSearch}
                 ></input>
               </Modal.Title>
             </Modal.Header>
             <Modal.Body>

Users

                  {userdetails.map((element) => {
                    if(currentUser.user.username !== element.username){
                      return(

{element.username}{' '}<input
                          type="button"
                          id={element._id}
                          onClick={this.handleProductSelect.bind(this,element._id )}
                          value={this.state.Input}
                          style = {{backgroundColor: ( element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)}}></input>

                      );
                    }else{
                      return(

{element.username}

                      );
                    }
                  })}

             </Modal.Body>
          </Modal>

    )
  }
}

Answer: Issue
You've correctly used state to store the "active id", but you use only a single state to represent the buttons' values.
<input
  type="button"
  id={element._id}
  onClick={this.handleProductSelect.bind(this, element._id)}
  value={this.state.Input} // <-- same single state for all buttons!
  style = {{
    backgroundColor: (element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)
  }}
/>

Solution
Since I think the intent is to keep the buttons that have been "activated", i.e. you want the label "Requested" to remain, you should add some state to store all the requested active ids. There is also no need to store the static content in state that is the button label, same with background color, this is all derived data based on the state.active_id value.
this.state = {
  active_id: null,
  requestedIds: {},
}

Update handleProductSelect to be a curried arrow function. The arrow functions will bind the this of the class-component to the callback. The curried function allows you to not need an anonymous callback function just to attach the handler
handleProductSelect = id => () => {
  this.setState(prevState => ({
    active_id: prevState.active_id === id ? null : id, // toggle active id
    requestedIds: {
      ...prevState.requestedIds,
      [id]: id, // add requested id
    },
  }));
}

Update the Input to check if the requestedIds has a key for the current element _id and conditionally render the button label. Similarly, check the active id for the background color.
<input
  type="button"
  id={element._id}
  onClick={this.handleProductSelect(element._id)}
  value={this.state.requestedIds[element._id] ? 'Requested' : 'Add Friend'}
  style = {{
    backgroundColor: (element._id === this.state.active_id ?  'yellow' : 'white')
  }}
/>

Comment: hello @DrewReese im having one trouble in above code what changes i should make to add friendsid in both friendslist like the receiver and user
Comment: @PratikZinjurde I think you may need to provide a little more context around this new question. If you could create a running codesandbox for what you are trying to do I don't mind taking a look when I've some time. This also seems like it is a new question. It may be quicker to post a new SO question though, you'll get more eyes on it. If you do this feel free to (at) me here with a link to it.
Comment: ok thanks but i did this and its working now let user = await User.findByIdAndUpdate( id,{ $push: {"friendsList" : {friendId:fid}} } )
      if (user){
        await User.findByIdAndUpdate( fid,{ $push: {"friendsList" : {friendId:id}} } )// this line i added this and now in both users friendslist each others id is getting added
        res.status(200).json({
          message:"user found",
          user,
        });                                 actually i was asking  how to connect both users like users id is anothers friends id to whom we send request it was like a hack actually
Comment: hello @DrewReese i need ur help when i refresh the value of button resets how to make it permanent im thinking of using localstorage but im not finding where to put that condition of localstorage that if friendsid = userid then it will always show message value of the button
Comment: @PratikZinjurde Sure. A common solution is to use localStorage to persist your app state. You use `componentDidUpdate` to persist component state to local storage, and `componentDidMount` read from and initialize your component state.
Comment: hello @DrewReese i tried this i added this lines inside handleproductselect  const user = JSON.parse(localStorage.user);
  localStorage.setItem('user', JSON.stringify(currentUser)); its updating localstorage when i logout and again llogin it is not updating at the time i click the add friend button i tried one more thing i get particular userdata by id and updated localstorage with it and it was working properly but it was givving error as the data changed userid is showing undefined.could you help me with tis
Comment: async handleProductSelect(elementid){
  const {currentUser} = this.props;
  const curid = currentUser.user._id ;
  console.log(curid)
  const data = {
    id: curid,
    fid:fid
   }
  const AddingFriendtoList = await AddFreind(data);
  console.log(AddingFriendtoList);
  const userdata = await UserService.getUser(curid);
  console.log(userdata);
  const user = JSON.parse(localStorage.user);
  localStorage.setItem('user', JSON.stringify(currentUser)); //  not updating as soon as i click  but when i use ocalStorage.setItem('user', JSON.stringify(userdata)); this is giving err
Comment: @PratikZinjurde Trying to read code in the comments is very difficult. Do you have this code hosted somewhere it can be viewed? Like in an online sandbox or your repository?
Comment: https://github.com/pratikpz18/Ping/blob/main/frontend/src/components/SearchModal.js this is my github repo you can see above code  but its not hosted yet
Comment: console.log(user.user.friendsList.push({friendId:fid})); i added this line now localstorage is updating instantly but according to mongoose schemma [0]:friendId: "603fa5b48acfb50acc21ddbc"
_id: "603fa5ca8acfb50acc21ddbe",  this is like a hack would you guide me how to keep message value of button activated even after refresh for particular user whose id=friendid in localstorage


Why do I keep getting memory allocation errors when running my php script?

Question: I'm iterating through a handful of csv files (none that exceed more than 320MB) to clean up and format the files how I need them using the follow script:
while($row = mysqli_fetch_array($rsSelect)){

    $fileName = $row["file_name"];

    if(strpos($fileName,'DATA') == true){

        $file = $dir.$row["manifest_files"]."";
        echobr($file);
        $file1 = file_get_contents($file, null);

        unset($file);
        $file2 = str_replace('","','    ', $file1);

        unset($file1);
        $file3 = str_replace('"','', $file2);

        file_put_contents($dir.$row["file_name"].".txt",$file3,FILE_USE_INCLUDE_PATH);
        unset($file2);
        unset($file3);

}

I receive the following error no matter how high I set my memory limits within php.ini or unsetting variabeles where I can to free up memory. I've tried setting the limit inside the script as well and still no go. My machine has no shortage of RAM, enough to easily store when manipulating the files as I need them.

ERROR:  ( ! ) Fatal error: Out of memory (allocated 683147264) (tried to allocate 364322204 bytes)
Comment: after last `unset` append `gc_collect_cycles();`
Answer: Using file_get_contents() requires the entire file to be read into memory in one big chunk. You're probably better off using fopen() with a loop around fgets(). This will read just one line at a time:
$fp = fopen('file.csv', 'r');
while (($line = fgets($fp)) !== false) {
    // $line is the whole line
}

Alternatively, you might be able to use fgetcsv() and process individual fields as needed:
$fp = fopen('file.csv', 'r');
while (($row = fgetcsv($fp)) !== false) {
    // $row is an array of values from the line
}

Comment: Ah, excellent explanation! Thanks for your response Alex Howasky


Linear Algebra - Determine if the set of matrices in $M_{22}$ is linearly independent or linearly dependent

Question: Is the set of matrices $\{\begin{bmatrix}0&1\\0&1\end{bmatrix},\begin{bmatrix}1&1\\2&2\end{bmatrix},\begin{bmatrix}1&4\\2&2\end{bmatrix},\begin{bmatrix}5&4\\2&6\end{bmatrix}\}$ in $M_{22}$ linearly independent or linearly dependent?
For some reason I'm stuck.
What I have done:
$A_1\begin{bmatrix}0&1\\0&1\end{bmatrix} + A_2\begin{bmatrix}1&1\\2&2\end{bmatrix} + A_3\begin{bmatrix}1&4\\2&2\end{bmatrix} + A_4\begin{bmatrix}5&4\\2&6\end{bmatrix} = 0$
What I was thinking of doing is:
$A_1(det(A_1)) +A_2(det(A_2) + A_3(det(A_3)) + A_4(det(A_4)) = 0$
I don't know if that's right but I do know I'm on the right track! Any help would be much appreciated!
Answer: Looking into the determinant in this way is heading in the wrong direction.  The determinant is not preserved under addition.  To illustrate:
$$
\overbrace{\begin{bmatrix} 2 & 2 \\ -1 & 2 \\ \end{bmatrix}}^{\text{det}=6}
+
\overbrace{\begin{bmatrix} 0 & -1 \\ 1 & -2 \\ \end{bmatrix}}^{\text{det}=1}
=
\overbrace{\begin{bmatrix} 2 & 1 \\ 0 & 0 \\ \end{bmatrix}}^{\text{det}=0}.$$
To continue, notice that the system of equations $$A_1\begin{bmatrix}0&1\\0&1\end{bmatrix} + A_2\begin{bmatrix}1&1\\2&2\end{bmatrix} + A_3\begin{bmatrix}1&4\\2&2\end{bmatrix} + A_4\begin{bmatrix}5&4\\2&6\end{bmatrix} = \begin{bmatrix}0&0\\0&0\end{bmatrix}$$
is equivalent to
\begin{align*}
A_2+A_3+5A_4 &= 0 \\
A_1+A_2+4A_3+4A_4 &= 0 \\
2A_2+2A_3+2A_4 &= 0 \\
A_1+2A_2+2A_3+6A_4 &= 0.
\end{align*}
We can solve this in the usual way (i.e., Gaussian elimination).
Alternatively, we write the matrices as the rows of a $4 \times 4$ matrix
$$
\begin{bmatrix}
0 & 1 & 0 & 1 \\
1 & 1 & 2 & 2 \\
1 & 4 & 2 & 2 \\
5 & 4 & 2 & 6 \\
\end{bmatrix}.
$$
If the rows of this matrix are linearly independent (which occurs if and only if the matrix has non-zero determinant), then the original set of matrices is linearly independent.
Answer: Hint : You get 4 equations with 4 unknowns if you solve the matrix equation
       elementwise. Note, that the sum is the null-matrix, not the number 0.
You do not need determinants.
Answer: Your first equation is correct, where $A_1,..A_4$ are scalars.
Note, that equation gives you:
$A_2+A_3+5A_4=0$
$A_1+A_2+4A_3+4A_4=0$
$2A_2+2A_3+3A_4=0$
and $A_1+2A_2+2A_3+6A_4=0$
Equations $1$ and $3$ then imply that $A_4=0$.
Equations $3$ and $4$ imply that $A_1=0$.
Ans then equations $1$ and $2$ imply that $A_2=A_3=0$.
So these are indeed linearly ind.


I have two public sites on my Ubuntu Server (Apache2). How would you distinguish the two when requesting them?

Question: Sorry if the question is unclear. I have two sites which I would like to set up in Apache2 on Ubuntu Server. Both of them should be open to the public. I would like to set up a separate IP for each of them (which I already did). I set up my router so that it forwards requests on port 80 to one of the IP addresses. How can I configure my setup so there is a way to access the other IP address?
Answer: If you have a second public IP and a NAT router which can support either a range of public IP addresses or multiple IP addresses, otherwise most simple NAT routers can not.
Most folks actually set up multiple "virtual domains" to host different web sites under the same IP/web server combination.
Comment: I have a linksys router. What do you mean by "virtual domain"?
Comment: Lenny K, based on your comments thus far, it sounds like you are missing at lease a few key components in accomplishing what you have described. The biggest one may be the registered domains as most users are accustomed to accessing web sites via text-based URLs. Most typical Linksys NAT routers (they have quite a few) will fall into the "simple" classification where they are mainly targeted at proving Internet access versus hosting Internet services (e.g. web server). What are you ultimately trying to accomplish?
Comment: The server I am setting up will not be for users to access, therefor a domain is not needed. How would I know if my router falls into the "simple" classification? I have gotten my server to work before, I have just not been able to set up two public sites. Sorry for my lack of knowledge, I am new to this :)
Comment: Look through your Linksys's WAN configuration options. Does it allow your to either specify multiple or a range/network of public IP addresses? As for the web site not needed a text-based URL, then you may be able to accomplish what you desire by setting up each "site" as a sub-folder off of the main IP-based URL as well.
Comment: I have 3 different Static DNS IP's that I can set up...and I also have an option which is the DHCP Server (which is enabled). How would I set up the VirtualHost for the sub-folders?
To Apache, it would be just one site, correct?
Comment: "I have 3 different Static DNS IP's that I can set up" - What is that? Are you referring to the DNS settings on the router? If so, that has nothing to do with the Public IP(s) that can be assigned to the Internet facing side of the NAT router.
Comment: Yes, that is what I meant. I know it has nothing to do with the public IP, just wanted to know if that is at all related to what I am trying to do.
Comment: No, your router's DNS configuration will not impact your web server setup and/or configuration.
Comment: Okay, that is what I thought. Thanks for clarifying.
Answer: You want Virtual Hosts.  Essentially, the HTTP request made by the client includes the domain name of the site they're accessing.  So the Apache server knows what content to serve them.
--Christopher Karel
Comment: I don't have a domain registered for either site at the moment. Eventually, one of the sites will have a domain, but the other will remain just an IP.
Comment: Also, my router only has one public IP. How would the user be able to decide which IP to connect to?
Comment: In that case, you need to set up the virtual hosts to listen on different ports, and then use a different site on each port.
Comment: So I could use (for example) port 80 on one site and port 8080 on another?
Answer: Along the line of the answers that have already been posted, and to keep it simple:
In Linux I believe the parlance is Virtual Hosts, as Christopher posted in his answer. Essentially you run multiple web sites on one ip address and the web server sorts out which site the incoming connection is destined for.
In Windows IIS parlance, you would set the ip based web site (the one with no domain) as the default web site on your server and you would create a second web site using host headers for the "named" web site to differentiate between the "named" web site and the "unnamed" web site. Your router would be configured to forward incoming HTTP connections on the one public ip address to the server, which would then handle the connection appropriately, based on whether the connection were meant for the "named" or unnamed" web site.
You need to figure out if name-based virtual hosts and ip-based virtual hosts configurations can be "combined" on your web platform so that you can use both methods.
Comment: I am running Linux (Ubuntu Server). What I need to find out is what the server will use to distinguish the two site requests. I don't have Windows IIS, so I can't use that right? Also, I need the site to work WITHOUT the domain temporarily. Later, I plan to add a domain.
Thanks for your help!


UIWebView shouldStartLoadWithRequest only fires once when calling a modal view from inside

Question: I have part of my app written in JS and running inside of a WebView.  I'm using the UIWebView shouldStartLoadWithRequest method to capture http requests as a means of communicating between JS and obj-c.  This works great until I attempt to load a Modal View Controller over my webview from inside the shouldStartLoadWithRequest method.  Once this happens, shouldStartLoadWithRequest is no longer called.  Sometimes I need to dismiss this modal view controller and go back to the webview and do some things and then re-present the modal controller.  The modal controller comes up the first time just fine, then I dismiss it and attempt to present it again by navigating to a URL from javascript and it no longer will present itself.  NSLogs inside shouldStartLoadWithRequest are never run.
In my javascript I do something like this:
 window.location='myapp:whateverMethod';

objective c code looks like this:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *requestString = [[request URL] absoluteString];
    NSLog(@"REQUEST URL: %@", requestString);
    if([requestString hasPrefix:@"myapp:"]) {
        NSArray *components = [requestString componentsSeparatedByString:@":"];
        NSString *function = [components objectAtIndex:1];
        if([self respondsToSelector:NSSelectorFromString(function)]) {
            [self performSelector:NSSelectorFromString(function)];
        }
        return NO;
    }
    return YES;
}

-(void) whateverMethod {
    NSLog(@"whateverMethod called!");
    // This is a quick way to grab my view controller from the storyboard, so assume it exists
    UIViewController *splash = [self.storyboard instantiateViewControllerWithIdentifier:@"splashViewController"];
    [self presentModalViewController:splash animated:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
        [self dismissModalViewController:splash animated:NO];
    });
}

At this point my webview is still visible.  I navigate from page to page in my webapp and all javascript works great in it but the "shouldStartLoadWithRequest" delegate method of the webview no longer is called.  I cannot figure out why.  Does anyone have any ideas?
Comment: After not finding a solution that fits the needs of this project I ended up imitating the modal view inside of the webview using CSS animations, etc (close enough to what the modal view looks like) and thus not having to hide the webview anymore.
Answer: I noticed that Cordova doesn't set the window.location property.  Instead it has two options: it either creates an iframe and sets the src of the iframe to that url, or it creates an XMLHttpRequest object e.g. in the iOSExec() function:
    if (bridgeMode) {
        execXhr = execXhr || new XMLHttpRequest();
        // Changeing this to a GET will make the XHR reach the URIProtocol on 4.2.
        // For some reason it still doesn't work though...
        execXhr.open('HEAD', "file:///!gap_exec", true);
        execXhr.setRequestHeader('vc', cordova.iOSVCAddr);
        if (shouldBundleCommandJson()) {
            execXhr.setRequestHeader('cmds', nativecomm());
        }
        execXhr.send(null);
    } else {
        execIframe = execIframe || createExecIframe();
        execIframe.src = "gap://ready";
    }

That being said, it may be beneficial to use something like Cordova instead of trying to roll it yourself (even if it's just embedding their view controller), since they handle a lot of the headaches that come up with webview delegates.
Comment: Interesting.  I have actually tried creating requests with both of those methods and experience the exact same result (shouldStartLoading executes until a modal window appears and then stops thereafter).  It would be interesting to try it with cordova and see if the same result happens.  It feels like a nuance in iOS, but I could be wrong.
Answer: I've just had the same problem, but related to using a href="#" anchor.
This Stack Overflow answer sorted it
There are more answers on that thread that deal with widow.location, so you may have luck with them.
Answer: Checked out Cordova and they have their own queuing system, not really a help. But...
Disobedient Media's answer gave me an idea. Instead of window.location, why not try window.location.hash.
Now some JS code for logging is:
function sendMsgToNative(msg)
{
    window.location.hash = '~cmd~' + msg;
}
console.log = function (msg) { sendMsgToNative('log~js ' + msg); };

and the Objective-C code is:
NSString *req = [request.URL absoluteString];
NSArray *components = [req componentsSeparatedByString:@"~"];

// Check for your protocol
if ([components count] > 1 && [(NSString *)[components objectAtIndex:1] isEqualToString:@"cmd"])
{
    // Look for specific actions
    if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"log"])
    {
        NSString *logStr = [(NSString *)[components objectAtIndex:3] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        LOGI("%@", logStr);
    }
}

You get the full URL including 'http:...' so I chose tilde instead of colon, and incremented the indices.
Now you can log all willy-nilly and send whatever amount of commands you want and they will all get through :-)
Answer: I (embarrassingly) spent a couple of hours working on this today, and realised that in my viewDidDisappear: I was setting the UIWebViewDelegate to nil!
All I needed to do to fix was once the modal was dismissed, re-set the UIWebViewDelegate and everything worked again.


Power Series Problem.

Question: Suppose $\sum a_nx^n$ has a finite radius of convergence, say $R$, and $a_n\ge 0$ for all $n$, show that if the series converges at $R$ then it also converges at $-R$ .
What I did: Applying the root test to the series:  $\lim_{n\to\infty}|a_nx^n|^{1/n}$,
Now the series converges at $x = R$, thus we can conclude $\lim_{n\to\infty}|(an)|^{1/n}|R| < 1$.
Now for $x = -R$, $\lim_{n\to\infty}|a_n(-R)^n|^{1/n}$, which equals $\lim_{n\to\infty}|a_n|^{1/n}|R|$ which is already less than $1$, so it converges for $x = -R$. Is this correct ??
Comment: No, you can't conclude that limit is $<1.$ An example that shows this is $\sum_{n=1}^\infty x^n/n^2.$
Comment: @zhw. so how to show that it converges for x = -R ?
Comment: Does Lt mean $\limsup$?
Comment: @HagenvonEitzen no, Limit as n approaches to infinity , here i didn't use the limitSup definition , just tried the root test directly .
Comment: @RohitDuggal There's no reason to believe that the limit exists.
Answer: Note that the Root Test is not an if and only if statement.  Convergence of the series does not imply that the limit is less than 1, in fact there are convergent series such that the limit does not exist at all.  (You can replace the limit with a lim sup, but the test might still be inconclusive.)
Your argument doesn't use the fact that the $a_n\ge 0$ for all $n$.  In general, without a constraint like this the result is false.  If you set $a_n = \frac{(-1)^n}{n}$, for instance, then the series converges at $R = 1$ but not at $-R = -1$.  My hint on how to use this condition is to write out the series for $x = -R$, and try to check that it converges absolutely.
Comment: Here's what i tried :
(-R)^n <= (R)^n ,

a(n)(-R)^n <= a(n)(R)^n { a(n) >= 0} ,

|a(n)(-R)^n| <= |a(n)(R)^n| ,

Sigma|a(n)(-R)^n| <= Sigma[a(n)(R)^n] ,

Now Sigma[a(n)(R)^n] converges as its given so by Weierstrass M test the series converges at x = -R. is it ok ?
Comment: @Rohit Duggal that does suffice to show absolute convergence, but note that once you start introducing absolute values your $\le$ inequalities can be replaced by equalities.

Power Series Problem.


Warnings with Smarty after upgrade to PHP 7.0.8

Question: After upgrading Plesk and PHP to the version 7.0.8, I'm getting the following warning when using Smarty.

PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Smarty_Compiler has a deprecated constructor in /var/www/vhosts/mydomain.com/httpdocs/Smarty/Smarty_Compiler.class.php on line 35

Here the file mentioned in the warning:
/*
 * @link http://smarty.php.net/
 * @author Monte Ohrt <monte at ohrt dot com>
 * @author Andrei Zmievski <firstname.lastname@example.com>
 * @version 2.6.20
 * @copyright 2001-2005 New Digital Group, Inc.
 * @package Smarty
 */

/* $Id: Smarty_Compiler.class.php 2773 2008-08-12 18:17:51Z Uwe.Tews $ */

/**
 * Template compiling class
 * @package Smarty
 */
class Smarty_Compiler extends Smarty {

I need help to understand the problem and how to fix it, is it relative to Smarty or fixable on my end?
Comment: share more information please like what's your php version now? and share  the full error message.
Comment: AH01071: Got error 'PHP message: PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Smarty_Compiler has a deprecated constructor in /var/www/vhosts/mydomain.com/httpdocs/Smarty/Smarty_Compiler.class.php on line 35\n'
Comment: Runing PHP version 7.0.8
Comment: I edited the title of your question to include more informations about your warning, like the PHP version you just updated to. I added to the question all new informations you provided in the comments too and improved the formatting. Good luck!
Answer: As of PHP 7.0.x, PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.
So, there's two solution:

You can turn off the deprecated warning message by adding this on your code:
error_reporting(E_ALL ^ E_DEPRECATED);
Edit the Smarty_Compiler.class.phpfile and change the method name Smarty_Compiler() to __construct()
Comment: class Smarty_Compiler extends Smarty {

    // internal vars
    /**#@+
     * @access private
     */

    /**#@-*/
    /**
     * The class constructor.
     */
    function Smarty_Compiler()
    {
Comment: yes, rename `function Smarty_Compiler()` to `function __construct()`.
Comment: it works. I changed it in two files: Smarty_Compiler... and Smarty...


How to perform multilevel lookup with possible missing values at the each level?

Question: I'm creating several variables based on query string parameters, and I have two options:

Single-line if/else statement
foo = event['queryStringParameters']['foo'] if event['queryStringParameters'] and 'foo' in event['queryStringParameters'] else None

Four-line try/except statement
try:
    foo = event['queryStringParameters']['foo']
except (KeyError, TypeError):
    foo = None

Note: the event is from AWS Lambda, so I don't have control over it
Comment: The first snippet is so wide, I have to scroll it by over 4 screen widths.
Comment: @Alexander why would you *want* it to be a `defaultdict`? Often, you don't *want* those semantics. If the only reason is to avoid doing one of the two above, then probably, IMO, it isn't what you want
Comment: Do you control `event`? Can you make it into a defaultdict?
Comment: What is the source of this dict, a JSON or similar? Maybe we can leverage this.
Comment: @Alexander but why?
Comment: @juanpa.arrivillaga why what?
Comment: @juanpa.arrivillaga Often you don't, but here it would be useful.
Comment: @Alexander I don't think it would. I think the second form here is pythonic.
Comment: @Alexander The event is from AWS Lambda
Answer: Ideally, you would just make event into a defaultdict (configured so that intermediate dicts return {} and leaf dicts return None).
You can emulate that yourself at the callsite, by using get instead of []:
foo = event.get('queryStringParameters', {}).get('foo', None)

But as you see, it's more cumbersome.
Comment: how would you configure a defaultdict to distinguish between "intermediate" and "leaf" nodes, unless you now the expected depth beforehand? This could use an actual concrete example
Comment: @juanpa.arrivillaga Good question. You're right, you would need to know the depth beforehand. That may or may not be possible, depending on OPs circumstances, which we don't know about. Without further details, a concrete example would just be a shot in the dark.
Answer: The second version with the try/except is more easily digestible.
If you have an aversion to try/except, the dict.get() method would also be useful here:
qsp = event.get('queryStringParameters')
foo = qsp and asp.get('foo')

As suggested by the commenter, a match/case (for Python 3.10 or later) would also work, but I don't think it is as clear as the try/except version or the get() version:
match event:
    case {'queryStringParameters': {'foo': foo}}: pass
    case _: foo = None

Comment: @acoordes the `try-except` approach you have is perfectly fine
Comment: Yes, that would work as well.   I don't think it is a win for clarity though.
Comment: Btw, would you recommend `match` syntax for these kinds of problems? Something like `case {'queryStringParameters': {'foo': val, **x}, **y}`?
Comment: I'm stuck in Python 3.7, so `match` isn't an option
Answer: Let's try generalizing the kind of logic @Alexander employed in that answer to allow for looking up with any number of levels of nested dictionaries.
def nested_get(d, default_val, *keys):
    d2 = d
    for k in keys:
        if not isinstance(d2, dict): return default_val
        d2 = d2.get(k, {})
    return d2

Now:
foo = nested_get(event, None, 'queryStringParameters', 'foo')


Como verificar se um número é par ou ímpar?

Question: Como faço para descobrir se um determinado número que está armazenado numa variável é par ou ímpar com PHP?
Comment: Gonçalo, conseguiu resolver seu problema com a resposta? Ou precisa de mais alguma informação?
Answer: No PHP, como pode haver em várias outras linguagens, uma forma de saber se um número é par ou ímpar, pode se usar o operador %, que significar MOD, para calcular o "resto" da divisão do valor. Se o resto do número tem valor zero, então sabemos que o resultado é par. Segue abaixo:
if($valor % 2 == 0){
     echo "par";
} else {
     echo "impar";
}

Código simplificado usando operador ternário:
echo !($valor % 2) ? "par" : "impar";

Answer: Uma outra alternativa com o operador bitwise &:
$numero = 3;

if ( $numero & 1 ) {
  echo "$numero é impar!";
} else {
  echo "$numero é par!";
}

O operador & faz a comparação dos valores usando sua forma binária, cada bit é comparado, retornando 1 quando ambos os bits forem iguais a 1, caso contrário retorna 0.
No exemplo acima o número 3 em binário é 00000011 e 1 é 00000001, o resultado dessa operação é 00000001, o número mais a direita é 1 (e nesse caso indica que é um número ímpar) ou é 0, que indica que é um número par.
Veja um exemplo:
  00000011 // 3
& 00000001 // 1
= 00000001 (ímpar)

  00000110 // 6
& 00000001 // 1
= 00000000 (par)

Veja também: Qual o uso prático de operadores bitwise em PHP?
Comment: Muito bom Stderr! Mas tem um pequeno detalhe. Faça um caso de teste sendo `$numero = 9209458740945999;` , e veja o resultado.
Comment: Acontece nos dois casos, usando `mod` e usando `bitwise`.
Comment: @CleidimarViana Valeu. :) Para corrigir isso, você teria que usar o [`BC Math`](http://php.net/manual/en/ref.bc.php) ou [`GMP`](http://php.net/manual/en/ref.gmp.php) ou outra alternativa. Por exemplo, com o BC Math da para usar a função [`bcmod`](http://php.net/manual/pt_BR/function.bcmod.php) veja um [**exemplo**](http://ideone.com/dPzpUi).


Knock out tournament 3

Question: Thirty-two players ranked 1 to 32 are playing in a knockout tournament. Assume that in every match between any two players, the better-ranked player wins, the probability that ranked 1 and ranked 2 players are winner and runner up respectively, is?
My approach:

But the given answer is 16/31. Could someone please explain where i went wrong?
Comment: The lowest ranked player cannot get through the first round, but in your calculation that player could fill one of the blanks after the first round.
Comment: It's obvious that it should be $\frac{16}{31}$: whatever half of the bracket the rank 1  player is in, the rank 2 player should be in the other half.   But, that doesn't explain what went wrong with your approach. See my Comment above and Haris' answer for that, and also see Haris' answer for a nice fix that does follow your approach.
Comment: Please don't use images of text/math on this site.
Answer: There are a couple of mistakes in your approach.
One, you are excluding player 1 (top-ranked) from all five matches - the whole tournament basically. You should be considering only the first four matches.
Two, your approach assumes that every player is equally likely to face the top ranked (or second ranked) player in the four matches building up to the finals. That's not correct. The lower a player's rank, the less likely he/she is to play against either of the two players.
Correct Solution
Here's one approach we could take to solve this problem.
There will be $4$ matches before the final. For players with rank $1$ and $2$ to be the winner and the runner-up, they must both reach the finals. And for that to happen, the only condition necessary is that they don't meet in earlier matches. They are guaranteed to win against other opponents.
Looking at things from the perspective of any of the two players (I'm going with rank 1), the total number of ways in which their opponents to the first four matches can be selected are $31 \times 15 \times 7 \times 3$. In the first round, there are 31 players to choose from, in the second, 15, and so on.
But for the question's condition to be met, we will have to exclude the second-ranked player in each stage. Remember they can't play against each other before the final. So, the number of ways to choose opponents for player 1 would be $30 \times 14 \times 6 \times 2$.
Hence the required probability would be
$$\frac{30 \times 14 \times 6 \times 2}{31 \times 15 \times 7 \times 3} = \frac{16}{31}$$
Comment: Nice!  Good explanation what is wrong with the OP's calculation ... and a nice fix too! There is of course a much easier way to see that the probability should be $\frac{16}{31}$, since the two players simply need to be on opposite sides of the bracket when split in half, but your approach is still in line with the approach the OP is taking... it effectively fixes where the OP went wrong in the details, thus showing that the OP's way of thinking can still work, instead of offering up the much simpler explanation that follows a completely different approach. Good work! :)
Comment: Thank you for your kind words. The solution you propose would be so much more elegant, besides being simpler. The difference would become much obvious if there were more players, say, 256. Why don't you go ahead and post it as an answer? I think it would be helpful to many who may not read the comments.
Comment: OK, will do!  Just want to make sure the OP accepts your Answer, rather than mine. I'll add a note :)
Comment: Greatly appreciate it! :)
Comment: Thanks! I got my mistake
Answer: What is wrong with your calculation is that you don't take into account that for any match the lower-ranked player always loses. So that puts constraints on which players can be placed in the 'blank' spots, whereas in your calculation any players could end up in any black spot. As a simple example: the lowest ranked player cannot get through the first round, but in your calculation that player could fill one of the blanks after the first round.
Now, I really like @Haris Answer in which they give the same explanation .. but also provide a nice fix using your approach! So you should definitely accept their Answer!
Still, I like to point out that it can be much more easily established that the probability should be $\frac{16}{31}$: in order for the two players to end up in the final, they need to be in opposite halfs of the bracket. So, wherever the rank $1$ player goes, the rank $2$ player needs to be in one of the $16$ spots of the other half, rather than in one of the $15$ spots of the same half.

Knock out tournament 3


Examples for Kripke semantics for intuitionistic logic

Question: In my previous question,  Mees de Vries talked about Kripke semantics and
reading his links, I tried to show that $(X\wedge \neg Y)\rightarrow Z \vdash X\rightarrow (Y\vee Z)$ is valid using Kripke semantics.
Here is my answer, but I'm not sure whether it is right or not:
Since $(X\wedge \neg Y)\rightarrow Z$, for any world $u\ge w$, if $X\wedge \neg Y$ holds at $u$, then $Z$ holds at $u$.  What I want to show is for any world $u \ge w$ if $X$ holds at $u$, then  $Y\vee Z$
holds at $u$.
Let's call $u_X$ be the world where $u_X\ge u$ and $X$ holds at $u_X$. Then  For any such $u_X\ge w$, either $Y$ or $\neg Y$ holds at $u_X$.  If $\neg Y$ holds at $u_X$, then $(X\wedge \neg Y)$ holds at $u_X$. So, by the premise above, $Z$ holds at $u_X$, ans so does $Y\vee Z$. If $Y$ holds at $u_X$, then $ Y \vee Z$ holds at $u_X$.  So, it is valid intuitionistically.
Is it right?
Comment: Must be : What I want to show is for any world $u≥w$ if $X$ holds at $u$, then $Y∨Z$ holds at $u$.So, last paragraph must be : If $Y$ holds at $u_X$, then $Y∨Z$ holds at $u_X$. If $¬Y$ holds at $u_X$, then $(X∧¬Y)$ holds at $u_X$ and thus also $Z$ and $Y∨Z$.
Comment: @MauroALLEGRANZA There's some error in my question. I edited. Thanks :)
Answer: There is an incorrect step where you say, "either $Y$ or $\neg Y$ holds at $u_X$."  In Kripke semantics, you do not always have, for an arbitrary node $\alpha$ and sentence $\varphi$ that $\alpha\Vdash\varphi$ or $\alpha\Vdash\neg\varphi$.  What you do have is that either $\alpha\Vdash\varphi$ or $\alpha\nVdash\varphi$, but $\alpha\nVdash\varphi$ does not imply $\alpha\Vdash\neg\varphi$.


Partial differential equation, known solution

Question: Knowing that any solution of $y \frac{\partial ^2 u}{\partial y^2} + 2 \frac{\partial  u}{\partial y} = \frac{2}{x}$ is of the form $u(x,y) = \frac{\varphi(x) + y^2}{xy} + \psi(x)$,
where $\varphi, \ \psi $ are $C^2$,
find the solution of
$(1) \ \ y \frac{\partial ^2 u}{\partial y^2} + 2 \frac{\partial  u}{\partial y} = \frac{2}{x}, \ u(x,x)=g(x)$
and of
$(2) \ \ y \frac{\partial ^2 u}{\partial y^2} + 2 \frac{\partial  u}{\partial y} = \frac{2}{x}, \ u(y^3, y)=g(y)$.
Here $g: \mathbb{R} \rightarrow \mathbb{R}$ is a given function.
I'm having problems solving this.
I've solved a similar problem $\frac{\partial u}{\partial x} = 2x \frac{\partial u}{\partial y}, \ u(4,y)=g(y)$, ($g$ is given) where the solution was $u(x,y)=\varphi(y+x^2)$ and I just plugged $\varphi$ to the equation: $\varphi(y+16)=u(4,y)=g(y), \ \ \varphi(y)=g(y-16), \ \ u(x,y)=g(x^2+y-16)$.
But here it doesn't seem to work. Could you explain to me how to solve it?
Thank you!
Comment: is this two different problems ((1) and (2)) or must both conditions be satisfied simultaneously?
Comment: These are two different problems. I'll edit the question to make it less confusing.
Answer: This is a second order equation. The general solution depends on two arbitrary functions ($\phi$ and $\psi$.) If you impose only one condition, you will get infinite answers depending on one arbitrary function. Consider (1). You want
$$
u(x,x)=\frac{\phi(x)+x^2}{x^2}+\psi(x)=g(x).
$$
You can choose $\psi$ arbitrarily and let
$$
\phi(x)=x^2(g(x)-\psi(x)-1).
$$
On the other hand, if you impose both conditions (1) and (2), you will get a system of two equations with the two unknowns $\phi$ and $\psi$, and you will find (in most cases) a unique solution $u$.
Comment: I see. Thank you a lot!


TinyMCE plugin not showing euro symbol

Question: I use the last update of the TinyMce plugin and I have a problem with the € key. Nothing happens when I want to insert this € symbol [with ctrl + alt + e].
I read the doc but I dont know what to edit for make it works...
Answer: With TinyMce you can "insert special character" with a plugin
It is in the TinyMce documentation :
"This plugin adds a charmap toolbar button that enables users to insert special characters into their text. It also adds the menu item Special character under the Insert menu."
https://www.tinymce.com/docs/plugins/charmap/
Hope this helps

TinyMCE plugin not showing euro symbol


a simple example of a non-continuous function whose graph is homeomorphic to the domain

Question: There is a theorem that says that if $f$ is a continuous map, then its graph is homeomorphic to the domain. The converse is false. I'd like to find the simplest counterexample possible. I've found this
$f:\mathbb{R}\longrightarrow \{0,1\}$,
where $\mathbb R$ is endowed with the topology generated by the sets $\{1\},\{2\},\{3\},...$ and $f(x)=1$ for $x=0,1,2,...$ and $f(x)=0$ otherwise.
Is there a simpler example?
edit: In my example, $\{0,1\}$ has discrete topology.
Comment: I don't think that your example works. The topology on $\mathbb{R}$ gives it $\omega$ isolated points, and the only nbhd of any other point is all of $\mathbb{R}$. The graph of $f$ has $\omega$ isolated points, but $\langle 0,f(0)\rangle$ is a non-isolated point that has a proper subset of the graph as a nbhd, and the isolated points of the graph are not dense in the graph.
Comment: What do you mean by domain here? An open connected set?
Comment: No! By "the domain" I meant the domain of $f$. http://en.wikipedia.org/wiki/Function_%28mathematics%29#Definition
Comment: Oh I see. Got it. How stupid I am! I keep thinking of domain in the set of point-set topology.
Comment: Does anyone know a reference for the result that the graph of a continuous function is homeomorphic to its domain?
Comment: @Michael: Engelking, Cor. 2.3.21.
Comment: Thank you! It is actually Cor.2.3.22.
Comment: @Michael: Oops. You're right: eye-slip.
Answer: Here's one that seems easy to visualize.
Take $X = [0,1) \times \mathbb{N}$ with its usual topology; i.e. $X$ is a countable disjoint union of half-open "sticks".  Define $f : X \to \mathbb{N}$ by
$$f(x,n) = \begin{cases} 1, & n=1, x < 1/2 \\ 2, & n=1, x \ge 1/2 \\ n+1, & n > 1.\end{cases}$$
Then a homeomorphism from the graph of $f$ to $X$ is given by
$$F((x,n),k) = \begin{cases} (2x,1), & k=1 \\ (2x-1, 2), & k=2 \\ (x,k), & k > 2. \end{cases}$$
(Hopefully I have written it correctly.)
The idea is that the graph looks just the same, except that the first stick has been broken in half.  By stretching the half-pieces we get two full-size sticks.  But there were already infinitely many sticks, so adding one more doesn't produce an "extra" if we re-index.
Answer: Nate's is nicer, but here's an example based on the proposer's original idea.
Topologize $\mathbb{Z}$ as follows: each even integer is an isolated point, and if $n$ is odd, a set $V$ is a nbhd of $n$ iff $V\supseteq\mathbb{Z}\setminus 4\mathbb{Z}$. Call the resulting space $X$. Let $A=\{4n+1:n\in\mathbb{Z}\}$, give $D=\{0,1\}$ the discrete topology, and let $f:X\to D$ be the indicator (characteristic) function of $A$. Clearly $f$ is not continuous, since $A=f^{-1}[\{1\}]$ is not open in $X$.
Now let $G$ be the graph of $f$. The set of isolated points of $G$ is
$$I=\Big(A\times\{1\}\Big)\cup\Big(2\mathbb{Z}\times\{0\}\Big)\;.$$
If $p\in G\setminus I$, then $p=\langle 4n+3,0\rangle$ for some $n\in\mathbb{Z}$, and a set $V\subseteq G$ is a nbhd of $p$ in $G$ iff $V\supseteq \Big(\mathbb{Z}\setminus \big(A\cup 4\mathbb{Z}\big)\Big)\times\{0\}$. From this it's not hard to check that the function
$$h(n)=\begin{cases}
\left\langle \frac{n}2,0\right\rangle,&\text{if }n\equiv 0\pmod 8\\\\
\left\langle\frac{n}2-1,1\right\rangle,&\text{if }n\equiv 4\pmod 8\\\\
\langle n,0\rangle,&\text{if }n\equiv 2\pmod 4\\\\
\langle 2n+1,0\rangle,&\text{if }n\equiv 1\pmod 2
\end{cases}$$
is a homeomorphism of $X$ onto $G$: the first two clauses match up the isolated points that don't have to belong to nbhds of the non-isolated points; the third matches up the other isolated points; and the fourth matches up the non-isolated points.


Mediapipe runtime error whilst following the Hand_landmarker guide. Unable to initialize runfiles

Question: I am trying to follow the getting started guide for the hand landmarks in mediapipe for python but when I try to run it I get a runtime error.
Traceback (most recent call last):
  File "C:\Users\Tom\PycharmProjects\MediaPipe\mediapipe_static.py", line 12, in <module>
    with HandLandmarker.create_from_options(options) as landmarker:
  File "C:\Users\Tom\PycharmProjects\MediaPipe\venv\lib\site-packages\mediapipe\tasks\python\vision\hand_landmarker.py", line 271, in create_from_options
    return cls(
  File "C:\Users\Tom\PycharmProjects\MediaPipe\venv\lib\site-packages\mediapipe\tasks\python\vision\core\base_vision_task_api.py", line 66, in __init__
    self._runner = _TaskRunner.create(graph_config, packet_callback)
RuntimeError: Unable to initialize runfiles: ERROR: external/bazel_tools/tools/cpp/runfiles/runfiles.cc(120): cannot find runfiles (argv0="")

I am running on:

python 3.10.8
pip 23.0.1
mediapipe 0.9.2.1

This is the code I ran
import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
HandLandmarker = mp.tasks.vision.HandLandmarker
HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a hand landmarker instance with the image mode:
options = HandLandmarkerOptions(
    base_options=BaseOptions(model_asset_path='[path to hand_landmark.task]'),
    running_mode=VisionRunningMode.IMAGE)
with HandLandmarker.create_from_options(options) as landmarker:
    # Load the input image from an image file.
...

I tried changing the model_asset_path but this seemed to not be the issue here.
Comment: This seems to be an open issue with media pipe at the moment. https://github.com/google/mediapipe/issues/4272
Answer: This appears to be a known issue with MediaPipe right now, as @Pollcosso mentioned.  The best solution is to use the media_asset_buffer option, which requires you to load the file as bytes and then pass the byte object to the factory method:
    model_file = open('hand_landmarker.task', "rb")
    model_data = model_file.read()
    model_file.close()

    base_options = python.BaseOptions(model_asset_buffer=model_data)
    options = vision.HandLandmarkerOptions(base_options=base_options, num_hands=2)
    detector = vision.HandLandmarker.create_from_options(options)


pytest test with --ignore and --junitxml generate xml with ignored tests

Question: I am using pytest with --ignore and --junitxml options to generate a report of the test cases those are not ignore but when my report is generated, It also takes into account the ignored tests.
I am using the following command
pytest --ignore=tests/test_a.py --junitxml=pytest_not_a.xml
Comment: Hi @MrBeanBremen , I am able to run the above pytest command but while the junit generate the report on gitlab report it keeps the --ignore test file's test as skipped ones and it also takes those into percentage calculations.
Comment: Hm, I don't know - I just tested it locally, and the ignored test is not referenced in the generated xml. Sorry, no idea what may be different in your setup...
Answer: I am able to resolve this using pytest.mark.httpapi, so rather than using it over each test suite. I added pytest_collection_modifyingitems which puts the marker on the test on run time.
def pytest_collection_modifyitems(config, items):
    for item in items:
        if 'test_a.py' in str(item.fspath):
            mark = getattr(pytest.mark, "httpapi")
            item.add_marker(mark)
            item.add_marker(pytest.mark.common)

Now the above command would be slightly changed like
py.test -v -m "not httpapi" --junitxml=pytest_not_a.xml. Now the Junit gitlab artifacts only takes the processed tests and do not include skipped tests in success rate calculation.


Notating manuals and pedal on a pipe organ

Question: What is the easiest way to notate an original piece for pipe organ (two manual) and pedal? I would like to have:

The left hand play a tonal chord on the Great Manual
The right hand play a melody on the Swell Manual
The feet play on the Pedalboard
Have a cluster of sound on the Positive
Comment: There is a contradiction here. The first sentence indicates a two-manual organ, but three manuals are listed: Great, Swell, and Positive.
Answer: An obvious question is how is the cluster going to be played, if the organist is using both hands for something else. Of course, you can use weights to hold down the keys, provided the organist has time to manipulate them. It's not entirely unknown for an assistant (whose main functions are to change the stops if the instrument doesn't have modern automation technology, and to turn the pages) to play a few notes when required!
But aside from that, it's quite common to use more than 3 staves for organ music that requires complicated registration. Split up the notation so that the music for each manual is on one (or even two) staves of its own.
Answer: I may be misunderstanding the question but you can notate organ music on MuseScore. You just create a new piece then follow the Wizard.

In the first menu, you pick a title and all the other type of titles.
At the second menu, you are given various choices in regards to
templates.
Here you have to click on the choose instrument tab.
Click on the Keyboard header.
Choose between Pipe Organ or regular Organ
Choose A Key Signature
And lastly pick a Time Signature, pickup measure and the amount of
bars the piece has.

That gives you something resemble this which should be adequate for most Organ pieces. I don't know enough about Organ music to know if this is adequate to your needs.


Converting Hexidecimal Strings to Numeric Types and back

Question: I need a function to convert hex values in the format 0xFFFF (2 Bytes) to decimal (unsigned and signed).
For example:
0xFFFE is 65534  (unsigned)
0xFFFE is -2     (signed)
I need also the same thing for 4 Bytes and 1 Byte.
All these options (3 * 2 options) I need to convert back - from decimal to hex (total 12 options).
My function should look like this:
    string Myconverter(int ByteSize, bool IsFromHextoDecimal, bool IsSigned)
    {
        ...
    }

If there's build in functionality that performs these conversions, I'd like to a reference/link.
Comment: Have a look at [How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/bb311038.aspx) (courtesy of MSDN)
Answer: Use methods in the Convert class to parse the string to a number. To parse an unsigned 2 byte value you use the ToUInt16 method, and specify the base 16:
ushort value = Convert.ToUInt16("0xFFFF", 16);

Use these methods for other format:
ToInt16  = signed 2 byte
ToUInt32 = unsigned 4 byte
ToInt32  = signed 4 byte
ToByte   = unsigned 1 byte
ToSByte  = signed 1 byte

To format a number to a hexadecimal string you can use the X format (or x to get lower case letters) and specify the number of digits:
string formatted = value.ToString("X4");

That will however not have the 0x prefix, so if you want that you have to add it:
string formatted = "0x" + value.ToString("X4");


Some images are not displayed in IE

Question: Some images fails to load on IE.
DOM7009: Unable to decode image at URL: '[some unique url]'.

The URL are set to sites/default/files/styles/image/image_name.jpg?itok=RANDTOKEN
I can fix the error by removing the header in .htaccess
Header always set X-Content-Type-Options nosniff

But that does not seem to be a right solution. Any ideas why it behaves like this?
Answer: I'm inclined to believe this is a MIME type (or Content Type) configuration issue on the server because the "X-Content-Type-Options nosniff" would bypass this kind of problem.  That header is telling Internet Explorer to not extract MIME type info from the server response.
IE is very unforgiving these days (since IE 10 or so) with respect to the MIME type reported by the server. If your server is reporting that Jpegs are text or pngs, for example, Internet Explorer will fail to render it even if the extension is a well-known extension like "jpg."
Adding/Correcting MIME Types in Apache
You have many different ways to fix your server's reported mime type.
.htaccess (overrides server configuration)
If you're stuck with just editing your .htaccess file, add AddType image/jpeg jpeg jpg jpe to it in order to override whatever is happening with the server.
mime.types or httpd.conf (actually fixing the server configuration)
If you have full access to your server, try to locate the "mime.types" file on your server (assuming it exists) or add the "AddType" line to your httpd.conf file if jpegs aren't defined anywhere.  It's possible that the "jpg" extension or "jpeg" MIME type already exists in one of these files and is just not correctly configured.
A restart of Apache will make sure config changes are in place when you see if the problem is fixed, too.
See also
If this problem persists, there is also another question in Stack Overflow at: https://stackoverflow.com/questions/27934411/images-failing-to-load-in-ie-with-dom-7009-error-unable-to-decode-in-console that has many alternative causes.
Comment: For the common image types:      AddType image/jpeg .jpeg .jpg .jpe .JPG
AddType image/gif .gif .GIF
          AddType image/png .png

Some images are not displayed in IE


spark dataframe select one element from array but the value is not the right one

Question: df.select($"onenews".getItem(1), $"onenews").show(5,false)

the result shows as follows, the field value getItem(1) isn't right, and the column "onenews" I got is from string's split sections.

I have known the reason, it's because of spark's lazy computing, the onenews's column is computed from a function which contains shuffle.
Comment: What is the question?
Comment: onenews[1]  the value isn't right, see the onenews array
Comment: Arrays indexes started with 0, first element is "getItem(0)"
Answer: I didn't understand your question clearly, as per my understanding if you want to fetch 0th element from onenews column, you need to use getItem(0) insted of getItem(1).
sample code:
df.select(df.col("onenews").getItem(0)).show()

Comment: $"onenews".getItem(1)'value isn't  onenews(1), you can see it clearly in the picture


Can a non-differentiable space, such as the Weierstrass curve, be connected?

Question: I'm not a mathematician and I'm very new to topology, I'm just a guy who's curious about shapes.
My favorite function is the Weierstrass function, which is continuous everywhere but differentiable nowhere. Is its curve connected? Is that even a valid question to ask for a non-differentiable curve?
Thanks for your time.
Comment: Check out [this question](https://math.stackexchange.com/questions/1573795/proof-of-the-continuous-image-of-a-connected-set-is-connected)
Answer: Yes. More generally, the image of any continuous function from an interval to $\mathbb{R}$ will be path connected: let $f : I \subseteq \mathbb{R} \rightarrow \mathbb{R}$ be a continuous function on an interval $I$ (such as the whole real line) and let $\mathcal{C} := im(f)$ be its image. Now, pick any two points $y,y' \in \mathcal{C}$ so that there exist $x,x' \in I$ with $f(x) = y$ and $f(x') = y$. Since $I$ is an interval and $x,x' \in I$, we have that $[x,x'] \subseteq I$ and thus we can take the following continuous path:
$$
\gamma : [x,x'] \to \mathcal{C} \\
t \to f(t)
$$
which verifies $\gamma(x) = f(x) = y$ and $\gamma(x') = f(x') = y'$ as desired.
Moreover, any continuous function from a (path) connected space will have a (path) connected image.
For path connectedness, the proof is the following: let $f: C \to D$ be a continuous function with $C$ path connected and let $p,q \in im(f)$ with $p = f(a)$ and $q = f(b)$. By path connectedness of $C$, we have a path $\gamma$ from $a$ to $b$. Thus,  $f \circ \gamma$ is a path from $p$ to $q$.
The connected case requires a bit more topology (but not that much).
Answer: Yes, the graph of the function is connected.
Let $f \colon [0,1] \to \mathbf{R}$ be any continuous function.
Then the mapping $F \colon [0,1] \mathbf{R}^2$ defined by $F(t) = (t,f(t))$ is itself continuous. The graph in question is the image of $[0,1]$ under the mapping $F$. But the image of a connected set under a continuous mapping is connected. Since $[0,1]$ is connected, the graph is connected.


'Extra argument in call'

Question: I am getting an error in my super.init as soon as I call an Enum data type from a super class. What am I doing wrong here?
class Atleta : Pessoa {

    var beltRanking : Int = 1
    let previousGraduation : Date
    var nextGraduation : Date

    init(beltRanking: Int, previousGraduation: Date, nextGraduation: Date) {

        self.beltRanking = 1
        self.previousGraduation = previousGraduation
        self.nextGraduation = nextGraduation

        super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: RolePessoa) {

            self.name = name
            self.country = country
            self.birthDay = birthDay
            self.email = email
            self.joiningDate = joiningDate
            let role = RolePessoa()

        }

    }

Enum declaration on another file/class:
enum RolePessoa {
    case Aluno
    case Funcionario
    case Instrutor
    case Visitante
}

Here's the Pessoa class:
class Pessoa {

    var bodyStats : BodyStats = BodyStats()
    let name : String
    let country : String
    let birthDay : Date
    let email : String
    let joiningDate : Date
    var role : RolePessoa

    //    var typeOfCar : CarType = .Coupe

    init(name: String, country: String, birthDay: Date, email: String, joiningDate: Date, role: RolePessoa) {

        self.name = name
        self.country = country
        self.birthDay = birthDay
        self.email = email
        self.joiningDate = joiningDate
        self.role = .Aluno

    }

}

Comment: And your call to `super.init` has the wrong syntax. You don't add the `{ ... }` part to the call.
Comment: You should look at in the Swift book for the proper syntax. See [Designated and Convenience Initializers in Action](https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID223)
Comment: I absolutely Absolutely will.
Answer: Issue description
There are brackets in the code after the super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: RolePessoa) method call in Atleta class. Swift compiler thinks that it is a closure passed as the last parameter.
Solution
The intention here was to call super.init method and pass correct parameters there. We can change the method call to fulfil the goal:
super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: .Aluno)

Note, that we are passing .Aluno as a role as it is used in the Pessoa class initializer anyway.
Refactoring suggestion
You might want to remove the role from initializer parameters to simplify the code or assign the default value to it like this:
init(name: String, country: String, birthDay: Date, email: String, joiningDate: Date, role: RolePessoa = .Aluno) {

    self.name = name
    self.country = country
    self.birthDay = birthDay
    self.email = email
    self.joiningDate = joiningDate
    self.role = role
}

Then super init call can be changed in a next way:
super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate)

Note, that in this case, we don't specify role at all as it is assigned .Aluno by default.
We can also specify a different role if needed:
super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: .Funcionario)

There is good official documentation about initializers to read for beginners: Initialization.
Comment: You are overlooking the fact that the call to `super.init(name: name, ...)` is referencing non-existent variables. The extraneous block is only the first of several issues.
Comment: @rmaddy Yes. The title of the question is about `'Extra argument in call'`, so the answer suggests how to solve that problem. I don't think that we have enough information, for now, to suggest what to use instead of the missing values. Do you think, we should mention this in the answer?

'Extra argument in call'


A natural minor scale with raised fourth

Question: Good day
I am trying to understand what scale/mode is created by raising the fourth of a natural minor. It sounds quite dark. I understand that natural minor is the Aeolian mode of the major scales, thus, natural minor cannot have its own sets of modes, is this right?
Regardless, the piece of music center on the tonic, in this case A minor in the left hand on the piano with many diatonic chords of A minor in the right hand, all of which has no sharp or flats, thus pure A natural minor. So tonal center is kept in A and in a minor scale throughout, but then there is a F dominant 7th chord that resolves back to Am. Surely this must be a modal change? The F7 chord is F A C D#. The Mixolydian scale of F has a Bb and Eb. The piece I am playing has no B flats. I don't believe the gypsy scale nor double harmonic scale explained this case.
By all means, correct me if I'm wrong.
Thank you in advance for any explanations.
Answer: If you have a natural minor with a raised fourth (#4), let's say starting from A, you would have A B C D# E F G (A) . If you start that scale from E, you would get the minor Neapolitan scale, in which scale the fourth mode is Natural Minor ♯4 or Romani Minor or Aeolian #4.
This mode has the scale degrees you were asking about:

The F7 chord is F A C D#. The Mixolydian scale of F has a Bb and Eb.

You have a mistake here. The F7 chord would be F A C Eb (Eb, not D#). Without the song you are referring to, it's hard to be sure what the F7 chord is there for.
Comment: Weirdly, a similar thing was asked [earlier today](https://music.stackexchange.com/questions/111529/what-is-a-name-of-a-major-scale-with-raised-2nd-degree).
Comment: Looks like the OP's like the modes of the Neopolitan Minor scale!
Answer: I would not be too concerned by notes not in the scale, all notes can be used without weakening the tonality. For instance, think of the numerous hymn tunes that use chromatic chords. In the key of C the harmonic progression of C D7 G is an imperfect cadence that does not affect the sense of tonality.
In traditional harmony the chord of F A C D# is perfectly acceptable and does not imply a change of mode. It is an effective cadential chord because the D# resolves upwards to E and the F resolves down to E. The difference is that in traditional classical harmony, this chord would usually be followed by the dominant chord on E - with or without the 7th. The dominant chord E could be preceded by the 2nd inversion of Am but probably never Am in root position.
The chord you describe is not a dominant seventh chord - as Shevliaskovic pointed out - as it is D# not Eb. It's an augmented sixth chord, a German sixth to be precise. You can find more information here:
Augmented 6th chords
Comment: Thank you for the comment on the augmented 6th chord, this describes the chord better. Shevliaskovic answered my question exactly right. I could not find anything on my own research.
Answer: If the resolving chord is Am/E (slash chord am64) and not Am in root position this is 100% a German6th.


Why is $L^p(S) \subseteq L^q(S)$?

Question: Let $\mathbb{K} = \mathbb{R}$ or $\mathbb{K} = \mathbb{C}$.
Exercise: Let $p,q\in(1,\infty)$ and let $1\leq p<q<\infty$. Show that $L^p(S) \subseteq L^q(S)$.
What I've tried:
I know that $L^p(S) = \{f:S\to\mathbb{K}:\text{ $f$ measurable and }\int_S \left|f\right|^p d\mu < \infty\}$ and $L^q(S) = \{f:S\to\mathbb{K}:\text{ $f$ measurable and }\int_S \left|f\right|^q d\mu < \infty\}$. $L^p(S)\subseteq L^q(S)$ would mean that for every $f$ such that $\int_S \left|f\right|^p d\mu < \infty$ we would have $\int_S \left|f\right|^q d\mu < \infty$. I don't know how to show that this is true though.
Question: How do I solve this exercise?
Comment: What are $\mu$ and $S$?
Comment: This is not true, unless there's an assumption about $\mu$ that you haven't told us about...
Comment: If $\mu$ is a probability measure you can use Jansen's inequality.
Comment: Possible duplicate of https://math.stackexchange.com/questions/1397097/how-to-show-that-lp-norm-is-monotone-increasing
Comment: please clarify and define your terms
Comment: @yanko No, for a probability measure the inclusion is in the other direction.
Comment: Is the inclusion really in the correct direction?
Comment: The inclusion can go either way, depending on the measure space. Meaning of course also that there may be no inclusion at all.
Comment: Suppose that $0 < p < q ≤ ∞$. Then $L^q(S, μ) ⊂ L^p(S, μ)$ iff $S$ does not contain sets of finite but arbitrarily large measure, and
$L^p(S, μ) ⊂ L^q(S, μ)$ iff $S$ does not contain sets of non-zero but arbitrarily small measure.

https://en.wikipedia.org/wiki/Lp_space
Comment: Possible duplicate of [$L^p$ and $L^q$ space inclusion](https://math.stackexchange.com/questions/66029/lp-and-lq-space-inclusion)
Answer: In general there need not be any inclusion between $L^p(S,\mu)$ and $L^p(S,\mu)$, for an arbitrary measure space $(S,\mu).$
However if your measures are bounded, there are inclusions. See for example Wikipedia. Thus criteria for inclusion of $L^p$ spaces is, for $0<p<q\leq\infty$:

$L^q(S,\mu)\subseteq L^p(S,\mu)$ iff $S$ does not contain sets of finite but arbitrarily large measure,
$L^p(S,\mu)\subseteq  L^q(S,\mu)$ iff $S$ does not contain sets of non-zero but arbitrarily small measure.

Let's see this with some examples.
For example, let $S$ be the positive natural numbers line $S=\{n\in\mathbb{N}|n>0\}$ with counting measure. This space has sets of arbitrarily large measure, and the sequence $1/n^{1/p}$ is in $L^q$ but not $L^p$, so we have $L^q\not\subseteq L^p.$
Or let $S$ be the real interval $(0,1)$ with the Lebesgue measure. This space has sets of arbitrarily small measure, and the function $1/x^{1/q}$ is in $L^p$ but not $L^q$, so we have $L^p\not\subseteq L^q.$
The interval $(0,\infty)$ has sets of arbitrarily large and small measure, so neither inclusion holds, as the functions $1/x^{1/q}$ and $1/x^{1/p}$ show.
If the measure is both bounded above and bounded below, then there are inclusions going both ways, and $L^p$ and $L^q$ are isomorphic as topological vector spaces. I think this only happens if $S$ is finite and so $L^p$ is finite-dimensional, where all norms are equivalent.

So the upshot is, if we would like to prove one or the other inclusion, we must adopt one of the assumptions about our measure space.
So let's adopt axiom 1, then $S$ must have finite measure. Now $p<q$, so $q/p>1$, so $x\mapsto x^{q/p}$ is a convex function, so by Jensen's inequality, we have
$$\left(\frac{1}{\mu(S)}\int\lvert f\rvert^p\right)^{q/p}\leq \frac{1}{\mu(S)}\int \lvert f\rvert^q,$$
so $\lVert f\rVert_p\leq \mu(S)^{\frac{1}{p}-\frac{1}{q}}\lVert f\rVert_q$ and so $L^q(S)\subseteq L^p(S).$
Alternatively, apply Hölder's inequality to $f^p\in L^{\frac{q}{p}}$ and $\chi_S\in L^{\frac{q}{q-p}},$ giving
$$\lVert\chi_S f^p\rVert_1\leq\lVert\chi_S\rVert_{\frac{q}{q-p}}\lVert f^p\rVert_{\frac{q}{p}},$$
and take the $p$th root.

For option 2, to answer your title question and show that $L^p(S)\subseteq L^q(S)$, let's assume we have a lower bound, so $\mu(E)\geq m$ for all $E\subseteq S.$
Given a simple function
$$f=\sum a_i\chi_{E_i}$$
where $E_i$ are disjoint measurable sets and $\chi_{E_i}$ are the indicator functions, we have
$$\lVert f\rVert_p^p=\sum \lvert a_i\rvert^p\mu(E_i)$$
and so
$$\frac{\sum \lvert a_i\rvert^p\mu(E_i)}{\lVert f\rVert_p^p}=1$$
but if a sum of nonnegative terms is equal to one, then each term is at most one, so
$$\frac{\lvert a_i\rvert^p\mu(E_i)}{\lVert f\rVert_p^p}\leq 1$$ as well as its $p$th root
$$
\frac{\lvert a_i\rvert\mu(E_i)^{1/p}}{\lVert f\rVert_p}\leq 1.
$$
A fundamental fact of exponentiation, which is at the root of the identity we seek, with exponents $p<q$ is that if the base $x>1$ then it is increasing, $x^p<x^q$, while if the base $x<1$ it is decreasing, $x^p>x^q.$
Thus we have
$$
\frac{\lvert a_i\rvert^q\mu(E_i)^{q/p}}{\lVert f\rVert_p^q}\leq\frac{\lvert a_i\rvert^p\mu(E_i)}{\lVert f\rVert_p^p}\leq 1,
$$
and therefore also the sum
$$
\frac{\sum\lvert a_i\rvert^q\mu(E_i)^{q/p}}{\lVert f\rVert_p^q}\leq\frac{\sum\lvert a_i\rvert^p\mu(E_i)}{\lVert f\rVert_p^p}=1.
$$
In order to transform the left-hand side of this inequality into the $\lVert\cdot\rVert_q$ norm, we use the boundedness $\mu(E_i)\geq m$ to write
$$\mu(E_i)^{q/p}=\mu(E_i)\mu(E_i)^{\frac{q-p}{p}}\geq\mu(E_i)m^{\frac{q-p}{p}},$$
so that our inequality becomes
$$
\frac{m^{\frac{q-p}{p}}\sum\lvert a_i\rvert^q\mu(E_i)}{\lVert f\rVert_p^q}\leq\frac{\sum\lvert a_i\rvert^q\mu(E_i)^{q/p}}{\lVert f\rVert_p^q}\leq\frac{\sum\lvert a_i\rvert^p\mu(E_i)}{\lVert f\rVert_p^p}=1.
$$
Finally, clearing denominators and taking the $q$th root gives us
$$\lVert f\rVert_q\leq \frac{1}{m^{\frac{1}{p}-\frac{1}{q}}}\lVert f\rVert_p,$$
for simple functions $f$. And since the simple functions are dense, it gives us also the inclusion we desire $L^p(S)\subseteq L^q(S).$

Why is $L^p(S) \subseteq L^q(S)$?


Tests of significance for vector-valued distributions

Question: I have a distribution that assigns 3 numbers to each data point instead of one scalar number. These numbers can be e.g. the weight of a person measured at 3 specific ages.
 (The distribution can of course be though of as 3 different distributions.)
 How can I use tests such as the t-test or one way ANOVA with such a distribution? Of course I can perform the test for each of the components and then multiply the F-scores and (separately) the p-values but I wanted to know what is the customary way to do such a test.
Comment: Do a Google search for "MANOVA". That's the general method. However, if your data consists of multiple measurements made on the same person, then "repeated measures" ANOVA may be more specifically tuned to your problem.
Comment: OK great. Is there also a mutivariate generalization of the paired t-test?
Comment: The paired t-test is just a two-way ANOVA without interaction. So MANOVA provides a direct generalization.
Comment: Oops I meant pairwise t-test.
Answer: Principle
Let's imagine, that your 3 numbers it is just coordinates in 3D space. Than You have a question whether your groups have sense or not (like in usual ANOVA). Idea is well described here and here. My implementation of numeric ANOVA below:

Body of the numeric ANOVA function
MATLAB code:
function F = fAnova( Dataset )
%% INPUT: First 3 columns - coordinates, 4th column - group index
%% OUTPUT F-statistic

Find unique groups IDs and their GroupIDXs (from 1 to number of groups)
[GroupLevels,~,GroupIDXs]=unique(Dataset(:,4));
% Get number of different Groups
NumberOfGroups=numel(GroupLevels);
% Get number of observations, equal to number of rows
NumberOfObservations=size(Dataset,1);
% Count number of observations in each group. It is the same as nItems, but
% lets imagine we work not with simulated data
NumberOfObservationsInEachGroup=accumarray(GroupIDXs,Dataset(:,4),[],@(x) numel(x));
% Calculate pair-wise distances
PairWiseDistances=pdist(Dataset(:,1:3));
% make distance matrix
DistMatrix=squareform(pdist(Dataset(:,1:3)));
% leave only low triangle
DistMatrix=tril(DistMatrix);
% Get grouping matrix. 0 when observations from different groups, ones when
% from same group.
GroupMatrix=repmat(Dataset(:,4)',NumberOfObservations,1)==repmat(Dataset(:,4),1,NumberOfObservations);
% Calculate matrix with number of observations per group. Equal to
% GroupMatrix, but instead of 1 for each group we have number of
% observations.
NumberOfObservationsMatrixRedundant=[];
for iGroup=1:NumberOfGroups
   NumberOfObservationsMatrixRedundant=[NumberOfObservationsMatrixRedundant,repmat(NumberOfObservationsInEachGroup(iGroup),NumberOfObservations,NumberOfObservationsInEachGroup(iGroup))];
end %iGrooup
% Make zeros for cells from different groups
NumberOfObservationsMatrix=NumberOfObservationsMatrixRedundant.*GroupMatrix;
%Redundant
% Get SS_T
SSt=sum(sum(DistMatrix.^2))/NumberOfObservations;
% Get SS_W

SSw=nansum(nansum(((DistMatrix.*GroupMatrix).^2)./NumberOfObservationsMatrix));

% Get SS_A
SSa=SSt-SSw;

% Get F
F=abs((SSa/(NumberOfGroups-1))/(SSw/(NumberOfObservations-NumberOfGroups)));

end % Function

Permutations and example
Let's test our function
%Initialize array of 4 groups of 3D points

nItems=[5 7 9 11]; % Number of dots in each group
Dataset=[];        % First 3 columns - coordinates, 4th column - group index
for iGroup=1:4
    % normrnd(mu,sigma,n,m) generates matrix with n rows and m columns.
    % Values are normally distributed with parameters mu and sigma
    coords1=normrnd(iGroup,1,nItems(iGroup),1);
    coords2=abs(log10(normrnd(iGroup,1,nItems(iGroup),1)));
    % ramrnd(a,b,n,m)  generates matrix with n rows and m columns. Values
    % have gamma distribution with parameters a and b
    coords3=gamrnd(iGroup,1,nItems(iGroup),1);
    GroupIDX=repmat(iGroup,nItems(iGroup),1);
    Dataset=[Dataset;[coords1, coords2, coords3, GroupIDX]];
end %iGroup

Normalize Your data if it is necessary. Normalization depends from your data. I could not give you any suggestions. Let's normalize to standart deviation
for iColumn=1:3
    Dataset(:,iColumn)=Dataset(:,iColumn)./std(Dataset(:,iColumn));
end %iColumns

Thus, we are ready to get observed F
Fobserved=fAnova( Dataset );

Let's create null-distribution under assumption that groups are distributed randomly. To do it you may sample 4th column with (more conservative) or without (less conservative) replacement.
Fsample=[];
SampleDataset=Dataset;
for iSample=1:10^5
    SampleDataset(:,4)=datasample(Dataset(:,4),length(Dataset(:,4)),'Replace',true);
    Fsample(end+1)=fAnova( SampleDataset );
end % iSample

Computed p-value will be number of samples where F-statistic was equal or higher, than observed divide to number of samples +1. We should add 1, as our observation is also "Inside" population.
pValueANOVA=sum(Fsample>=Fobserved)/(numel(Fsample)+1);

Now comes some graphic output
fPlotHist(Fobserved,Fsample,100) %fPlotHist(Observed value,Null distribution,number of bins for histogramm)
title(['ANOVA p-value:' num2str(pValueANOVA,2)])
xlabel('F statistic')
ylabel('Counts')
legend({'null-distribution','', 'Fsample>=Fobserved','Observed F statistic'},'FontSize',14)
set(gca,'FontSize',14)

Links to code
ANOVA function
Example
fPlotHist function
Answer: You can't
First things first: there are generalizations available for your case, but it's not that straight forward. Let me explain:
What you have is, as it seems, a multivariate distribution. Every data-point consists of several (not completely independent I assume) values. Pay attention by saying:

(The distribution can of course be though of as 3 different distributions.)

NO!
You do have one multivariate distribution in 3 dimensions. Of course you can make 3 projections which look at first glance like three distributions, but they do not represent the same data-set as your original distribution! See below for an example. The projections (1-dimensional distributions on the side) look like they are the same, but the 2-dimensional view tells otherwise.

And here starts the problem: if you would just use 1-dimensional tests to tell whether the blue and the red one are the same, they would conclude that they are. Which they surely are not!
So why don't just generalize to multi-dimensions? Because some things are not defined in multivariate distributions. For example, there does not exist an order (which does for the 1-dimensional case, you can sort them by their value). That's why comparing multidimensional distributions gets quite tricky.
One of the best answers would be to use machine learning: train a classifier on your data and on your null-hypothesis. Use a good classifier, the better the classifier performs (CV) on the data, the more different they are.
There are also other test outside, more statistically "approved" ones ;) But they are not a direct counter-part to their 1-dimensional smaller brother and it may even is better to use a completely, for multivariate analysis "created" test instead of a generalized 1-dimensional test.
So find out what you really need, it also depends strongly on your data and the problem you are tackling.
Comment: I don't say your answer is wrong. But I wanted to highlight that the comparison of a multivariate distribution versus the comparison of a one dimensional distribution cannot, in general, be done straight forward but adds some additional implications. He has to be aware of that.
Comment: Why do you think that my approach is incorrect. I don't understand it from Your answer.


point of intersection of a line l and the plane p, i get 0 somehow

Question: $L: x=\frac {y-1}{2}=\frac {z+1}{3}$,
$P= x − 2y + z = 1$.
Find the point of intersection of the line L and the
plane P.
Comment: i convert it to parametric equations but they end up gettin no answer for t, unless im doing it wrong
Comment: Have you tried directly substituting?
Comment: turns out the question changed and the acutally answer is that there exist no point of intersection between the line l and the plane p. thanks alot for looking into this for me anyway
Answer: True, I tried directly substitution but I get a contradiction:
\begin{eqnarray}
-2x + y  &=& 1 \to y = 2x+1\\
 3x - z  &=& 1 \to z = 3x-1\\
 x-2y +z &=& 1 \\
 &\to& x-4x-2+3x-1 =1\\
 &\to& -2 = 2 ><
\end{eqnarray}
Comment: yh theres no answer but thanks alot for the help, ( i assumed there was an acutal answer until the changed the wording into if there exist a plane)
Answer: Just a comment: Are you dealing with one line or two lines, I do not understand the stament :
$$L:x = \frac{y-1}{2}=\frac{z+1}{3}$$
Don't you mean :
\begin{eqnarray}
L_1 : x = \frac{y-1}{2} \\
L_2 : x = \frac{z+1}{3}
\end{eqnarray}
Comment: That is in fact one line; it is a system of equations whose solution set is a line. The L1 and L2 that you have pointed out are planes, not lines.


Como armazenar o erro que o CI_Exception fornece

Question: Olá, gostaria de capturar os erros PHP no codeigniter e armazenar no banco, ou ao menos exibir de uma forma mais suave ao usuário, no arquivo error_php.php são exibidos todos detalhes que preciso, até a linha do código onde o erro ocorreu, mas eu gostaria de conseguir essas informações no controller para poder armazenar.

A PHP Error was encountered

Severity: <?php echo $severity; ?>

Message:  <?php echo $message; ?>

Filename: <?php echo $filepath; ?>

Line Number: <?php echo $line; ?>

Tentei com Try catch mas não funcionou, tentei jogar para o flashdata e depois usar, mas não é correto e mesmo assim não funcionou também.
Comment: Como vc tentou capturar a exception? em ambiente de produção essa msg gigante some (precisa configurar isso).
Comment: Oi, então tentei sim, mas na verdade não quero que suma não, quero conseguir armazenar o erro no banco de dados. ou pelo menos trabalhar ele de uma forma mais amigável. parece que quando é exception até é possível, ai ele redireciona para a view erro_exception, mas nesse caso ele manda para erro_php, acho que não tem uma exception pra esses erros (eu acho)
Answer: É possível fazer o que você deseja, mas isto inclui alterar o core do CodeIgniter. É que o CodeIgniter define um gerenciamento personalizado de erros do PHP quando chama a função abaixo no arquivo /system/core/CodeIgniter.php:
set_error_handler('_error_handler');

E o tratamento das exceções passa para a função _error_handler( ) no arquivo /system/core/Commom.php. Perceba que é nesta função o escopo das variáveis que você deseja utilizar:
function _error_handler($severity, $message, $filepath, $line) {
    $is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $severity) === $severity);

    if ($is_error)
        set_status_header(500);

    if (($severity & error_reporting()) !== $severity)
        return;

    $_error =& load_class('Exceptions', 'core');
    $_error->log_exception($severity, $message, $filepath, $line);

    if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
        // AQUI ESTÃO AS VARIÁVEIS PRONTAS QUE VOCÊ DESEJA
        // O CODEIGNITER ESTÁ PRONTO PARA CHAMAR A VIEW

        // INSIRA DADOS NO BANCO AQUI, DE ACORDO COM USUÁRIO LOGADO, EXCEÇÃO, ETC...
        // $severity, $message, $filepath, $line !!!

        $_error->show_php_error($severity, $message, $filepath, $line);

    if ($is_error)
        exit(1); // EXIT_ERROR
}