text:
Q: Bootstrap center align not working I'm trying to center-align a form I created with Bootstrap, but margin:0 auto or offset isn't working. I'm still new to front-end development and Bootstrap, so it might be a simple mistake. Here is the Code below. Appreciate for some help

html,
body,
header,
#intro {
  height: 100%;
}

#intro {
  background: url("../img/back.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          <form>

              <input type="email" class="form-control" placeholder="Enter Your Username">

              <input type="password" class="form-control" placeholder="Enter Your Password">

                         <input type="checkbox">Remember Me

              <button type="submit" class="btn btn-primary form-control"> Login </button>

          </form>

A: Since you want to center the form, I have created a center_div class.
  margin: 0 auto;
  width: 80%

Hope it will achieve what you needed. Feel free to ask any issues in the comment section.

html,
body,
header,
#intro {
  height: 100%;
}

#intro {
  background: url("../img/back.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.center_div {
  margin: 0 auto;
  width: 80%
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          <form>

              <input type="email" class="form-control" placeholder="Enter Your Username">

              <input type="password" class="form-control" placeholder="Enter Your Password">

                     <input type="checkbox">Remember Me

              <button type="submit" class="btn btn-primary form-control"> Login </button>

          </form>

A:

html,
body,
header,
#intro {
  height: 100%;
}

#intro {
  background: url("../img/back.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          <form>

              <input type="email" class="form-control" placeholder="Enter Your Username">

              <input type="password" class="form-control" placeholder="Enter Your Password">

                <input type="checkbox">Remember Me

              <button type="submit" class="btn btn-primary form-control"> Login </button>

          </form>


text:
Q: Show each column for UNION statement in SQL Server 2005 I have these simple SQL statements:
SELECT     COUNT(ID) AS Expr1
FROM         Table1
UNION
SELECT     COUNT(ID) AS Expr2
FROM         Table1 AS Table1_1
WHERE     (UPDATED > CREATED)
UNION
SELECT     COUNT(DISTINCT DATEPART(year, UPDATED)) AS Expr3
FROM         Table1 AS Table1_2

I want to show results as:
Expr1     Expr2    Expr3
-----     -----    -----
5           3         2

How to do that ? I understand that UNION is more reliable and faster than using OR in WHERE clause.

A: You cannot do this with UNION - that will give you a union of rows - not columns.
For your requirement, try something like this:
SELECT
    Expr1 = (SELECT COUNT(ID) FROM Table1),
    Expr2 = (SELECT COUNT(ID) FROM Table1 WHERE UPDATED > CREATED),
    Expr3 = (SELECT COUNT(DISTINCT DATEPART(year, UPDATED)) FROM Table1)

That will give you one row with three columns, containing the values you're looking for.

A: Isn't something like
SELECT
COUNT(ID) AS Expr1,
    (SELECT COUNT(ID) FROM Table1 WHERE UPDATED > CREATED) as Expr2,
    COUNT(DISTINCT DATEPART(year, UPDATED) as Expr3
FROM Table1

what you need?

redpajama_set_name: RedPajamaStackExchange


text:
Q: mongodb $unwind empty array With this data:
{
    "_id" : ObjectId("576948b4999274493425c08a"),
    "virustotal" : {
        "scan_id" : "4a6c3dfc6677a87aee84f4b629303c40bb9e1dda283a67236e49979f96864078-1465973544",
        "sha1" : "fd177b8c50b457dbec7cba56aeb10e9e38ebf72f",
        "resource" : "4a6c3dfc6677a87aee84f4b629303c40bb9e1dda283a67236e49979f96864078",
        "response_code" : 1,
        "scan_date" : "2016-06-15 06:52:24",
        "results" : [
            {
                "sig" : "Gen:Variant.Mikey.29601",
                "vendor" : "MicroWorld-eScan"
            },
            {
                "sig" : null,
                "vendor" : "nProtect"
            },
            {
                "sig" : null,
                "vendor" : "CAT-QuickHeal"
            },
            {
                "sig" : "HEUR/QVM07.1.0000.Malware.Gen",
                "vendor" : "Qihoo-360"
            }
        ]
    }
},
{
    "_id" : ObjectId("5768f214999274362f714e8b"),
    "virustotal" : {
        "scan_id" : "3d283314da4f99f1a0b59af7dc1024df42c3139fd6d4d4fb4015524002b38391-1466529838",
        "sha1" : "fb865b8f0227e9097321182324c959106fcd8c27",
        "resource" : "3d283314da4f99f1a0b59af7dc1024df42c3139fd6d4d4fb4015524002b38391",
        "response_code" : 1,
        "scan_date" : "2016-06-21 17:23:58",
        "results" : [
            {
                "sig" : null,
                "vendor" : "Bkav"
            },
            {
                "sig" : null,
                "vendor" : "ahnlab"
            },
            {
                "sig" : null,
                "vendor" : "MicroWorld-eScan"
            },
            {
                "sig" : "Mal/DrodZp-A",
                "vendor" : "Qihoo-360"
            }
        ]
    }
}

I'm trying to group by and count the vendor when sig is not null in order to obtain something like:
{
    "_id" : "Qihoo-360",
    "count" : 2
},
{
    "_id" : "MicroWorld-eScan",
    "count" : 1
},
{
    "_id" : "Bkav",
    "count" : 0
},
{
    "_id" : "CAT-QuickHeal",
    "count" : 0
}

At the moment with this code:
db.analysis.aggregate([
    { $unwind: "$virustotal.results"  },
    {
        $group : {
             _id : "$virustotal.results.vendor",
             count : { $sum : 1 }
        }
    },
    { $sort : { count : -1 } }
])

I'm getting everything:
{
    "_id" : "Qihoo-360",
    "count" : 2
},
{
    "_id" : "MicroWorld-eScan",
    "count" : 2
},
{
    "_id" : "Bkav",
    "count" : 1
},
{
    "_id" : "CAT-QuickHeal",
    "count" : 1
}

How can I count 0 if the sig is null?

A: You need a conditional expression in your $sum operator that will check if the "$virustotal.results.sig" key is null by using the comparison operator $gt (as specified in the documentation's BSON comparsion order)
You can restructure your pipeline by adding this expression as follows:
db.analysis.aggregate([
    { "$unwind": "$virustotal.results" },
    {
        "$group" : {
            "_id": "$virustotal.results.vendor",
            "count" : {
                "$sum": {
                    "$cond": [
                        { "$gt": [ "$virustotal.results.sig", null ] },
                        1, 0
                    ]
                }
            }
        }
    },
    { "$sort" : { "count" : -1 } }
])

Sample Output
/* 1 */
{
    "_id" : "Qihoo-360",
    "count" : 2
}

/* 2 */
{
    "_id" : "MicroWorld-eScan",
    "count" : 1
}

/* 3 */
{
    "_id" : "Bkav",
    "count" : 0
}

/* 4 */
{
    "_id" : "CAT-QuickHeal",
    "count" : 0
}

/* 5 */
{
    "_id" : "nProtect",
    "count" : 0
}

/* 6 */
{
    "_id" : "ahnlab",
    "count" : 0
}

A: I changed the null with None and the numbers increased but seems not correct yet.
Basically doing the query in mongoshell I get like
{
    "_id" : "Kaspersky",
    "count" : 176.0
    }
from python:
Kaspersky   64
one of these 2 is wrong :)
So I'm trying to investigate what part of the query in python is not correctly written compared to the mongo shell one.
I did a simple query:
In mongoshell:
        rtmp = results_db.analysis.count( { "virustotal.results" : { "$elemMatch" : { "vendor": "Kaspersky", "sig": {"$ne": "null"} } }})
results: 176
db.analysis.count( { "virustotal.results" : { $elemMatch : { "vendor": "Kaspersky", "sig": {$gt: null} } }})
results: 0
Then I tried in python:
    rtmp = results_db.analysis.count( { "virustotal.results" : { "$elemMatch" : { "vendor": "Kaspersky", "sig": {"$ne": "null"} } }})
results: 568
rtmp = results_db.analysis.count( { "virustotal.results" : { "$elemMatch" : { "vendor": "Kaspersky", "sig": {"$ne": "None"} } }})

results: 568
rtmp = results_db.analysis.count( { "virustotal.results" : { "$elemMatch" : { "vendor": "Kaspersky", "sig": {"$gt": "None"} } }})

results: 64
rtmp = results_db.analysis.count( { "virustotal.results" : { "$elemMatch" : { "vendor": "Kaspersky", "sig": {"$gt": "null"} } }})

results: 6
hard to says what is the correct value! I suppose 176 but not able to reproduce in python...


text:
Q: Hierarchy of priority (if statements in for loops) I am currently taking a Python Databases course offered by Coursera.  The link to the course may be found here:
https://www.coursera.org/learn/python-databases
I am not asking for anyone to do my homework, just for clarification on how Python 2 reads for loops and prioritizes if statements.  You can download the appropriate code and XML file I'm parsing here:
http://www.pythonlearn.com/code/tracks.zip
Everything that the program is meant to do is outside the scope of this question.  Inside of the tracks.py program I come across a helper function used for extracting a value of a key inside a dictionary declared in the Library.xml file.  It looks like this:
def lookup(d, key):
    found = False
    for child in d:
        if found : return child.text
        if child.tag == 'key' and child.text == key : found = True
    return None

At first glance, it didn't make sense to me how the function was checking the found boolean and returning the value for the given key prior to checking if it was there in the first place.  When I try switching the two statements though, the program doesn't properly read in the data.  Why is this?
If anyone wants me to post how I test and discover why this doesn't work please just let me know and I will add some outputs.

A: Python evaluates statements from top to bottom, as most languages do. My guess would just be that the function is supposed to return the next element after the one with the given key.
The <dict> elements in your Library.xml look like this:
<dict>
    <key>Major Version</key><integer>1</integer>
    <key>Minor Version</key><integer>1</integer>
    <key>Date</key><date>2015-11-24T11:12:10Z</date>
    ...

Those are not really dictionaries in the Python-sense, but just an element <dict> containing a list of alternating <key> and <integer/string/date/whatever> elements, the latter being the values to the preceding keys. So if you are looking for the value to a given key, you iterate the list d until you find the key and then return the text of the next child.
Assuming that those <dict> elements are always well formed, you could also use this:
def lookup(d, key):
    it = iter(d)
    for child in it:
        if child.tag == 'key' and child.text == key :
            return next(it).text
    return None


text:
Q: How to Merging two groups in one category in microstrategy Currently I have report like:
Dept      Sub-Dept      No.Of-Lectures
1           101            2
1           102            3
1           104            1
2           201            3
2           203            4

I assume in future Dept 2 is going to merge into Dept 1 so that Sub Dept 201 will report into Sub 102.
How can I implement this kind of requirement in MicroStrategy?

A: There are two way to do it, on the data side or on the MicroStrategy side.
On the data side you have just to modify your fact data to update the Sub-Dept 201 to Sub-Dept 102, modifying the data you can decide to update only after a certain date (not sure if you have a date column in your table) to continue to see the old lectures associated to Dept 2 and the new ones to Dept 1.
On the MicroStrategy side you could create a Custom Group with an element for each Dept, except for Dept 2, Dept 1 and Dept 2 will be part of the same group. Same thing for Sub-Dept 201.
Another possible solution in MicroStrategy would be to create logical tables to create an hierarchy like:
Dept -> Old Dept -> Sub-Dept -> Old Sub-Dept

This will give you a dimension like:
Dept  Old Dept  Sub-Dept  Old Sub-Dept
1     1         102       102
1     2         101       201

Then you can hide the attributes Old Dept and Old Sub-Dept and create a custom drill mapping to jump from Dept to Sub-Dept ignoring the hidden child.
Not sure how good are you with MicroStrategy and dimensional modelling, maybe my last option could be a little confusing for you.
In my opinion the first option, update the data, is the best, especially if you don't plan to go back to the old department structure.
The second is a good temporary solution, the third one can be a bit of overkill if you can go with the other two.


text:
Q: Как сделать автообновляемую таблицу с БД на JS? Вопрос может быть не понятен....
Так вот:
Нужно сделать вывод с автообновлением из БД в админ - панель. В таблицу. Как, не могу додуматься. Обработчик есть в файле ajax. В таблице 3 стоблца. но один может быть пустым. Подскажите пожалуйста...

A: Попытка продемонстрировать как это реализуется в общем случае:

const stubItems = { // Тут будем хранить данные(как будто это база)
  1: {id: 1, title: 'First'},
  2: {id: 2, title: 'Second'},
};

class API { // Класс доступа к нашей "базе", все методы асинхронные, чтобы переход на реальный API был наиболее легким
  get(id) {
    return new Promise((ok, fail) => {
      return stubItems[id] ? ok(stubItems[id]) : fail();
    });
  }
  list() {
    return new Promise(ok => ok(Object.keys(stubItems).map(id => stubItems[id])));
  }
}

class Table { // Класс таблицы с данными
  constructor(api, id) { // Передаём объект API и идентификатор таблицы
    this.api = api;
    this.tbody = document.querySelector(`#${id} tbody`);
  }
  clear() { // Очистка строк таблицы
    [...this.tbody.querySelectorAll('tr')].forEach(tr => tr.remove());
  }
  addRow(id, title) { // Конструирование строки и добавление её в таблицу
    const tr = document.createElement('tr');
    const tdId = document.createElement('td');
    const tdTitle = document.createElement('td');
    tdId.textContent = id;
    tdTitle.textContent = title;
    tr.appendChild(tdId);
    tr.appendChild(tdTitle);
    this.tbody.appendChild(tr);
  }
  update() { // Обновление содержимого таблицы из API
    this.clear(); // Очищаем таблицу до запроса. Вероятно, более коректным будет очищать её после запроса, +проверять, может и не изменилось ничего.
    this.api.list() // Запрашиваем данные из базы
      .then(res => res.forEach(row => this.addRow(row.id, row.title)));
  }
}

const api = new API();
const table = new Table(api, 'data-table');
table.update();
setInterval(() => table.update(), 1000);

// Имитируем обновление базы
setTimeout(() => stubItems[4] = {id: 4, title: 'Forth'}, 1500);
setTimeout(() => {delete stubItems[2];}, 5000);

Id	Title


text:
Q: Is firebase token is unique and permanent for every user? I am  developing   a web push notification app using javascript and PHP.
When a user grants permission for notification and receives a token from firebase.
I use ajax to store this token in database for that user.
Is this token permanent?
Or It will change?
Actually, I want to generate a token for a user when he first signs up on the website, so it's necessary me to know how the token is managed by firebase.

A: The token may change when:

*

*The app deletes Instance ID

*The app is restored on a new device

*The user uninstalls/reinstall the app

*The user clears app data.

Assuming you are already listening on onNewToken of FirebaseMessagingService to get the initial token. Be alert to get the callback triggered in the above scenarios when a new token is assigned to your endpoint and don't miss a chance to update your app server with the new id and the concerned user.


text:
Q: Controlling dynamic time step size in NDSolveValue Statement of problem
I'm writing a script to calculate the temperature of a 2D system with time-dependent heat deposition. The heat deposition is a square wave pulse of duration w = 10^-6 seconds, occurring at a rate of rep = 150Hz (every 6.67*10^-3 seconds).  Without using options, NDSolveValue misses these temporal pulses. If I set MaxStepFraction -> w/MaxTime, the calculation takes much too long (and runs out of memory on my system).
Is there a way to tell NDSolveValue to use shorter time steps around the points in time at which the pulses turn on? I've tried using WhenEvent[] but have not had any success.
Background information
The system comprises a thin metal sheet with bottom face at y=0 with water flowing over the top of the metal sheet.  The top 1/8 of the metal sheet is an interface region with enhanced thermal transport properties.  The heat pulse has a Lorentzian (Cauchy) shape centered on x=0.
If the system performs the calculation with adequate time steps, the temperature in the solid should look something like this:

This is calculated using MaxTimeStep->w and th1=0.02
Here's the code (modified from here, running on V 11.1):
Constants
    cs = 134.;(* Tungsten Specific Heat (J/kg K)*)
    cf = 4187.; (* Water Specific Heat (J/kg K)*)
    ps = 0.0193;(* Tungsten Density (kg/cm^3)*)
    pf = 0.001; (* Water density (kg/cm^3)*)
    ks = 1.; (* Tungsten Thermal Conductivity (W/cm K)*)
    kf = 650.*10^-5; (* Water Thermal Conductivity (W/cm K)*)
    f = 0.1; (* Thermal Transfer Coefficient (Metal/Water) (W/cm^2 K)*)

Adjustable Parameters
    (* Geometric Sizes*)
    th1 = 0.02; (* Thickness of solid layer (cm) *)
    th2 = 0.02; (* Thickness of liquid layer considered (cm) *)
    th3 = 0.2; (* Actual total thickness of liquid layer (cm) *)
    thick = th1/8; (* Thickness of interface (cm) *)
    len = .3; (* Width of water channel (cm) *)
    ht = th1 + th2; (* total height of system *)

    (* Temperature Parameters *)
    T0 = 276.; (* Inlet/outlet temperature (K) *)
    Tstarts = 350.; (* Starting solid temperature (K) *)
    Tstartf = 276.; (* Starting liquid temperature (K) *)

    (* Water Flow Parameters *)
    windia = 0.1; (* Water inlet diameter (cm) *)
    r = 0.2; (* scale factor for flow curve *)
    v0 = 50.; (* Water velocity in channel (cm/s) *)

    (* Beam Parameters *)
    w = 2*^-6; (*Pulse Temperal length (s)*)
    rep = 150;(*Pulse Rep Rate (Hz)*)
    MaxT = 1/rep; (* Max exposure time (s) *)

    (*Parameters for heat deposition (MeV) *)
    as = 10^7;
    bs = 0.0368;
    ns = 1.662;

    af = 10^6;
    bf = 0.03923;
    nf = 1.703;

    (* Time shape of pulse *)
    pulse[t_] = Piecewise[{{1, Abs[t] < w}}, 0];
    pulsemod[t_] = pulse[Mod[t - w, 1/rep, -1/rep]];

    (* Instantaneous power deposited in each layer (J/s) *)
    qsb[x_, y_, t_] = as/(bs^ns + Abs[x]^ns)*pulsemod[t];
    qfb[x_, y_, t_] = af/(bf^nf + Abs[x]^nf)*pulsemod[t];

Build Mesh
    Needs["NDSolve`FEM`"]

    (* Coordinates of edges *)
    top = ht;
    bot = 0;
    left = -len/2;
    right = len/2;
    interfacef = th1;
    interfaces = th1 - thick;
    buffery = 1.5 thick; (* Thickness of modified mesh around interface *)
    bufferx = len/10; (* Thickness of modified mesh around beam *)

    (* Mesh scale constants (larger values makes finer mesh) *)
    meshf = 1;
    meshs = 1;
    meshint = 1;
    meshbuf = 2;
    (*Use associations for clearer assignment later*)
    bounds = <|inlet -> 1, hot -> 2, outlet -> 3|>;
    regs = <|solid -> 10, fluid -> 20, interface -> 15|>;

    (*Meshing Definitions*)
    (*Coordinates*)
    crds = {{left, bot}(*1*), {right, bot}(*2*), {right, top}(*3*), {left, top}(*4*), {left, interfacef}(*5*), {right, interfacef}(*6*), {left, interfaces}(*7*), {right, interfaces}(*8*)};
    (*Edges*)
    lelms = {{5, 4}(*left edge*)(*1*), {1, 2}(*bottom edge*)(*2*), {6,
        3}(*3*), {2, 8}, {8, 6}, {3, 4}, {5, 6}, {7, 8}, {1, 7}, {7,
        5}(*4*)};
    boundaryMarker = {bounds[inlet], bounds[hot], bounds[outlet], 4, 4, 4,
       4, 4, 4, 4};(*4 will be a default boundary*)
    bcEle = {LineElement[lelms, boundaryMarker]};
    bmesh = ToBoundaryMesh["Coordinates" -> crds, "BoundaryElements" -> bcEle];

    (*Identify Center Points of Different Material Regions*)
    fluidCenter = {(left + right)/2, th1 + th2/2};
    fluidReg = {fluidCenter, regs[fluid], (th2/meshf)^2};

    interfaceCenter = {(left + right)/2, interfaces + thick/2};
    interfaceReg = {interfaceCenter, regs[interface], (thick/meshint)^2};

    solidCenter = {(left + right)/2, bot + th1/2};
    solidReg = {solidCenter, regs[solid], (th1/meshs)^2};

    (* Create and refine mesh *)
    meshRegs = {fluidReg, interfaceReg, solidReg};
    mesh = ToElementMesh[bmesh, "RegionMarker" -> meshRegs, MeshRefinementFunction -> Function[{vertices, area}, Block[{x, y}, {x, y} = Mean[vertices];
          If[y > (interfaces + interfacef)/2 - buffery &&
            y < (interfaces + interfacef)/2 + buffery,
           area > (thick/meshbuf)^2, area > (th2/meshf)^2]]]];

    (* Plot Mesh *)
    (* Show[{mesh["Wireframe"["MeshElementStyle" -> {FaceForm[Blue], FaceForm[Yellow],
          FaceForm[Red]}, ImageSize -> Large]]}, PlotRange -> {{-20 thick,
        20 thick}, {(interfaces + interfacef)/2 -
         2 buffery, (interfaces + interfacef)/2 + 2 buffery}}] *)

Region Values
    (*Region Dependent Properties with Piecewise Functions*)
    k = Evaluate[
      Piecewise[{{kf, ElementMarker == regs[fluid]}, {ks,
         ElementMarker == regs[interface] ||
          ElementMarker == regs[solid]}, {0, True}}]];
    p = Evaluate[
       Piecewise[{{pf, ElementMarker == regs[fluid]}, {ps,
          ElementMarker == regs[interface] ||
           ElementMarker == regs[solid]}, {0, True}}]];
    c = Evaluate[
       Piecewise[{{cf, ElementMarker == regs[fluid]}, {cs,
          ElementMarker == regs[interface] ||
           ElementMarker == regs[solid]}, {0, True}}]];
    vp = Evaluate[
       Piecewise[{{v0 (1 - ((y - (th1 + ht)/2)/r)^2),
          ElementMarker == regs[fluid]}, {0, True}}]];

    qsp[x_, y_, t_] =
      Evaluate[Piecewise[{{qsb[x, y, t],
          ElementMarker == regs[interface] ||
           ElementMarker == regs[solid]}, {0, True}}]];
    qfp[x_, y_, t_] =
      Evaluate[Piecewise[{{qfb[x, y, t],
          ElementMarker == regs[fluid]}, {0, True}}]];

    (*fac increases heat transfer coefficient in interface layer*)
    fac = Evaluate[If[ElementMarker == regs[interface], f/thick, 0]];

    (*Neumann Conditions *)
    nvsolid = 0;
    nvfluid =
      NeumannValue[-(tf[x, y, t] - T0)*v0*th2*len*pf*cf,
       ElementMarker == bounds[outlet]];

    (*Dirichlet Conditions for the Left Wall*)
    dcfluid =
      DirichletCondition[tf[x, y, t] == T0,
       ElementMarker == bounds[inlet]];

    (*Balance Equations for Fluid and Solid Temperature*)
    fluideqn =
      p c (D[tf[x, y, t], t] + vp D[tf[x, y, t], x]) -
        k Inactive[Laplacian][tf[x, y, t], {x, y}] -
        fac (ts[x, y, t] - tf[x, y, t]) - qfp[x, y, t] == nvfluid;
    solideqn =
      p c D[ts[x, y, t], t] - k Inactive[Laplacian][ts[x, y, t], {x, y}] -
         fac (tf[x, y, t] - ts[x, y, t]) - qsp[x, y, t] == nvsolid;
    ics = ts[x, y, 0] == Tstarts;
    icf = tf[x, y, 0] == Tstartf;

Solve the System
    (* Setup timer for convenience *)
    MSz = w; (* Max time step *)
    tp = 0;
    t0 = AbsoluteTime[];
    rate := Quiet[tp/(AbsoluteTime[] - t0)];
    ProgressIndicator[Dynamic[tp/MaxT]]
    Print[Dynamic[ToString[tp] <> " / " <> ToString[N[MaxT]]]]
    Print[Dynamic[
      "Time Remaining: " <> ToString[Round[(MaxT - tp)/rate]] <> " s"]]

    (* Execute Solving *)
    ifun = NDSolveValue[{fluideqn, solideqn, dcfluid, ics, icf}, {tf,
        ts}, {t, 0, MaxT}, {x, y} \[Element] mesh
       , StepMonitor :> (tp = t)
       , MaxStepSize -> MSz];

    (* Plot Result *)
    (* Plot[ifun[[1]][0, th1 + thick/2, t], {t, 0, MaxT}
     , PlotRange -> All]
    Plot[ifun[[2]][0, th1 - thick/2, t], {t, 0, MaxT}
     , PlotRange -> All] *)

Additional Notes:
The following is independent of the primary purpose for this post.
Internal Boundary Conditions
It doesn't seem obvious that I need to have two separate temperature functions - one for the solid and one for the liquid.  However, MMA cannot handle internal boundary conditions.  If it could, I would add a Robin boundary condition, namely
    rc = NeumannValue[-(temp[x, y, t] - temp[0, th1, t])*
       f/thick, ElementMarker == bounds[interface]]

and the single differential equation to solve would be
    tempeqn =
     D[temp[x, y, t], t] ==
      1/(p c) (Inactive[Div][
           k Inactive[Grad][temp[x, y, t], {x, y}], {x, y}] +
          qp[x, y, t] + nv + rc) - vp D[temp[x, y, t], x]

pursuant to initial condition
ic = temp[x, y, 0] ==
   Tstartf + (Tstarts -
       Tstartf) (1 -
        Tanh[(y - (interfacef + interfaces)/2)/(.25 thick)])/2;

However, when attempting to do this, MMA produces the error
    NDSolveValue::delpde: Delay partial differential equations are not currently supported by NDSolve.

Since the boundary condition expression is
    k d/dx(u(x,y,t)) = h(u(x,y,t)-u(x,th1,t))

one could imagine taking a linear approximation to the temperature within the interface region.  That is, adding a term to the differential equation that looks like
    (k-h(y-th1))d/dx(u(x,y,t)) = 0

However, I think such an assumption is not justified and will produce incorrect results.
WhenEvent[]
According to the help file, WhenEvent[] allows the user to change the value of a state variable.  A state variable seems to mean the dependent variable.  The following is something that one might expect to work, but does not:
    ifun = NDSolveValue[{fluideqn, solideqn, dcfluid, ics, icf,
      WhenEvent[Abs[t - 1/rep] <= w, MSz -> w],
      WhenEvent[Abs[t - 1/rep] > w, MSz -> 10 w]},
      {tf, ts}, {t, 0, MaxT}, {x, y} \[Element] mesh
      , MaxStepSize :> MSz];

...because 'delayed rule (:>)' cannot be used as a MaxStepSize.  The above attempt produces the error
    NDSolveValue::ndmss: Value of option MaxStepSize -> MSz is not a positive real number or Infinity.

Replacing the 'delayed rule (:>)' with just 'rule (->)', we get the errors:
    NDSolveValue::wenset: Warning: the rule MSz->w will not directly set the state because the left-hand side is not a list of state variables.
    NDSolveValue::wenset: Warning: the rule MSz->10 w will not directly set the state because the left-hand side is not a list of state variables.

This is telling us that the WhenEvent[] event will not be evaluated because MSz is not a state variable.  WhenEvent[] does not work with 'set (=)', so I cannot actually change the value of MSz.  And even if I could, I'd need to be able to use 'delayed rule (:>)' i.e. MaxStepSize :> MSz.  I think the solution to my question is not found in using WhenEvent[], or if it is, then it is not in using WhenEvent[] with MaxStepSize or MaxStepFraction

A: Your question and your system is fairly complex and I would consider breaking it up into more manageable chunks.  It is easier to get help that way.  Your system contains multiple materials, thin layers, liquids and solids, convection-diffusion, transient pulses, etc., so there are a lot of interactions to sort out. I also recommend that you conduct a dimensional analysis as it can help you sort out the dominant regimes that are present in the system.  That aside, this is not a complete answer, rather it shows some building blocks that might be useful.
The following shows how I broke up the tasks into four steps:

*

*Pulsed heating using WhenEvent on a 0D model.

*Structured quad meshing to reduce model size.

*Combine structured quad meshing with WhenEvent on a layered conduction problem.

*Add convection.

Perhaps the following concepts can be used to at least reduce the model size so that concepts can be tested on a shorter cycle.
Pulsed heating using WhenEvent on a 0D model
I do not use WhenEvent enough to be a pro with its usage. Therefore, I always start with a simple model to make sure my WhenEvent construction behaves as intended. Consider the following simple model of a flow tank heated by a pulsed coil as shown by the equation below.
$$\frac{{du}}{{dt}} =  - u(t) + q(t)$$
In the following Mathematica code, I introduce a unit heat load with a period of one time unit with a duty cycle of 0.025.
duty = 1/40;
period = 1;
{sol} = NDSolve[{u'[t] == -u[t] + q[t], q[0] == 0, u[0] == 0,
    WhenEvent[{Mod[t, period],
      Mod[t + period duty, period]}, {q[t] ->
       If[q[t] == 0, 1/duty, 0]}]}, {u, q}, {t, 0, 10},
   DiscreteVariables -> q];
Plot[{Evaluate[{u[t], q[t]} /. sol], 0, 1/duty}, {t, 0, 10},
 PlotTheme -> "Web", PlotStyle -> {Thick, Thick, Dashed, Dashed},
 PlotPoints -> 500]
Row[{
  Column[{
    Plot[{Evaluate[q[t] /. sol], 0, 1/duty}, {t, 0, 10},
     PlotTheme -> "Web",
     PlotStyle -> {Directive[Thick, Green], Dashed, Dashed},
     PlotPoints -> 500, ImageSize -> Medium],
    Plot[{Evaluate[u[t] /. sol]}, {t, 0, 10}, PlotTheme -> "Web",
     PlotStyle -> {Directive[Thick, Red]}, PlotPoints -> 500,
     ImageSize -> Medium]
    }], Column[{
    Plot[{Evaluate[q[t] /. sol], 0, 1/duty}, {t, 0, 2.1},
     PlotTheme -> "Web",
     PlotStyle -> {Directive[Thick, Green], Dashed, Dashed},
     PlotPoints -> 500, ImageSize -> Medium],
    Plot[{Evaluate[u[t] /. sol]}, {t, 0, 2.1}, PlotTheme -> "Web",
     PlotStyle -> {Directive[Thick, Red]}, PlotPoints -> 500,
     ImageSize -> Medium]
    }]}]

The results looks similar to the OP so this looks like a working representation of a pulse sequence with WhenEvent.
Structured quad meshing to reduce model size
A good computational mesh is necessary for accurate simulation results.  For a model such as this that contains thin layers and potentially very thin thermal boundary layers, one generally uses an anisotropic mesh that is fine in the direction of steep gradients and coarser in the direction of shallow gradients.Using this approach, you will have a much smaller mesh and potentially longer time steps due to CFL considerations thus substantially reducing your computational requirements.
Unfortunately, Mathematica does not provide a GUI to construct these types of mapped structured meshes. Fortunately, Mathematica provides lots of geometric computation that should allow us to slap something together to construct layered structured meshes.  In fact, I was inspired by the RegionProduct documentation that shows how one can simply construct a tensor product grid with a graded mesh. This combined with the two Element Mesh Tutorial should give us what we need to construct a valid FEM mesh.
I apologize in advance for the following code. It is hastily constructed, but it appears to function and will allow us to construct structured layered meshes on rectangular domains with a few lines of code.
Mathematica code for structured meshes
Needs["NDSolve`FEM`"]
ex = {1, 0};
ey = {0, 1};
eleft = -ex;
eright = ex;
etop = ey;
ebot = -ey;
ebi = ElementIncidents[#["BoundaryElements"]][[1]] &;
ebm = ElementMarkers[#["BoundaryElements"]][[1]] &;
ei = ElementIncidents[#["MeshElements"]][[1]] &;
em = ElementMarkers[#["MeshElements"]][[1]] &;
epi = Flatten@ElementIncidents[#["PointElements"]] &;
epm = Flatten@ElementMarkers[#["PointElements"]] &;

(* Shortand *)
FP = Flatten@Position[#, True] &;
UF = Union@Flatten[#, Infinity] &;

gidx = Flatten@Position[#, True] &;
gelm = #1[[gidx[#2]]] &;
ginc = Union@Flatten@gelm[#1, #2] &;
getBoundaryNodes = ginc[#["pureBoundaries"], #[dirs[#2]]] &;

lineElms2Nodes[lelms_, mask_] :=
 Union@Flatten@lelms[[Flatten@Position[mask, True]]]
pfn[ei_, em_, marker_] := Pick[ei, # == marker & /@ em]
in1dMask[l1_, l2_] := MemberQ[l1, #] & /@ l2
in2dMasks[l1_, l2_] := in1dMask[l1, #] & /@ Transpose[l2]
inBothMask[l1_, l2_] := Inner[And, #1, #2, List] & @@ in2dMasks[l1, l2]
regBothMask[assoc_, marker_] :=
 inBothMask[assoc["regIncAssoc"][marker], assoc["pureBoundaries"]]
meshinfo[mesh_] := Module[{crd, nCrd, elms, nElms, markers, nMarkers,
   uniqueMarkers, boundaries, boundaryNormals, bndNodes, bndMarkers,
   regInc, regIncAssoc},
  crd = mesh["Coordinates"];
  nCrd = Dimensions[crd][[1]];
  elms = ei[mesh];
  nElms = Dimensions[elms][[1]];
  markers = em[mesh];
  nMarkers = Dimensions[markers][[1]];
  uniqueMarkers = Union@markers;
  boundaries = ebi[mesh];
  boundaryNormals = mesh["BoundaryNormals"][[1]];
  bndNodes = epi[mesh];
  bndMarkers = epm[mesh];
  regInc = pfn[elms, markers, #] & /@ uniqueMarkers;
  regIncAssoc =
   AssociationThread[uniqueMarkers -> (Union[Flatten@#] & /@ regInc)];
  <|
   "crd" -> crd,
   "nCrd" -> nCrd,
   "elms" -> elms,
   "nElms" -> nElms,
   "markers" -> markers,
   "nMarkers" -> nMarkers,
   "uniqueMarkers" -> uniqueMarkers,
   "boundaries" -> boundaries,
   "boundaryNormals" -> boundaryNormals,
   "bndNodes" -> bndNodes,
   "bndMarkers" -> bndMarkers,
   "regIncAssoc" -> regIncAssoc
   |>
  ]
extinfo[mesh_] :=
 Module[{flat, flatinfo , assoc, regBndList, regBoundMasks,
   pureBoundaryNormals, pureNorth, pureEast, pureSouth, pureWest},
  assoc = meshinfo[mesh];
  flat = flatMesh[mesh];
  flatinfo = meshinfo[flat];
  AppendTo[assoc, "pureBoundaries" -> flatinfo["boundaries"]];
  AppendTo[assoc,
   "pureBoundaryMarkers" ->
    First@ElementMarkers@flat["BoundaryElements"]];
  AppendTo[assoc,
   "nPureBoundaries" -> Dimensions[flatinfo["boundaries"]][[1]]];
  AppendTo[assoc, "pureBndNodes" -> flatinfo["bndNodes"]];
  AppendTo[assoc, "pureBndMarkers" -> flatinfo["bndMarkers"]];
  pureBoundaryNormals = flat["BoundaryNormals"][[1]];
  AppendTo[assoc, "pureBoundaryNormals" -> pureBoundaryNormals];
  pureNorth = (0.9999 < ey.#) & /@ pureBoundaryNormals;
  pureEast = (0.9999 < ex.#) & /@ pureBoundaryNormals;
  pureSouth = (0.9999 < -ey.#) & /@ pureBoundaryNormals;
  pureWest = (0.9999 < -ex.#) & /@ pureBoundaryNormals;
  AppendTo[assoc, "pureNorth" -> pureNorth];
  AppendTo[assoc, "pureEast" -> pureEast];
  AppendTo[assoc, "pureSouth" -> pureSouth];
  AppendTo[assoc, "pureWest" -> pureWest];
  regBndList = regBothMask[assoc, #] & /@ assoc["uniqueMarkers"];
  regBoundMasks =
   AssociationThread[assoc["uniqueMarkers"] -> regBndList];
  AppendTo[assoc, "regBoundMasks" -> regBoundMasks]
  ]
meshGrowth[x0_, xf_, n_, ratio_] := Module[{k, fac, delta},
  k = Log[ratio]/(n - 1);
  fac = Exp[k];
  delta = (xf - x0)/Sum[fac^(i - 1), {i, 1, n - 1}];
  N[{x0}~Join~(x0 +
      delta Rest@
        FoldList[(#1 + #2) &, 0,
         PowerRange[fac^0, fac^(n - 3), fac]])~Join~{xf}]
  ]
adjust[l_, assoc_] :=
 Module[{itest, newlist, nodesfound, newmarks, pos, ll},
  newlist = l["pbm"];
  itest = Inner[And, assoc["reg"], assoc["dir"], List];
  pos = Flatten@Position[itest, True];
  newlist[[pos]] = assoc["marker"];
  nodesfound = UF@assoc["lelm"][[pos]];
  ll = assoc["lnodes"];
  newmarks = l["pbnm"];
  newmarks[[Flatten@(Position[ll, #] & /@ nodesfound)]] =
   assoc["marker"];
  <|"pbm" -> newlist, "pbnm" -> newmarks|>]
adjustMarkers[mesh_, adjustments_] :=
 Module[{itest, extmi, assocs, l, bcEle},
  extmi = extinfo[mesh];
  assocs =
   AssociationThread[{"lelm", "lnodes", "reg", "dir", "marker"},
      {extmi["pureBoundaries"], extmi["pureBndNodes"],
       extmi["regBoundMasks"][#["region"]],
       extmi[#["dir"]], #["marker"]}] & /@ adjustments;
  l = <|"pbm" -> extmi["pureBoundaryMarkers"],
    "pbnm" -> extmi["pureBndMarkers"]|>;
  l = Fold[adjust, l, assocs];
  bcEle = {LineElement[extmi["pureBoundaries"], l["pbm"]]};
  (*l=extmi["pureBndMarkers"];
  l=Fold[adjust,l,assocs];*)
  pEle = {PointElement[Transpose@{extmi["pureBndNodes"]}, l["pbnm"]]};
  {bcEle,
   ToElementMesh["Coordinates" -> mesh["Coordinates"],
    "MeshElements" -> mesh["MeshElements"],
    "BoundaryElements" -> bcEle, "PointElements" -> pEle]}]
pointsToMesh[data_] :=
  MeshRegion[Transpose[{data}],
   Line@Table[{i, i + 1}, {i, Length[data] - 1}]];
rp2Mesh[rh_, rv_, marker_] := Module[{sqr, crd, inc, msh, mrkrs},
  sqr = RegionProduct[rh, rv];
  crd = MeshCoordinates[sqr];
  inc = Delete[0] /@ MeshCells[sqr, 2];
  mrkrs = ConstantArray[marker, First@Dimensions@inc];
  msh = ToElementMesh["Coordinates" -> crd,
    "MeshElements" -> {QuadElement[inc, mrkrs]}]
  ]
combineMeshes[mesh1_, mesh2_] :=
 Module[{crd1, crd2, newcrd, numinc1, inc1, inc2, mrk1, mrk2, melms},
  crd1 = mesh1["Coordinates"];
  crd2 = mesh2["Coordinates"];
  numinc1 = First@Dimensions@crd1;
  newcrd = crd1~Join~ crd2;
  inc1 =  ElementIncidents[mesh1["MeshElements"]][[1]];
  inc2 =  ElementIncidents[mesh2["MeshElements"]][[1]];
  mrk1 = ElementMarkers[mesh1["MeshElements"]][[1]];
  mrk2 = ElementMarkers[mesh2["MeshElements"]][[1]];
  melms = {QuadElement[inc1~Join~(numinc1 + inc2), mrk1~Join~mrk2]};
  ToElementMesh["Coordinates" -> newcrd, "MeshElements" -> melms]
  ]
markerSubsets[mesh_] := With[
  {crd = mesh["Coordinates"],
   bids = Flatten[ElementIncidents[mesh["PointElements"]]],
   ei = ei[mesh], em = em[mesh]},
  {crd, bids, ei, em, pfn[ei, em, #] & /@ Union[em]}]
incidentSubs[mesh_] :=
 Module[{coords, ei, em, boundaryIDs, pureboundaryIDs, mei,
   interiorIDs, interfaceNodes},
  {coords, boundaryIDs, ei, em, mei} = markerSubsets[mesh];
  interiorIDs = Complement[Range[Length[coords]], boundaryIDs];
  interfaceNodes =
   Flatten[Intersection @@ (Flatten[#] &) /@ # & /@
     Partition[mei, 2, 1]];
  pureboundaryIDs = Complement[boundaryIDs, interfaceNodes];
  {pureboundaryIDs, interfaceNodes, interiorIDs}
  ]
flatMesh[mesh_] :=
 ToElementMesh["Coordinates" -> mesh["Coordinates"],
  "MeshElements" -> {QuadElement[
     ElementIncidents[mesh["MeshElements"]][[1]]]}]
nodeTypes[mesh_] :=
 Module[{mtemp, pureboundaryIDs, interfaceNodes, intIDs,
   tpureboundaryIDs, tinterfaceNodes, tintIDs, boundaryInts,
   interiorInterfaceNodes, bool},
  mtemp = flatMesh[mesh];
  {pureboundaryIDs, interfaceNodes, intIDs} = incidentSubs[mesh];
  {tpureboundaryIDs, tinterfaceNodes, tintIDs} = incidentSubs[mtemp];
  boundaryInts = Complement[tpureboundaryIDs, pureboundaryIDs];
  interiorInterfaceNodes = Complement[interfaceNodes, boundaryInts];
  bool = ContainsAll[tpureboundaryIDs, #] & /@ ebi[mesh];
  {bool, tpureboundaryIDs, interiorInterfaceNodes, intIDs}]
(*Use associations for clearer assignment later*)
bounds = <|"inlet" -> 1, "hot" -> 2, "outlet" -> 3, "cold" -> 4,
   "default" -> 0|>;
regs = <|"solid" -> 10, "fluid" -> 20, "interface" -> 15,
   "insulation" -> 100|>;
dirs = <|"north" -> "pureNorth", "east" -> "pureEast",
   "south" -> "pureSouth", "west" -> "pureWest"|>;
bcadj = <|"region" -> regs[#1], "dir" -> dirs[#2],
    "marker" -> bounds[#3]|> &;

The following constructs a thin ${\color{Red} {Red}}$ solid region with a uniform mesh and a thicker ${\color{Green} {Green}}$ fluid region with a boundary layer mesh to capture the solid fluid interface.  I also marked certain edges by what I think there boundary conditions are going to be later. If they are not used, they default to Neumann value of zero or that of an insulated wall condition.
(* Model Dimensions *)
lf = 0;
rt = 5;
th1 = 2;
th2 = 8;
bt = -th1;
tp = th2;
(* Horizontal Flow Dir Region *)
rh = pointsToMesh[Subdivide[lf, rt, 10]];
(* Thin Metal Region Uniform Mesh*)
rv = pointsToMesh[Subdivide[bt, 0, 10]];
(* Thick Fluid Region Geometric Growth Mesh *)
rv2 = pointsToMesh@meshGrowth[0, tp, 40, 16];
(* Build Element Meshes From Region Products *)
m1 = rp2Mesh[rh, rv, regs["solid"]];
m2 = rp2Mesh[rh, rv2, regs["fluid"]];
(* Combine the solid and fluid mesh *)
mesh = combineMeshes[m1, m2];
(* Define a series of BC adjustments *)
(* Last assignement takes precedence with PointElement *)
adjustments = {bcadj["solid", "south", "hot"]};
AppendTo[adjustments, bcadj["fluid", "north", "cold"]];
AppendTo[adjustments, bcadj["fluid", "west", "inlet"]];
(* Adjust the mesh with new boundary and point elements *)
{bcEle, mesh} = adjustMarkers[mesh, adjustments];
(* Display the mesh and bc's *)
Column[{Row@{mesh[
     "Wireframe"["MeshElement" -> "BoundaryElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red}, ImageSize -> Medium]],
    mesh["Wireframe"[
      "MeshElementStyle" -> {FaceForm[Red], FaceForm[Green]},
      ImageSize -> Medium]]},
  Row@{mesh[
     "Wireframe"["MeshElement" -> "PointElements",
      "MeshElementIDStyle" -> Black, ImageSize -> Medium]],
    mesh["Wireframe"["MeshElement" -> "PointElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red},
      ImageSize -> Medium]]}}]

The images show that I constructed the mesh as I intended.
Combine structured quad meshing with WhenEvents on a layered conduction problem
Now, we are ready to combine the WhenEvent, structured mesh, and heat equation example from the finite element tutorial into an example where we pulse the solid layer with heat and watch it transfer into the fluid layer. For simplicity, we are considering conduction only and I have set the top of the model to be a cold wall at the initial starting temperature condition.
duty = 1/32;
period = 0.5;
fac = Evaluate[
   Piecewise[{{0.1, ElementMarker == regs["solid"]}, {0, True}}]];
k = Evaluate[
   Piecewise[{{285, ElementMarker == regs["solid"]}, {1, True}}]];
op = \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]\(u[t, x, y]\)\) -
   Inactive[
     Div][(-{{k, 0}, {0, k}}.Inactive[Grad][u[t, x, y], {x, y}]), {x,
     y}] - fac q[t];
Subscript[\[CapitalGamma], D2] =
  DirichletCondition[u[t, x, y] == 0, ElementMarker == bounds["cold"]];
ufunHeat =
  NDSolveValue[{op == 0, u[0, x, y] == 0 , Subscript[\[CapitalGamma],
    D2], q[0] == 0,
    WhenEvent[{Mod[t, period],
      Mod[t + period duty, period]}, {q[t] ->
       If[q[t] == 0, 1/duty, 0]},
     "DetectionMethod" -> "Interpolation"]}, {u, q}, {t, 0,
    5}, {x, y} \[Element] mesh, DiscreteVariables -> q,
   MaxStepFraction -> 0.001];

This code should run in a few seconds.  Due to the discretization differences between the layers, I find it is usually best to plot each layer separately and combined them with Show.
plrng = {{lf, rt}, {bt, tp}, {0, 0.320}};
SetOptions[Plot3D, PlotRange -> plrng, PlotPoints -> Full,
  ColorFunction ->
   Function[{x, y, z}, Directive[ColorData["DarkBands"][3 z]]],
  ColorFunctionScaling -> False, MeshFunctions -> {#3 &}, Mesh -> 20,
  AxesLabel -> Automatic, ImageSize -> Large];
plts = Plot3D[ufunHeat[[1]][#, x, y], {x, y} \[Element] m1,
    MeshStyle -> {Black, Thick}] &;
pltf = Plot3D[ufunHeat[[1]][#, x, y], {x, y} \[Element] m2,
    MeshStyle -> {Dashed, Black, Thick}] &;
showplot =
  Show[{plts[#], pltf[#]},
    ViewPoint -> {3.252862844243345`, 0.28575764805522785`,
      0.8872575066569075`},
    ViewVertical -> {-0.2612026545717462`, -0.022946143077719586`,
      0.9650112163920842`}, ImageSize -> 480,
    Background -> RGBColor[0.84`, 0.92`, 1.`], Boxed -> False] &;
ListAnimate[showplot /@ Evaluate@Subdivide[0, 5, 80]]

The results appear to be reasonable.
Add convection
Now, we are in a position to add the convective term to the fluid layer. I will begin by making the flow length four times longer and I will increase the resolution at the fluid-solid interface using the following code.  The fluid enters via the inlet at the initial conditions.
(* Model Dimensions *)
lf = 0;
rt = 20;
th1 = 2;
th2 = 8;
bt = -th1;
tp = th2;
(* Horizontal Region *)
rh = pointsToMesh[Subdivide[lf, rt, 40]];
(* Thin Metal Region Uniform Mesh*)
rv = pointsToMesh[Subdivide[bt, 0, 10]];
(* Thick Fluid Region Geometric Growth Mesh *)
rv2 = pointsToMesh@meshGrowth[0, tp, 80, 32];
(* Build Element Meshes From Region Products *)
m1 = rp2Mesh[rh, rv, regs["solid"]];
m2 = rp2Mesh[rh, rv2, regs["fluid"]];
(* Combine the solid and fluid mesh *)
mesh = combineMeshes[m1, m2];
(* Define a series of BC adjustments *)
(* Last assignement takes precedence with PointElement *)
adjustments = {bcadj["solid", "south", "hot"]};
AppendTo[adjustments, bcadj["fluid", "north", "cold"]];
AppendTo[adjustments, bcadj["fluid", "west", "inlet"]];
(* Adjust the mesh with new boundary and point elements *)
{bcEle, mesh} = adjustMarkers[mesh, adjustments];
(* Display the mesh and bc's *)
Column[{Row@{mesh[
     "Wireframe"["MeshElement" -> "BoundaryElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red}, ImageSize -> Medium]],
    mesh["Wireframe"[
      "MeshElementStyle" -> {FaceForm[Red], FaceForm[Green]},
      ImageSize -> Medium]]},
  Row@{mesh[
     "Wireframe"["MeshElement" -> "PointElements",
      "MeshElementIDStyle" -> Black, ImageSize -> Medium]],
    mesh["Wireframe"["MeshElement" -> "PointElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red},
      ImageSize -> Medium]]}}]
(* Simulation *)
duty = 1/32;
period = 0.5;
v = Evaluate[
   Piecewise[{{{0.1 (y/th2)^2 {1, 0}},
      ElementMarker == regs["fluid"]}, {{{0, 0}}, True}}]];
fac = Evaluate[
   Piecewise[{{0.2, ElementMarker == regs["solid"]}, {0, True}}]];
k = Evaluate[
   Piecewise[{{285, ElementMarker == regs["solid"]}, {1, True}}]];
op = \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]\(u[t, x, y]\)\) +
   v.Inactive[Grad][u[t, x, y], {x, y}] -
   Inactive[
     Div][(-{{k, 0}, {0, k}}.Inactive[Grad][u[t, x, y], {x, y}]), {x,
     y}] - fac q[t];
Subscript[\[CapitalGamma], D1] =
  DirichletCondition[u[t, x, y] == 0,
   ElementMarker == bounds["inlet"]];
Subscript[\[CapitalGamma], D2] =
  DirichletCondition[u[t, x, y] == 0, ElementMarker == bounds["cold"]];
ufunHeat =
  NDSolveValue[{op == 0, u[0, x, y] == 0 , Subscript[\[CapitalGamma],
    D1], Subscript[\[CapitalGamma], D2], q[0] == 0,
    WhenEvent[{Mod[t, period],
      Mod[t + period duty, period]}, {q[t] ->
       If[q[t] == 0, 1/duty, 0]},
     "DetectionMethod" -> "Interpolation"]}, {u, q}, {t, 0,
    5}, {x, y} \[Element] mesh, DiscreteVariables -> q,
   MaxStepFraction -> 0.001];
plrng = {{lf, rt}, {bt, tp}, {0, 0.22}};
(* Movie Generation *)
SetOptions[Plot3D, PlotRange -> plrng, PlotPoints -> Full,
  ColorFunction ->
   Function[{x, y, z}, Directive[ColorData["DarkBands"][5 z]]],
  ColorFunctionScaling -> False, MeshFunctions -> {#3 &}, Mesh -> 20,
  AxesLabel -> Automatic, ImageSize -> Large];
plts = Plot3D[ufunHeat[[1]][#, x, y], {x, y} \[Element] m1,
    MeshStyle -> {Black, Thick}] &;
pltf = Plot3D[ufunHeat[[1]][#, x, y], {x, y} \[Element] m2,
    MeshStyle -> {Dashed, Black, Thick}] &;
showplot =
  Show[{plts[#], pltf[#]},
    ViewPoint -> {-2.9775556124522455`, 0.6436172037401853`,
      1.473064652282362`},
    ViewVertical -> {0.4255034386507697`, -0.09197522028503674`,
      0.9002707273647687`}, ImageSize -> 400,
    Background -> RGBColor[0.84`, 0.92`, 1.`], Boxed -> False] &;
ListAnimate[showplot /@ Evaluate@Subdivide[0, 5, 80]]

The above code should produce the following animation.I have made no attempts at validation, but the model seems to be behaving reasonably well.

Here is a plot of the temperature taken at the vertical middle and the horizontal beginning, middle, and end of the strip.
Plot[{ufunHeat[[1]][t, 0.05 rt, -th1/2],
  ufunHeat[[1]][t, 0.5 rt, -th1/2],
  ufunHeat[[1]][t, 0.95 rt, -th1/2]}, {t, 0, 5}, PlotPoints -> {200},
 WorkingPrecision -> 20, MaxRecursion -> 10, PlotRange -> {0, 0.280},
 ImageSize -> 600, PlotTheme -> "Web",
 Filling -> {2 -> {{3}, {LightGreen}}, 1 -> {{2}, {LightYellow}}},
 PlotLegends ->
  Placed[SwatchLegend[{"Beg", "Mid", "End"},
    LegendFunction -> "Frame", LegendLayout -> "Column",
    LegendMarkers -> list[[-1]]], {{0.1, 0.75}, {0.15, 0.75}}]]

It looks similar to the graph provided in the OP.
I do not precisely know the inner workings of WhenEvent, but other solvers will tighten their time steps around explicit events. I would presume that the same happens in Mathematica.  Because it is a physical system with finite diffusivity, the square pulses will most likely be convoluted With a broadening function and will manifest itself as a Gaussian or Lorentzian type shape.
Inlet Boundary Condition Sensitivity
At the liquid-solid inlet interface, the model appears to be pinned.  This is due to the Dirichlet condition at the shared node.  Local heat transfer coefficients are infinite at the entrance for constant temperature or constant flux prescribed boundary conditions.  This pinning would be required if one wanted to compare to analytical solutions.  However, in real systems, although local heat transfer coefficients can be very high at the entrance, they are not infinite.  Depending on your need, you may want to make adjustments to the inlet boundary condition.
As stated previously, we can override that condition by adjusting the west-solid boundary after the inlet assignment.  Alternatively, we can extend the model by adding a solid insulation layer before the heated solid.  I also adjusted the equations and the domain a bit, but we still should be able to observe if the model is still pinned at the interface.
Adjusting the Inlet Interface Node to be a Default Insulating Neumann Value
We can adjust the model and simulate with the following code:
(* Model Dimensions *)
th1 = 1;
th2 = 2 th1;
lf = 0;
rt = 5 th1;
bt = -th1;
tp = th2;
(* Horizontal Region *)
rh = pointsToMesh@meshGrowth[lf, rt, 80, 8];
(* Thin Metal Region Uniform Mesh*)
rv = pointsToMesh[Subdivide[bt, 0, 10]];
(* Thick Fluid Region Geometric Growth Mesh *)
rv2 = pointsToMesh@meshGrowth[0, tp, 80, 32];
(* Build Element Meshes From Region Products *)
m1 = rp2Mesh[rh, rv, regs["solid"]];
m2 = rp2Mesh[rh, rv2, regs["fluid"]];
(* Combine the solid and fluid mesh *)
mesh = combineMeshes[m1, m2];
(* Define a series of BC adjustments *)
(* Last assignement takes precedence with PointElement *)
adjustments = {bcadj["solid", "south", "hot"]};
AppendTo[adjustments, bcadj["fluid", "north", "cold"]];
AppendTo[adjustments, bcadj["fluid", "west", "inlet"]];
AppendTo[adjustments, bcadj["solid", "west", "default"]];
(* Adjust the mesh with new boundary and point elements *)
{bcEle, mesh} = adjustMarkers[mesh, adjustments];
(* Display the mesh and bc's *)
Column[{Row@{mesh[
     "Wireframe"["MeshElement" -> "BoundaryElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red}, ImageSize -> Medium]],
    mesh["Wireframe"[
      "MeshElementStyle" -> {FaceForm[Red], FaceForm[Green]},
      ImageSize -> Medium]]},
  Row@{mesh[
     "Wireframe"["MeshElement" -> "PointElements",
      "MeshElementIDStyle" -> Black, ImageSize -> Medium]],
    mesh["Wireframe"["MeshElement" -> "PointElements",
      "MeshElementMarkerStyle" -> Blue,
      "MeshElementStyle" -> {Black, Green, Red},
      ImageSize -> Medium]]}}]
duty = 1/6000 (*6000*);
period = 1;
w = 1/period;
tmax = 10;
v = Evaluate[
   Piecewise[{{{16.6 (y/th2)^2 {1, 0}},
      ElementMarker == regs["fluid"]}, {{{0, 0}}, True}}]];
fac = Evaluate[
   Piecewise[{{1, ElementMarker == regs["solid"]}, {0, True}}]];
gamma = Evaluate[
   Piecewise[{{1, ElementMarker == regs["solid"]}, {1.64, True}}]];
k = Evaluate[
   Piecewise[{{0.446, ElementMarker == regs["solid"]}, {50 0.0021,
      True}}]];
op = \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]\(u[t, x, y]\)\) +
   v.Inactive[Grad][u[t, x, y], {x, y}] -
   Inactive[
     Div][(-{{k, 0}, {0, k}}.Inactive[Grad][u[t, x, y], {x, y}]), {x,
     y}] - fac q[t];
Subscript[\[CapitalGamma], D1] =
  DirichletCondition[u[t, x, y] == 0,
   ElementMarker == bounds["inlet"]];
Subscript[\[CapitalGamma], D2] =
  DirichletCondition[u[t, x, y] == 0, ElementMarker == bounds["cold"]];
ufunHeat =
  NDSolveValue[{op == 0, u[0, x, y] == 0 , Subscript[\[CapitalGamma],
    D1], Subscript[\[CapitalGamma], D2], q[0] == 0,
    WhenEvent[{Mod[t, period],
      Mod[t + period duty, period]}, {q[t] ->
       If[q[t] == 0, 1/duty, 0]},
     "DetectionMethod" -> "Interpolation"]}, {u, q}, {t, 0,
    tmax}, {x, y} \[Element] mesh, DiscreteVariables -> q,
   MaxStepFraction -> 0.001];

We can see that the pinning effect is reduced, but it has not been eliminated.
Adding an Insulated Entrance Region
Next we will try adding an insulated entrance region before the heated element to mitigate the pinning at the entrance. I added a yellow insulated region to obtain the mesh shown below.

Unfortunately, I have reached the character limit, but when the above mesh is simulated, it produces the following:

We have substantially mitigated the pinning issue by extending the boundary.
Summary

*

*Created a 0D model of pulse heating with WhenEvent that behaves reasonably well.

*Developed some prototype code that facilitates the building of structured quad meshes and assignment of boundary conditions.

*Demonstrated that the quad mesh works reasonably well on a two layer heat equation system.

*Created a prototype with convection that works reasonably well.

*Made no attempts at validation and the code should be used at your own risk.


text:
Q: Elasticsearch Relations on Laravel i'm creating a Car Dealer web-site. And i'm trying to use elasticsearch for my search. But i dont understand relationships in elasticsearch. i have Cars, Car_Options , Brand , City tables. i'm keeping some meta-datas in Car_Options table. normally in mysql my tables like :
Car Table :
id , name , brand_id , price , city_id

Car_Options Table :
id , car_id , name , value

Brand Table :
id , name

City Table :
id , name

i tried to use this package for elasticsearch : iverberk/larasearch. I can index my Cars table (Model) and i can search on this table. But i could not understand how to fetch related datas from other tables. i read about relations on elasticsearch , but i could not implement it. Some of them tells about indexing them to one document. some of them tells about parent/child way.
So , my problem is , i dont understand how to index relations on elastic search and how to search them.
i indexed Cars and Cites to try but i could not get to true result.
i made some tries like :
return Car::search('NewYork', ['fields' => ['city.name']])->getResults();

Waiting for help about logic ! which way i should follow ? how should i index them with relations ?
Thank you !

A: The power of a NoSQL database like ElasticSearch is that nobody makes you do complicated realtions to avoid duplicate data.
This means that, personally, if the only thing you need to store in the car model is a city name, just save it there.
I really think it's quicker and more efficient to duplicate some data than to make 2 calls, one for Car model and another one for the related City.


text:
Q: java.io.FileNotFoundException on posting data from Android I am trying to post data from my android device to server through HTTPS Url, I am getting this error
  java.io.FileNotFoundException:https://URL
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
    at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5086)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    at dalvik.system.NativeStart.main(Native Method)

Can anyone help me?


text:
Q: Create Json Array in C# with data from SQL I have to get Data from SQL and send it as JSON to the frontend of the app. I'm not good in C# so I was Messing around with it. At the moment I get not Valid JSON:
  {"name":"Perez","company":"test"}{"name":"Jespersen","company":"Codeparc"}

As you can see it is not coming as an Array. How can I achieve that?
My Code:
 using System;
 using System.Data.SqlClient;
 using Newtonsoft.Json;

 namespace eltklt_webapp
{
//Create the Client Object
public class Client
{
    public string name;
    public string company;

}
public partial class getData : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["type"] == "clients")
        {
                // SQL Server Read Statement Sample
                using (SqlConnection conn = new SqlConnection(Gizmos.getConnectionString()))
            {
                SqlCommand command = new SqlCommand("select * from clients", conn);
                conn.Open();

                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Client Client = new Client();
                        Client.name = reader["name"].ToString();
                        Client.company = reader["company"].ToString();
                        string jsonString = JsonConvert.SerializeObject(Client);
                        Response.Write(jsonString);
                    }
                }
            }
        Response.End();
        }//end if Clients
    }
}
}

A: Have you tried to put your Client objects into an array or list and call JsonConvert.SerializeObject on the list?

A: protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["type"] == "clients")
    {
            List<Client> clients=new List<Client>();
            // SQL Server Read Statement Sample
            using (SqlConnection conn = new SqlConnection(Gizmos.getConnectionString()))
        {
            SqlCommand command = new SqlCommand("select * from clients", conn);
            conn.Open();

            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Client Client = new Client();
                    Client.name = reader["name"].ToString();
                    Client.company = reader["company"].ToString();
                    clients.Add(Client);
                    //string jsonString =                     JsonConvert.SerializeObject(Client);

                }
            }
        }
      var jsonString = JsonConvert.SerializeObject(clients);
      Response.Write(jsonString);
    Response.End();
    }//end if Clients
}

Hope this could give you basic idea.

A: Thanks! adding
 List<Client> clients=new List<Client>();

Doing the while loop and pushing the while into the client list with:
                clients.Add(Client);

Then Serialize it, solved the problem! Thank you guys!

A: If you can use SQL 2016 there is a much better way.
SELECT name, company from clients FOR JSON PATH

There is also a nice framework for streamlining the new JSON functionality in SQL 2016 here: https://github.com/ahhsoftware/EzAdoVSSolution


text:
Q: Correios API request Possuo um problema com meu código c#,estou tentando consumir a api dos correios porém os dados vem nulo, eu encontrei um outro tutorial na internet que dizia para instanciar a classe rastro e pegar a propriedade rastroJSON mas meu serviço não possui essa propriedade(rastroJSON), sendo essa propriedade rastroJSON exibida na página 7 da documentação dos correios.
Minha tentativa vindo os dados nulos:
            correios.rastro a = new correios.rastro();
            correios.sroxml xml = new correios.sroxml();
            xml = a.buscaEventos("ECT", "SRO", "", "U", "", "CODIGO");
            Console.WriteLine(xml.objeto);
            Console.ReadKey();

correios é o namespace da minha referencia.
o objeto do consolewriteline vem nulo, eu criei uma referencia de serviço com o endereço:
http://webservice.correios.com.br/service/rastro/Rastro.wsdl
tentei seguir o manual:
https://www.correios.com.br/para-voce/correios-de-a-a-z/pdf/rastreamento-de-objetos/manual_rastreamentoobjetosws.pdf, mas não funcionou.
Eu criei primeiro com uma referencia de serviço, logo em seguida tentei criando uma referencia de serviço web, nas propriedades avançadas.

A: O seu código está correto.
    correios.rastro a = new correios.rastro();
    correios.sroxml xml = new correios.sroxml();
    xml = a.buscaEventos("usuario", "senha", "tipo", "resultado", "lingua", "objetos");
    Console.WriteLine(xml.objeto);
    Console.ReadKey();

Para o buscaEventos você tem esses parâmetros:
usuario
Informado pela área
comercial dos Correios na
ativação do serviço. Este
campo diferencia letras
maiúsculas e minúsculas
(case-sensitive).
senha
Informado pela área
comercial dos Correios na
ativação do serviço. Este
campo diferencia letras
maiúsculas e min
tipo
L: lista de objetos. O
servidor fará a consulta
individual de cada
identificador informado; F:
intervalo de objetos. O
servidor fará a consulta
sequencial do primeiro ao
último objeto informado,
resultado
T: serão retornados todos
os eventos do objeto; U:
será retornado apenas o
último evento do objeto.
lingua
101: Serão retornados
todos os eventos no
idioma Português
102: Serão retornados
todos os eventos no
idioma Inglês.
objetos
Código do objeto formado
por 2 letras, 9 números e 2
letras. Este campo
diferencia letras maiúsculas
e minúsculas (casesensitive).
Exemplo: AA458226057BR
(sempre informar tudo em
letras maiúsculas).
Exemplo:
http://webservice.correios.com.br/service/rastro/Rastro.wsdl?"usuario=9999999999&senha=S@1234YWC5&tipo=L&resultado=T&lingua=101&objetos=JO999999999BR

A: Consegui identificar o problema. Ao importar a referência do WSDL a classe sroxml com propriedades explícitas, uma delas é a que está retornando null objeto.
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("objeto", Order=4)]
        public objeto[] objeto {
            get {
                return this.objetoField;
            }
            set {
                this.objetoField = value;
                this.RaisePropertyChanged("objeto");
            }
        }

Basta alterar o valor do primeiro parâmetro do XmlElementAttribute para Form=System.Xml.Schema.XmlSchemaForm.Unqualified:
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=4)]

Tente executar a chamada do WebService novamente e vc terá a response tipada.
Não sei porque o wsdl está configurado para gerar a classe dessa maneira, só sei que apenas alterando isso o WebService passou a trazer o objeto completo.
Existem outros campos com esse mesmo problema, basta repetir a solução.


text:
Q: How to write code for GUI designed in independent Qt designer using Qt creator? I have a manjaro Linux system. It comes preinstalled with a Qt designer software that has more widgets compared to default Qt creator. But I can only design GUI with this designer software. How would I write code for it?
I have Qt Creator 5.5 installed, but I don't know if it it possible to integrate these two and if yes, how?


text:
Q: I want to add a caption to this table, and the (\caption) is not working. I had two errors 1.Undefined control sequence. 2. \caption outside float \setlength\extrarowheight{3pt}
\setlength{\tabcolsep}{4pt}
\noindent
\begin{tabularx}{\textwidth}{|C||C||C|}
\hline
\multicolumn{3}{|c|}{Table 1: State of The ART Schemes With Intelligent Surfaces}\\
\hline\hline
 Scheme & Architecture & Functionality \\
\hline
Intelligent wall & Active frequency selective surfaces with PIN diodes & Fully transparent reflecting surfaces\\
Spatial microwave modulators & Binary phase state tunable meta-surfaces & Shaping complex microwave fields\\
Coding meta-materials & Meta-surfaces with binary elements (0 or $\pi$ phases) & Reconfigurable scattering patterns\\
Programmable meta-surface & Meta-surfaces with PIN diode-equipped cells & Reconfigurable phase, polarization, and scattering\\
Reconfigurable reflect-arrays & Reflect-arrays with tunable (varactor-tuned) resonators & Adjustable reflection phase\\
Large intelligent surface & Active contiguous surface for transmission and reception & Gains compared to massive MIMO   \\
Software-controlled hypersurface & Meta-surfaces equipped with IoT gateways & Wave absorption, polarization, and steering\\
\hline
\end{tabularx}

A: The \caption (of a tabular) should be inside the environment table.
The package caption helps to setup the format of the caption, but it is not needed to use the command \caption.

\documentclass[12pt,a4paper]{article}

\usepackage{array}
\usepackage{tabularx}
\usepackage{caption} % added

\newcolumntype{C}{>{\centering\arraybackslash}X}

\begin{document}

    \noindent
    \begin{table}% added <<<<<<<<<
        \setlength\extrarowheight{3pt}
        \setlength{\tabcolsep}{4pt}
        \caption{State of The ART Schemes With Intelligent Surfaces}
    \begin{tabularx}{\textwidth}{|C||C||C|}
%       \hline
%       \multicolumn{3}{|c|}{Table 1: State of The ART Schemes With Intelligent Surfaces}\\
%       \hline
        \hline
        Scheme & Architecture & Functionality \\
        \hline
        Intelligent wall & Active frequency selective surfaces with PIN diodes & Fully transparent reflecting surfaces\\
        Spatial microwave modulators & Binary phase state tunable meta-surfaces & Shaping complex microwave fields\\
        Coding meta-materials & Meta-surfaces with binary elements (0 or $\pi$ phases) & Reconfigurable scattering patterns\\
        Programmable meta-surface & Meta-surfaces with PIN diode-equipped cells & Reconfigurable phase, polarization, and scattering\\
        Reconfigurable reflect-arrays & Reflect-arrays with tunable (varactor-tuned) resonators & Adjustable reflection phase\\
        Large intelligent surface & Active contiguous surface for transmission and reception & Gains compared to massive MIMO   \\
        Software-controlled hypersurface & Meta-surfaces equipped with IoT gateways & Wave absorption, polarization, and steering\\
        \hline
    \end{tabularx}
\end{table}
\end{document}


text:
Q: Reading output from imagemagick subprocess in Python I am wanting to get the average brightness of a file in python. Having read a previous question [Problem getting terminal output from ImageMagick's compare.exe ( Either by pipe or Python ) I have come up with :
cmd='/usr/bin/convert {} -format "%[fx:100*image.mean]\n" info: >    bright.txt'.format(full)
subprocess.call(cmd,shell=True)
with open('bright.txt', 'r') as myfile:
    x=myfile.read().replace('\n', '')
return x

the previous question recommended the use of 'pythonmagick' which I can find but with no current documentation and very little recent activity. I could not work out the syntax to use it.
I know that my code is unsatisfactory but it does work.
Is there a better way which does not need 'shell=true' or additional file processing ?

A: This seems to works for me to return the mean as a variable that can be printed. (This is a bit erroneous. See the correction near the bottom)
#!/opt/local/bin/python3.6

import subprocess

cmd = '/usr/local/bin/convert lena.jpg -format "%[fx:100*mean]" info:'

mean=subprocess.call(cmd, shell=True)
print (mean)

The result is 70.67860, which is returned to the terminal.
This also works with shell=False, if you parse each part of the command.
#!/opt/local/bin/python3.6

import subprocess

cmd = ['/usr/local/bin/convert','lena.jpg','-format','%[fx:100*mean]','info:']

mean=subprocess.call(cmd, shell=False)
print (mean)

The result is 70.67860, which is returned to the terminal.
The comment from tripleee below indicates that my process above is not correct in that the mean is being shown at the terminal, but not actually put into the variable.
He suggested to use subprocess.check_output(). The following is his solution. (Thank you, tripleee)
#!/opt/local/bin/python3.6

import subprocess

filename = 'lena.jpg'
mean=subprocess.check_output(
    ['/usr/local/bin/convert',
     filename,
     '-format',
     'mean=%[fx:100*mean]',
     'info:'], universal_newlines=True)
print (mean)

Prints: mean=70.6786

A: You can probably improve the subprocess, and eliminate the temporary text file with Popen + PIPE.
cmd=['/usr/bin/convert',
     full,
     '-format',
     '%[fx:100*image.mean]',
     'info:']
pid = subprocess.Popen(cmd,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
out, err = pid.communicate()
return float(out)

ImageMagick also ships with the identify utility. The same method could be achieved with...
cmd=['/usr/bin/identify', '-format', '%[fx:100*image.mean]', full]

It might be worth exploring if it's worth working directly with ImageMagick's shared libraries. Usually connected through C-API (pythonmagick, wand, &etc). For what your doing, this would only increase code-complexity, increase module dependancies, but in no way improve performance or accuracy.


text:
Q: magento currency selection In the product category page I have a block 'select your currency',but it does not show any option in the list.
My currency.phtml file is
<?php if($this->getCurrencyCount()>=0): ?>

        <?php echo $this->__('Select Your Currency') ?>

        <select name="currency" title="<?php echo $this->__('Select Your Currency') ?>" onchange="setLocation(this.value)" >
        <?php foreach ($this->getCurrencies() as $_code => $_name): ?>

            <option value="<?php echo $this->getSwitchCurrencyUrl($_code) ?>"<?php if($_code==$this->getCurrentCurrencyCode()): ?> selected="selected"<?php endif; ?>>
                <?php echo $_name ?> - <?php echo $_code ?>
            </option>
        <?php endforeach; ?>
        </select>
        <?php echo $_code;?>

<?php endif; ?>

Is there any problem in this file ?
  In the system->configuration->currency setup
  Base currency: US dollar
  Default display currency:Canadian Dollar
  Allowed currencies:Canadian Dollar
In manage currency rate
1.03 can=1.00 US dollar
How to get more than one option in the list ?
also i want to know the purpose of all the layout handles in directory.xml file like
catalog_category_layered
catalogsearch_advanced_index
catalogsearch_result_index
catalogsearch_advanced_result etc.
Please help me.
Thanks in advance.

A: For the currencies I'd suggest reading this article by Inchoo as it clearly outlines how to manage the available currencies and some nice code snippets on how to display them to your own liking in the template.
On your second part of the question (in the future I would advise you to split them up into 2 questions). The handles refer to types of pages in Magento. For example catalog_category_layered applies to all Category pages that implement layered navigation while catalogsearch_result_index applies to the page that displays the search results. This Magento tutorial explains a lot on how the layout XML system works including the page handles.

A: The problem may be with the block type. I am not sure what block type you are using but to use the functions getCurrencyCount and getCurrencies this block will need to be of type Mage_Directory_Block_Currency.
If this is the case then you will need to step into these functions and see what exactly is going wrong.


text:
Q: Using custom HTML tags to WordPress Similar to, for example, <blockquotes>, I also work with, for example, custom <blocktips> styled with :before and :after elements to be used regularly on a site. After styling, these are added in the Text editor as <blocktip>Text here</blocktip>.
The problem is that when I go back to the Visual editor, these elements are removed from the code and has to be added again before Updating.
In my case, is there a way to prevent the WordPress editor from removing these custom HTML tags.

A: You can expand list of KSES allowed tags (and their attributes):
add_filter('wp_kses_allowed_html', 'wpse_283385_blocktip_tag');
function wpse_283385_blocktip_tag($allowed_tags) {
    $allowed_tags['blocktip'] = array(
        'name' => true,
        'id' => true,
        'class' => true,
        'style' => true
    );

    return $allowed_tags;
}

add_filter('tiny_mce_before_init', 'wpse_283385_blocktip_tag_tinymce');
function wpse_283385_blocktip_tag_tinymce($init) {
    $tags = 'blocktip[*]';

    if ( isset( $init['extended_valid_elements'] ) ) {
        $init['extended_valid_elements'].= ','.$tags;
    } else {
        $init['extended_valid_elements'] = $tags;
    }

    return $init;
}

If you need more attributes for that tag, add them in the array in the first function, or add them to $tags (comma separated) in the second.


text:
Q: View model Property setter not hit when dependency property updated I have a user control with a dependency property:
public ObservableCollection<Exclusion> SelectedExclusions
{
    get
    {
        return (ObservableCollection<Exclusion>)GetValue(SelectedExclusionsProperty);
    }
    set
    {
        SetValue(SelectedExclusionsProperty, value);
    }
}

public static readonly DependencyProperty SelectedExclusionsProperty =
       DependencyProperty.Register(nameof(TimeSeriesChart.SelectedExclusions),
                                   typeof(ObservableCollection<Exclusion>),
                                   typeof(TimeSeriesChart),
                                   new PropertyMetadata(default(ObservableCollection<Exclusion>)));

I am adding a selected exclusion to this collection on key down:
 protected override void OnKeyDown(KeyEventArgs e)
 {
   if(e.Key == Key.Delete)
   {
     this.SelectedExclusions.Add(this.ExclusionProviders[0].Exclusions[this.hitTestInfo.DataSeriesIndex]);
   }
 }

In the view model I have this property & backing variable:
 private ObservableCollection<TimeSeriesLibraryInterop.Exclusion> selectedExclusionsToDelete = new ObservableCollection<TimeSeriesLibraryInterop.Exclusion>();

 public ObservableCollection<TimeSeriesLibraryInterop.Exclusion> SelectedExclusionsToDelete
   {
     get
      {
        return this.selectedExclusionsToDelete;
      }
      set
       {
         this.selectedExclusionsToDelete = value;
         this.RaisePropertyChanged();
       }
     }

Finally the binding in the view:
   <userControl1 SelectedExclusions="{Binding SelectedExclusionsToDelete, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

The dependency property collection is initialised and populated however the view model property setter is never hit when the dependency property collection changes (Add). I have no binding errors in the output window. Is there something I'm missing here?

A: Looks like you're adding an item to the collection rather than replacing the collection. You won't hit the vm collection property's setter that way.
If you want to your viewmodel to respond to items being added to the SelectedExclusionsToDelete collection, the viewmodel will need to handle the SelectedExclusionsToDelete.CollectionChanged event. "Properly" handling that event (remove, add, move, clear, etc.) is a real hassle, but if it's not a giant collection you can often get away with something quick and dirty: Treat any change as a whole new collection. I think that's exactly the case you've got, too.
Alternatively, for an even quicker and dirtier approach, I think you could make it a two-way binding by default and have the control assign a new ObservableCollection to this.SelectedExclusions in OnKeyDown. The binding will pass it back to the viewmodel and hit the setter.


text:
Q: What would be a formal substitute for the informal quantifiers "a lot of" and "lots of"? A lot of, lots of with a noun
We use a lot of and lots of in informal styles. Lots of is more informal than a lot of. A lot of and lots of can both be used with plural countable nouns and with singular uncountable nouns for affirmatives, negatives, and questions:

*

*We've got lots of things to do.

*That's a lot of money.

*There weren't a lot of choices.

source

Can we use the quantifiers in formal writings, and is there any substitute for them?

A: Yes, they can be used in formal writing. More formal-seeming alternatives include "a great deal":

We've a great deal to do.
  That's a great deal of money.

"Many" is less formal than that, but more than "a lot":

We've many things to do.

But it can only be used with countable nouns. Don't use:

That's many money.

Then there's are some versions that are formal, but only work in some cases:

There wasn't a wide range of choices.

("Wide range" is singular, so weren't needs to become wasn't)
Other alternatives can be excessively complex/unusual, although they will be understood.

There wasn't a considerable quantity of choices.
  That's a considerable quantity of money.

A: MANY
ADJECTIVE, PRONOUN, & DETERMINER
A large number of.
as determiner 'many people agreed with her'
as pronoun 'the solution to many of our problems'
'many think bungee jumping is a new craze'
as adjective 'one of my many errors'
Many is a more formal phrasing than "lots of".


text:
Q: Format numbers for human consumption How to add thousands/millions comma separator to my code. I want to display a comma separator for the fields 'How much loan?' and 'Your Credit'? I am using d3.js.
This is my code:
http://jsfiddle.net/gfo46te1/39/
It is said that I should use d3.format but I can't get it to work inside my calculator.
var myNumber = 22400;
d3.format(',')(myNumber);

JavaScript:
var inputValues = {
    price: {
        _value: 5000,
        set value(val) {
            this._value = parseFloat(val);
            var tiv = inputValues.trade_in_value.value;
            var cdp = inputValues.cash_down_payment.value;

            if(this._value < tiv + cdp) {
                if(this._value > tiv) {
                    inputValues.cash_down_payment.value = this._value - tiv;
                } else {
                    inputValues.cash_down_payment.value = 0;
                    inputValues.trade_in_value.value = this._value;
                }
            }
        },
        get value() {
            return this._value;
        },
        min: 0,
        max: 500000,
        step: 1,
        reset: function () {
            this._value = 500000;
        }
    },
    cash_down_payment: {
        _value: 6000,
        set value(val) {
            this._value = parseFloat(val);
            var sum = this._value + inputValues.trade_in_value.value;
            if(sum > inputValues.price.value) {
                inputValues.trade_in_value.value = inputValues.price.value - this._value;
            }
        },
        get value() {
            return this._value;
        },
        min: 0,
        get max() {
            return inputValues.price.value;
        },
        step: 500,
        reset: function () {
            this._value = 6000;
        }
    },

};

A: *

*if people would only look at the DevTools console to see if the browsers barks.
var commaFormat = d3.format(',');

this._value = formatComma(parseFloat(val));

*How many tool tips do you need?

*You can't get ',' characters in the input box
<input type="number" class="calc__input" placeholder="Ile chcesz pożyczyć" min="0" max="500000" step="1">

*to get a comma in the Credit div convert the number using the d3.format() generator
document.querySelectorAll('.chart__description-value')
    .forEach(function (valueWrapper) {
        var value = legendData[valueWrapper.classList[1]];
        valueWrapper.textContent = formatComma(Math.round(value));
    });

*Where is the Reset Button?


text:
Q: Merge events in rxjs (Nestjs - saga cqrs) I am using cqrs with nestjs
I have a saga, that basically its rxjs implementations
@Saga()
updateEvent = (events$: Observable<any>): Observable<ICommand> => {
    return events$.pipe(
      ofType(UpdatedEvent,),
      map((event) => {
        return new otherCommand(event);
      })
    );
  };
}

the question is How can I merge Events that all extend the same class
So I want only 1 saga to catch all events instead of saga per event
I tried
ofType(UpdatedEvent,CreateEvent,DeleteEvent),

but it does not work and typescript does not allow that , and also because of the generic type i got this :
right-hand side of 'instanceof' is not callable
my events is like:
class UpdateEvent extends Base<UpdateDto>{
   constructor(){super()}
}
class CreateEvent extends Base<CreateDto>{
   constructor(){super()}
}

there are differences between the events is the Dtos

A: Instead of using ofType you could just use filter(x => x instanceof UpdatedEvent || x instanceof CreateEvent || x instanceof DeleteEvent)
If this is a pattern you use often you could easily write a utility function eg instanceOneOf that takes a bunch of values in an array and does the instanceof checks internally.
Then you could do something like filter(x => instanceOneOf([UpdatedEvent, CreateEvent, DeleteEvent], x))


text:
Q: Is this authentication with Passport secure by design? I'm new to Node, Passport and authentication in web development in general
I followed this tutorial for setting up local authentication using the Passport module.
I was hoping an experienced developer could comment on the security of the design being taught there.
More specifically,
1) When the author does a POST for sending credentials, shouldn't he be doing it over HTTPS? When is it necessary to use HTTPS so that others aren't sniffing your information? How could the design be changed to POST using HTTPS?
2) I can't follow how session is being kept track of. Does passport abstract all of the session work? If so, are they using cookies? Are the cookies plaintext? Does the user get a token back in a cookie? Is that how isLoggedIn() works?
3) Is he getting any protection from content injection for free? I don't see any code to try and escape dangerous characters or anything.
Anyway, how hacker safe is this design?


text:
Q: Error while sending data from lambda to firehose I am testing my code that sends data from aws lambda to firehose. This is my code:
client = boto3.client('firehose')
for item in items:
    response = client.put_record(
        DeliveryStreamName='iot-firehose',
        Record=item)

My item will be a dictionary like this:
{
        'IMEI':123,
        'Time':'time',
        'Voltage':some voltage(type int),
        'Current':some Current(type int),
    }

I am getting this error, I went through documentation but I can't figure out where I am doing wrong.
[ERROR] ParamValidationError: Parameter validation failed:Missing required parameter in Record: "Data"Unknown parameter in Record: "IMEI", must be one of: DataUnknown parameter in Record: "Time", must be one of: DataUnknown parameter in Record: "Voltage", must be one of: DataUnknown parameter in Record: "Current", must be one of: DataTraceback (most recent call last):  File "/var/task/lambda_function.py", line 19, in lambda_handler    response = client.put_record(  File "/var/runtime/botocore/client.py", line 357, in _api_call    return self._make_api_call(operation_name, kwargs)  File "/var/runtime/botocore/client.py", line 648, in _make_api_call    request_dict = self._convert_to_request_dict(  File "/var/runtime/botocore/client.py", line 696, in _convert_to_request_dict    request_dict = self._serializer.serialize_to_request(  File "/var/runtime/botocore/validate.py", line 297, in serialize_to_request    raise ParamValidationError(report=report.generate_report())

A: I actually figured it out. That data "item" that I was sending was a python dictionary but it can needs data that is JSON .SO, json.dumps(item) solved it. There was a syntex error also, it should be response = client.put_record(DeliveryStreamName='iot-firehose',Record={'Data':json.dumps(item)}).


text:
Q: Why there is a segmentation fault when calling printf from a class? This is the relevant part (I think) of my source code
#include <iostream>
#include <cstdarg>
#include <cstring>
#include <cstdlib>

class Poly
{
private:
    double *coefficients;
    size_t degree;
    inline double *cfp(size_t i);

public:
    Poly();
    Poly(size_t n, ...);

    void Print() const;
    ~Poly();
};

Poly::Poly()
{
    this->degree = 0;
    this->coefficients = new double(1);
    *(this->coefficients) = 1.;
}

Poly::Poly(size_t n, ...)
{
    va_list coefs;
    va_start(coefs, n);

    this->degree = n;
    n++;
    register double *cfs = new double(n);
    this->coefficients = cfs;

    while (n--)
    {
        *cfs = va_arg(coefs, double);
        cfs++;
    }

    va_end(coefs);
}

void Poly::Print() const
{
    bool started = false;
    double c = this->cf(0);
    putchar('a');
    std::cout << this->degree << '\n';
    if (c != 0.)
    {
        std::cout << c;
        started = true;
    }

    size_t N = this->degree;

    for (size_t i = 1; i <= N; i++)
    {
        c = this->cf(i);
        if (c != 0.)
        {
            if (!started)
                started = true;
            else
                std::cout << ((c < 0.) ? " - " : " + ");
                //printf(" + ");
            std::cout << fabs(c) << " x^" << i;
            //printf("%lf x^%lu", c, i);
        }
    }
    printf("\n");
}

Poly::~Poly()
{
    delete this->coefficients;
}

int main()
{
    //printf("\n");        <- Uncommenting this line stops the error
    Poly p1(7, 1., 3., -9., 2., 0., 8., -2., 6.);
    p1.Print();
}

Right now, Print method has many printfs and couts. But when I uncomment the line from main, malloc brings segmentation fault at the first print or cout or even putchar from the 'Print` method. I cannot find any memory leaks there. Why does it happen and how to prevent it?
I am using gcc (g++) 9.3.0 on WSL Ubuntu. The program is compiled with the flags -lc -g.
gdb showed me this
malloc(): corrupted top size

Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50      ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) backtrace
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x00007ffff7c0f859 in __GI_abort () at abort.c:79
#2  0x00007ffff7c7a3ee in __libc_message (action=action@entry=do_abort, fmt=fmt@entry=0x7ffff7da4285 "%s\n")
    at ../sysdeps/posix/libc_fatal.c:155
#3  0x00007ffff7c8247c in malloc_printerr (str=str@entry=0x7ffff7da2556 "malloc(): corrupted top size") at malloc.c:5347
#4  0x00007ffff7c8583a in _int_malloc (av=av@entry=0x7ffff7dd5b80 <main_arena>, bytes=bytes@entry=1024) at malloc.c:4107
#5  0x00007ffff7c872d4 in __GI___libc_malloc (bytes=1024) at malloc.c:3058
#6  0x00007ffff7c6ee84 in __GI__IO_file_doallocate (fp=0x7ffff7dd66a0 <_IO_2_1_stdout_>) at filedoalloc.c:101
#7  0x00007ffff7c7f050 in __GI__IO_doallocbuf (fp=fp@entry=0x7ffff7dd66a0 <_IO_2_1_stdout_>) at libioP.h:948
#8  0x00007ffff7c7e0b0 in _IO_new_file_overflow (f=0x7ffff7dd66a0 <_IO_2_1_stdout_>, ch=97) at fileops.c:745
--Type <RET> for more, q to quit, c to continue without paging--
#9  0x00007ffff7c73482 in putchar (c=97) at putchar.c:28
#10 0x0000555555555cfe in Poly::Print (this=0x7fffffffdb90) at polynomial_r.cpp:241
#11 0x0000555555555fd2 in main () at test.cpp:7
(gdb) info frame
Stack level 0, frame at 0x7fffffffd6f0:
 rip = 0x7ffff7c3018b in __GI_raise (../sysdeps/unix/sysv/linux/raise.c:50); saved rip = 0x7ffff7c0f859
 called by frame at 0x7fffffffd820
 source language c.
 Arglist at 0x7fffffffd5c8, args: sig=sig@entry=6
 Locals at 0x7fffffffd5c8, Previous frame's sp is 0x7fffffffd6f0
 Saved registers:
  rip at 0x7fffffffd6e8
(gdb)

A: Looks like you corrupted your heap by writing past the end of your heap-allocation.  I think your problem is here:
register double *cfs = new double(n);

Note that the above code allocates a single double set to value n, when I think what you wanted to do was allocate an array of n doubles.  To do that you'd need to use brackets instead of parentheses:
register double *cfs = new double[n];


text:
Q: Assignment operation in member initializer lists I have the following Stack class.
class Stack{
public:
    int size;
    int* x;
    Stack() : size(10), x(new int[10]) {}
    Stack(const Stack& s) : x(new int[size=s.size]) {}

};

Notice the assignment in the copy constructor. The code works, compile fine and compiler (gcc) doesn't complain even with -Wall -Wextra flags. Does the compiler automatically rewrite the compiler to this?
Stack(const Stack& s) : size(s.size), x(new int[size]) {}

Or is there some other magic? I noticed when I change the definition order, the compiler complaints about not-in-order initialization. So I assume it's the case I mentioned. I couldn't find anything in the documentation and the ASM output doesn't help me either.

A:
Does the compiler automatically rewrite the compiler to this?
Stack(const Stack& s) : size(s.size), x(new int[size]) {}

No.
Stack(const Stack& s) : x(new int[size=s.size]) {}

can be though of as being
Stack(const Stack& s) : size(), x(new int[size=s.size]) {}

but it isn't really since actually writing size() would value initialize it, meaning it is zero initialized, but since it is the compiler that synthesizes the initialization, default initialization[1] happens meaning it is not initialized. Then you assign a value to it in x's initialization.  This is "safe", meaning it works in this case, but I wouldn't recommend it it.
Stack(const Stack& s) : size(s.size), x(new int[s.size]) {}

initializes both members and if you ever change the order of them in the class, you will still have the correct behavior.

A: Members of a class are always initialized in order of declaration, regardless of the order you specify them in the member initialization list. And if you omit them, they are default initialized. So doing this:
Stack(const Stack& s) : x(new int[size=s.size]) {}

Means that size is default initialized first. That leaves it with an indeterminate value (as fundamental types are supposed to be default-initialized). Then the initializer for x is evaluated. Part of evaluating new int[size=s.size] involves the assignment expression size=s.size, which modifies size as a side effect. So your code is correct here, despite being likely to raise eyebrows.
When you switch the order of the members around, then the assignment happens before size is supposed to be initialized. That leaves your code code open to undefined behavior.

A: From the Cppreference.com page on constructors:

Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor:

So yes, size here refers to this->size in the scope of the constructor, and the assignment size=s.size is a valid expression.
It goes without saying that you should not expect this to pass a code review :)

A: No, it rewrites it to this:
class Stack{
public:
    int size;
    int* x;
    Stack() : size(10), x(new int[10]) {}
    Stack(const Stack& s) :size(), x(new int[size=s.size]) {}
};

size() would be a default constructor for the object size but ints don't have one, so its just an empty statement and size remains uninitialized. Or does it?
I would say this code might generate undefined behavior. The member variables are initialized in the order in which they are declared as per 10.9.2 Initializing bases and members. But the evaluation order of the expressions used for the initialization is not defines. So, size=s.size can be called either before or after size(). For class types that would be a problem, but I am not sure whether size() is guaranteed to be no-op and whether the compiler might decide to initialize the variable to e.g. 0.


text:
Q: Alias in bash to add formatted current date to git commit message I am trying to add alias for a default commit message, something like this:
alias gc='git commit -m "Default commit: $(date)"'

but I don't like date's default format and would like to change it to this:
date +'%A, %d %B %Y %H:%M:%S' # Tuesday, 02 May 2017 23:12:07

I run into problem of how to build this in alias. I cannot handle the multiple double and single quotes. Can someone help?

Edit.
Thanks for the suggestion on using function and the code. Based on that I have made this, slightly changed:
gc ()
{
    if [ "$#" == "0" ]; then
        itsmsg="Deafult commit";
    else
        itsmsg="$*";
    fi;
    git commit -m "$itsmsg ($(date +'%A, %d %B %Y %H:%M:%S'))"
}

A: As @123 mentioned, you should use a function instead of an alias. This eliminates a level of quoting.
gc () {
  git commit -m "Default commit: $(date +'%A, %d %B %Y %H:%M:%S')" "$@"
}

A: Use ANSI C quoting so that you can escape single quotes inside single quotes:
alias gc=$'git commit -m "Default commit: $(date +\'%A, %d %B %Y %H:%M:%S\')"'


text:
Q: Should an AWS EC2 instance connect using only IPv4 Public IP? If I put the "IPv4 Public IP" of my EC2 instance in the browsers address shouldnt it connect and return an error message instead of just giving time out ?

A: So, it sounds like you are attempting to connect to the instance via SSH.
Things to check:

*

*The Security Group associated with the instance needs to have port 22 open to either your Public IP address, or to 0.0.0.0/0 (which is not a good security practice)

*You are on a network that is not blocking SSH traffic. Some corporate network prohibit such access (so try it from home).

*The instance is running an SSH server. This is standard on Linux distributions, such as the Amazon Linux AMI. (Believe it or not, some people wonder why they can't SSH to a Windows instance.)

*You should be trying to connect to a public IP address associated with the instance

*The instance needs to be in a Public Subnet (which means the Route Table associated with the Subnet is pointing 0.0.0.0/0 traffic to an Internet Gateway). If you are using the Default VPC, then this is done for you.

*You have the private half of the keypair that was nominated when the instance was launched. If you are using an Amazon Linux instance, the private half of the keypair would have been automatically copied to: /home/ec2-user/.ssh/authorized_keys
The fact that your connection is timing-out, as opposed to receiving an error message, most likely makes it an incorrectly configured Security Group. (Trust me, it's almost always the Security Group!)


text:
Q: How to change a maximum file size limit with php
Possible Duplicate:
PHP change the maximum upload file size

I use a free Web hosting service (Apache/2.2.17) on UNIX, I think . I use a php script to append data to some file in my home dir, with such code:
$my_handle = fopen($my_file_name, 'ab');
$bytes = fwrite($my_handle, $my_data);
fclose($my_handle);

When the file size reaches 128 MB, the script terminates, but no error is produced. So, I have to save data in 128 MB parts. Is there any way that I can change this "128 MB file size limit"?
Thanks!

A: You can change the configuration in the PHP settings but you won't have that option available on free hosting.
Upgrade your hosting.