text:
Q: Possible to insert into two tables where one of the table is shortage of auto_increment_ID? Table Product
pid  product_name

Table Category
cid category_name

Table Product_category
cid pid

For table Product and Category, their primary keys are "pid and cid" with auto_increment
For product_category table, its used to store the data where 1 product is assigned to multiple categories and thats why the table columns are "cid and pid"
I am using php+mysql to write some functions like creating new product, category and then assign product to one or multiple categories.
Assume that we have created a 2 categories with cid-> 1,2
3 steps to assign product to category

*

*add new product so that we have pid->123

*then assign this product into category cid->1

*insert into database table Product_category with pid->123 and cid->1

I want to do something simple like this instead
1. add new product and assign this product to category at the same time
However, for Table Product_category, it needs 2 value which are pid and cid , so that means we only know this pid after creating new product as its auto_increment. So my question is how to know this pid when adding new product? OR its impossible to do it this way?
public function conn(){

    $this->db_host="localhost";
    $this->db_name="bs";
    $this->db_user_name="root";
    $this->db_pass="";

    return mysqli_connect($this->db_host, $this->db_user_name, $this->db_pass, $this->db_name);
}

$query = "INSERT item(uid,item_id,item_name,item_price,item_quantity)
                    VALUES('$this->user_uid','$this->item_id','$this->item_name','$this->item_price','$this->item_quantity')";

    if (!mysqli_query($this->conn(), $query)) {
        echo "Failed to Add item!" . mysqli_error($query);
        return false;
    }else{
        printf("Last inserted record has id %d\n", mysqli_insert_id($this->conn()));
        return true;
    }

I try to test by adding new records, but it always get this
"Last inserted record has id 0"

A: I think your SQL required mysql_last_id so it should be like this
INSERT INTO Product VALUES(null, product_name);
$product_last_id = LAST_INSERT_ID();

INSERT INTO Category VALUES($product_last_id, category_name);
$category_last_id = LAST_INSERT_ID();

INSERT INTO Product_category VALUES($product_last_id, $category_last_id);

Have a look at LAST_INSERT_ID().

A: The cause of your mistake is the method conn. Because you create a new connection for every call $this->conn(). A new connection doesn't know anything about INSERT statement that was performed in previous connection that is why mysqli_insert_id returns 0. A quick solution is to define a new var $conn = $this->conn(); and use this one in all queries.

A: You need to set 2 database call first is product table. Insert a product. Then you will get the return value as pid, and I think you will get the cid from the page itself. You will select the option the new products belongs to which category then you can pass the cid. Then you can set the second database call insertProduct_categoryTable(cid,pid).


text:
Q: Defining pointers vs accessing values in an Array in Ruby Let's say I'm passing the following array to a method:
input = [1,9,10,3,2,3,11,0,99,30,40,50]

I need to work with sets of 4 numbers from that array as follows:
OPCODE = input[0] # first of the 4 numbers
pos1_pointer = will always be opcode position + 1 position to the right
pos2_pointer = will always be opcode position + 2 positions to the right
output = will always be opcode position + 3 positions to the right

pos1 and pos2 numbers are actually pointers to the actual values (eg. pos1_pointer = 9 (one position from opcode), actual value 30 (position 9 in the array).
How do I define the pointer based on where the OPCODE is sitting?
I've tried:
pos1_pointer = input[input[opcode] + 1] # points to 40 which is wrong (because opcode = input[0] which is 1, and it sums 9 positions to that, position 10 being value 40)
pos1_pointer = input[opcode + 1] # is also wrong because it assigns a value of 2 to it (it sums 1 to the value of opcode which is 1)

A: Use Iterators Rather Than Indexing
In Ruby, if you want to work with subsets of an array, there's a method for that! Array#each_slice can be used to feed your slices directly into a method, or to deconstruct them further. For example:
input = [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]

input.each_slice(4) do |slice|
  opcode, pos1, pos2, output = slice
  pp slice
end

You could replace pp slice with a call to your method(s) of choice, passing in either the whole slice or the deconstructed values as positional or keyword arguments. Let Ruby manage the indexing so you can focus on more important things.

A: Why not try this. The first argument, arr, is the array. The second argument, i, is the index at which you want to start from.
The method bellow will take the array and the index and then return an array starting from the whichever index, in this case 0, and then return everything between index 0 and index 0+3.
Double dots x..y means go from range x up to y. Triple dot x...y means start from x and go up to BUT exclude y.
def four(arr, i)
  return arr[i..i+3]
end

print four([1,9,10,3,2,3,11,0,99,30,40,50],0)
# input = [1,9,10,3,2,3,11,0,99,30,40,50]
# output = [1,9,10,3]

redpajama_set_name: RedPajamaStackExchange


text:
Q: my for loop in bash is not counting files and directories I'm writing a small script in bash to practice, I find the syntax of my code correct but I'm surely missing something, this is my code:
#!/bin/bash

cfiles=$(ls | wc -l)

echo $cfiles

files=0
dirs=0

for look in $(ls); do
   [ -d look ] && $((++dirs)) || $((++files))
done

echo "Files: $files"
echo "Directories: $dirs"

I'm receiving a long error message and wrong output:
22
test.sh: line 11: 1: command not found
... (until number 48)
test.sh: line 11: 48: command not found
Files: 48
Directories: 0

What's wrong with my code? It reaches a count of 48 with command not found, but there are 22 files excluding . and .. then it's doubling the number.
Thank you very much for helping!

A: $((++dirs)) expands to a number, which is then executed as a command, hence the error 1: command not found.
To just execute ++dir without expanding the result, use ((++dir)) without the $. Same for ++files.

It reaches a count of 48 with command not found, but there are 22 files

Then your file names contain whitespace or special symbols like *[]?. See Why you shouldn't parse the output of ls.
You can make your script a lot simpler and safer by using globs instead of ls. Also, the loop is not necessary with arrays or a function that counts its arguments.
#! /bin/bash
count() { echo $#; }
total=$(count *)
dirs=$(count */)
((files=total-dirs))

A: Compare how the shell handles expansion:
$ ls -t
'this file'   file  'this directory'   directory
$ for f in $(ls) ; do echo "[$f]" ; done
[directory]
[file]
[this]
[directory]
[this]
[file]
$ for f in * ; do echo "[$f]" ; done
[directory]
[file]
[this directory]
[this file]

So in one line:
$ dirs=0; files=0; for f in * ; do [ -d "$f" ] && ((++dirs)) || ((++files)) ; done ; echo "d: $dirs f: $files"


text:
Q: initialise timezoneJS with JSON files I'm working with timezone-js: https://github.com/mde/timezone-js. I have a list of predefined timezones I want to work with. So I pre-parsed JSON Data of those timezones.
But how exactly am I supposed to use this data?
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);

I can read the data, like here. But how am I supposed to use the tz variable to initialise timezoneJS?
I'm thinking that I'm supposed to do something like this first:
timezoneJS.timezone.loadZoneDataFromObject(_tz);
And then initialise it... And then initialise timezoneJS, but if I initialise now, I'll get an error that it can't find the default timezone: Uncaught Error: Error retrieving "null/northamerica" zoneinfo files, probably because I've supplied the json data.
Can I'd like to know what to do to use the json file, so I can create timezoneJS.Date objects.

A: First of all, tz_ is just a short cut which prevents writing timezoneJS.timezone in the subsequent lines.
Now, there are two options. If you have your file major_cities.json on the server and you want to initialize timezoneJS you just have to do what you wrote:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);

and you're all set. The second option is that you have an object containing data from that file. In such case you should use loadZoneDataFromObject instead of loadZoneJSONData, namely:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneDataFromObject(majorCitiesObject);

After that, you should not try calling the init function, hence timezoneJS is already initialized by the loadZoneJSONData. If you want to create a date, just call new timezoneJS.Date(). The following lines should give you a hint:
var timezoneName = 'Europe/London';
var newDate = new timezoneJS.Date(timezoneName);
console.log(newDate.toString());
console.log(newDate.toISOString());

Result should be sth like:
2013-04-08 11:56:33
2013-04-08T10:56:33.019Z


text:
Q: Next.js Link position <Link href={`/user/${username}`}>
  <List.Item active={router.query.username === username}>
    <List.Icon name="user" size="large" />
    <List.Content>
        <List.Header>
            Account
        </List.Header>
    </List.Content>
  </List.Item>
</Link>

If I use the next Link in the way above, my a tag is not a direct child of the next Link and my question is: is the href passed from Link to the a tag ? Otherwise I think It could hurt my web site SEO
(I now I can directly use Link around the a tag, I ask this because it could save my some styling)


text:
Q: Unable to parse events in grafana annotations I am working on Grafana for the first time. As a part of learning curve I have started exploring grafana annotations.
I am sending a custom value (build parameter) as an annotated value from Jenkins to Grafana. Here is the command.
"%curlPath%" -XPOST "%influxURL%" -H "Authorization: Bearer %gf_token%" --data-binary 'events text="%CRN%",tags="jenkins-builds"'

It's throwing below error:
D:\JenkinsAgentNode\workspace\E2E\anno-test>"C:\Program Files\Git\mingw64\bin\curl.exe" -XPOST "http://xx.xx.xx.xxx:8086/write?db=grafana&precision=n" -H "Authorization: Bearer ****" --data-binary 'events text="CR-177-117890",tags="jenkins-builds"'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100    61  100    54  100     7  18000   2333 --:--:-- --:--:-- --:--:-- 30500{"error":"unable to parse ''events': missing fields"}

curl: (3) URL using bad/illegal format or missing URL

Please find below screen shot of annotation configuration in grafana.

I am scratching my head because the same command worked in Linux based instance (below command), and I got to see an annotation marking in Grafana.
curl -XPOST "http://xx.xx.xx.xxx:8086/write?db=grafana&precision=n" -H "Authorization: Bearer $grafana_api" --data-binary 'events text="'$CRN'",tags="jenkins-builds"'

Annotation configuration is same as the above one.
Please guide me where I am committing mistake.
Regards

A: The solution to highlighted issue is to run curl in sh mode instead of bat mode in Windows OS.
Hope this helps future readers :)


text:
Q: Import data if the day of a cell matches the dates of the data in another sheet (in batch) - Google Apps Script I have a worksheet called "Calendario". In this sheet, there is a range of non-consecutive cells that correspond to the days of the month.
I have a worksheet called "Tareas/Eventos". In this sheet are added the tasks with their corresponding data.
My goal is that in each of the cells in the range of non-consecutive cells that correspond to the days of the month in the "Calendar" sheet, look in the "Tareas/Eventos" sheet if there are tasks with a matching date. If there are positive results, then copy the icon + task name and the checkbox from the "Tareas/Eventos" sheet to the range of rows corresponding to that cell of the day of the month of the "Calendario" sheet

Example:
In the Calendario sheet, cell "E20" corresponds to the 6th day of the month. Together with cell "A6" and cell "A10" it makes a date of 06 Feb. 2023
Then, in the "Tareas/Eventos" sheet, look for tasks with start date >= and end date <= on Feb. 6, 2023. Positive results will be copied to the range "E22:F34" with a maximum of 13 imported tasks ( from newest to oldest) in the "Calendario" sheet.
In column E within the range of maximum rows, the icon and the name of the task will be copied (concatenate). In column F within the range of maximum rows, the checked or unchecked checkbox will be copied.

This process must be repeated with all the cells that contain a day of the month.
Cells that do not contain day of the month (within range) are excluded.
Obviously, if there are cells with the day of the month, but there are no matching tasks, they are also excluded.
Now, I have managed to carry out this whole process with individual functions for each day of the month and their corresponding maximum rows (Calendar Sheet).
However, since there are 41 different ranges, merging all the individual functions into 1, the "parent" function has a high execution time.
Therefore, I would like to create a single function that does the whole process in "batch".
The problem is that I am a beginner and I don't really know how to handle so many different searches at the same time, as well as to place the matching tasks in their proper range of maximum rows.
I have made an attempt at it, and although at first it seemed that the thing was taking shape, somehow, in the end I have not managed to make it work. Possibly I am doing a wrong approach in some part of the code.
Here is a sample sheet:
https://docs.google.com/spreadsheets/d/1S1daQLMzrTi7eWxHgcsDhzhXOE8oZYKYOntO2Q0alvU/edit?usp=sharing
And here is an image:

This is my global code, the one that is supposed to work in batch...
function day_vistaMensual() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sourceSheet = ss.getSheetByName(' Tareas/Eventos');  // Hoja Origen
  const targetSheet = ss.getSheetByName(' Calendario (pruebas)');  // Hoja Destino
  var lastRowTareas = sourceSheet.getLastRow();  // Get last row of "Tareas/Eventos" Sheet.

  // Get the month and year from the "Calendar" sheet.
    var targetSheetMonth = targetSheet.getRange("A6").getValue();
    var targetSheetYear = targetSheet.getRange("A10").getValue();

  // We get the cell range of the day of the month from the "Calendario" sheet.

    var targetSheetDayCells = ['E4', 'H4', 'K4', 'N4', 'Q4', 'T4', 'W4', 'E20', 'H20', 'K20', 'N20', 'Q20', 'T20', 'W20', 'E36', 'H36', 'K36', 'N36', 'Q36', 'T36', 'W36', 'E52', 'H52', 'K52', 'N52', 'Q52', 'T52', 'W52', 'E68', 'H68', 'K68', 'N68', 'Q68', 'T68', 'W68', 'E84', 'H84', 'K84', 'N84', 'Q84', 'T84', 'W84'];

    var targetSheetDayRange = targetSheet.getRangeList(targetSheetDayCells);
    var targetSheetDateRangeVal = targetSheetDayRange.getRanges();

    targetSheetDateRangeVal.forEach(r => {
          var targetSheetDay = r.getValues();  // Valor de la celda
          var dayA1Notation = r.getA1Notation();  // Posicion de la celda
          Logger.log(targetSheetDay);
          Logger.log(dayA1Notation);

          if (targetSheetDay != '') {
            targetSheetDate = new Date(targetSheetDay + targetSheetMonth + targetSheetYear);  // Fecha de la celda en celdas no vacias
            Logger.log(targetSheetDate);
          } else {
            return;
          }
    });

  // Maximum number of rows per task in the "Calendario" sheet
    var maxTargetRows = 13;

  // Select the range of the Source sheet where the search will be made.
    var sourceSheetDates = sourceSheet.getRange('B5:H' + lastRowTareas).getValues();

  // We make the comparison of dates between the "Calendar" sheet and the "Tasks/events" sheet and confirm if there are matching tasks.

    var targetRowValues = []

    for (var i = sourceSheetDates.length - 1; targetRowValues.length <= maxTargetRows && i >= 0; i--) {
      var dateStartSourceSheet = new Date(sourceSheetDates[i][5]);

      // Compares the date of each row of the source sheet with the date of the target sheet.

      if (dateStartSourceSheet.getDate() == targetSheetDate.getDate() && dateStartSourceSheet.getMonth() == targetSheetDate.getMonth() && dateStartSourceSheet.getFullYear() == targetSheetDate.getFullYear()) {
        var iconTask = sourceSheetDates[i][1] + ' ' + sourceSheetDates[i][2];
        var checkbox = sourceSheetDates[i][0];

        targetRowValues.push([iconTask, checkbox]);
      }
    }

  // If it doesn't find a match, then do nothing.

    if (targetRowValues.length === 0) {
      Logger.log('Sin coincidendias. -- No matches.');
      return;
    }

  // Range of maximum rows for each cell of the day of the month of the sheet "Calendario"

    var targetRows = targetSheet.getRangeList("E6:E18", "H6:H18", "K6:K18", "N6:N18", "Q6:Q18", "T6:T18", "W6:W18", "E22:E34", "H22:H34", "K22:K34", "N22:N34", "Q22:Q34", "T22:T34", "W22:W34", "E38:E50", "H38:H50", "K38:K50", "N38:N50", "Q38:Q50", "T38:T50", "W38:W50", "E54:E66", "H54:H66", "K54:K66", "N54:N66", "Q54:Q66", "T54:T66", "W54:W66", "E70:E82", "H70:H82", "K70:K82", "N70:N82", "Q70:Q82", "T70:T82", "W70:W82", "E86:E98", "H86:H98", "K86:K98", "N86:N98", "Q86:Q98", "T86:T98", "W86:W98");

    var targetFirstRow = targetRows.getRow();
    var targetSheetCols = ['E', 'F', 'H', 'I', 'K', 'L', 'N', 'O', 'Q', 'R', 'T', 'U', 'W', 'X'];

    for (var i = 0; i < targetSheetCols.length; i++) {

      // Get the values per column.
      var colValues = targetRowValues.map(function (row) { return [row[i]] });

      // Write the column values starting from the first row of the destination range.
      targetSheet.getRange(
        targetSheetCols[i] + targetFirstRow +
        ':' +
        targetSheetCols[i] + (targetFirstRow + targetRowValues.length - 1))
        .setValues(colValues);
    }
}


text:
Q: Updating Azure Batch autoscale formula once pool exists I can create a pool with an autoscale formula fine. The code for this is as follows.
var pool = client.PoolOperations.CreatePool(poolName, vmsize, new CloudServiceConfiguration(osFamily, osVersion));
pool.TaskSchedulingPolicy = new TaskSchedulingPolicy(ComputeNodeFillType.Pack);
pool.AutoScaleFormula = autoscaleFormula;
pool.AutoScaleEnabled = true;
pool.AutoScaleEvaluationInterval = new TimeSpan(0, 0, 5, 0);
pool.Commit();

However if once the pool exists, I try and update the AutoScale formula, I get an error. The error is

{"The property AutoScaleFormula cannot be modified while the object is
  in the Bound state."}

The code is
var client = BatchClient.Open(GetCloudSharedKeyCredentials(primary));
var pool = client.PoolOperations.GetPool(poolName);
pool.AutoScaleFormula = formula;
pool.AutoScaleEnabled = true;
pool.AutoScaleEvaluationInterval = new TimeSpan(0, 0, 5, 0);
pool.Commit();

This used to work before I updated to the latest version of the Azure Batch library. Has anyone got any experience of Azure Batch and can advise why I'm getting this error?

A: You can use the PoolOperations.EnableAutoScale method directly.
For your example, you could use the following:
var client = BatchClient.Open(GetCloudSharedKeyCredentials(primary));
client.Pooloperations.EnableAutoScale(poolName, formula, TimeSpan.FromMinutes(5));


text:
Q: 3D rotation by a complex angle around a complex axis. Context
In electromagnetism, it is common to meet complex angles.
Snell's law can produce them (with metals and/or total internal reflection), and when we plug them into Fresnel's equations, the results make physical sense: evanescent or inhomogeneous waves.  The real and the imaginary parts of the complex wave vector are not collinear anymore: the wave propagates in one direction but decays in another.  In other words, the planes of iso-phase and iso-amplitudes are not parallel anymore.
I am not sure yet that I can make use of complex axes of rotation, but it seems natural to consider them.
Question
Rotating by a complex angle around a real axis seems trivial from an algebraic point of view: we can represent it with a matrix of complex numbers.
We should also be able to generalize it to rotations around complex axes: it's also just a matrix.
I can easily construct a 3D rotation matrix for a real axis and a real angle by creating a versor.  But what happens when the versor is not a quaternion but a biquaternion?  If $q$ is my complex versor and $v$ the complex vector that I wish to rotate, does $v'=qvq^{-1}$ still work?  Or should I throw in some complex conjugations?
Edit 1: experiment
I wanted to compare a rotation matrix created without quaternion to a rotation matrix created with a quaternion.  If these two matrices differ, then it means that the way I construct my quaternions is broken.
Without using quaternions, it is easy to create the matrix of a rotation around the axes $x$ $y$ and $z$, anything else is trickier.
These are, of course, real axes of rotation, not complex ones.
However, I can use complex angles there.
In this situation, then the two methods (with and without quaternion) give the same result.
This is not a proof, but $v'=qvq^*$ seems to work when
$q=\cos \theta + u \sin \theta$ with $\theta$ complex and $u$ real.
Here, * denotes the biconjugate (flip the sign of the vector), not the complex conjugate.  With real unit quaternions, $q^{-1}=q^*$.  This may not work with biquaternions in general, even though it worked in this experiment.
Edit 2: getting closer
$q = (w, x, y, z)$ is a quaternion, its biconjugate is $q^*=(w,-x,-y,-z)$.
$qq^* = w^2 + x^2 + y^2 + z^2$ is a scalar, a priori complex.
If $qq^* \ne 0$ then $q$ has an inverse $q^{-1} = q^* / (qq^*)$.
A rotation of angle $2\theta$ around a real unit axis $u=(x, y, z)$ can be represented by the following quaternion.
$$q = \cos \theta + \sin \theta \: (x, y, z)$$
$$qq^* = \cos^2 \theta + \sin^2 \theta (x^2+y^2+z^2)$$
The axis is real and unit, therefore $x^2+y^2+z^2$=1.
This leaves
$qq^* = \cos^2 \theta + \sin^2 \theta$
which equals 1 even when $\theta$ is complex.
Therefore, whenever the axis of rotation is real, even if the angle is complex, then $qq^*=1$ and $q^{-1} = q^*$.
This means that the inverse of a rotation matrix is its transpose.
The inverse is a rotation of angle $-\theta$ around the same axis.
$$q^{-1} = q^* = \cos\theta-\sin\theta \: u = \cos(-\theta)+\sin(-\theta)u$$
However, when the axis is complex, then this does not work: $qq^*\ne 1$.
Let us assume $qq^*\ne 0$.
$$q^{-1} = \frac{1}{qq^*}(\cos(-\theta) + \sin(-\theta) \:u)$$
Is there an angle $\phi$ such that $q^{-1}=\cos \phi + \sin \phi \:u$?
No, there are none: we cannot have $\cos^2+\sin^2=1$ both for $\theta$ and $\phi$ when $qq^* \ne 1$.
This means that the inverse of a rotation by a complex angle around a complex axis is NOT a rotation (Ehm, see edit 3).
Some scaling/shearing/something happened, which must be corrected.
The matrix has an inverse, the quaternion has an inverse, but the inverse is not a rotation.
So, when the inverse of a rotation is not a rotation, are we even allowed to speak about rotations in the first place?
Only the complex axes $(x,y,z)$ for which $x^2+y^2+z^2=1$ seem appropriate if we want the inverse of a rotation to be a rotation as well.
I have no idea what the shape of $x^2+y^2+z^2=1$ looks like.
Conclusion.
Rotating by a complex angle around a real axis works well.
Only a few complex axes (those for which $x^2+y^2+z^2=1$, even if the norm of said axis isn't 1 at all) are acceptable for rotations.  By acceptable, I mean that the inverse of a rotation is a rotation, which is generally not the case with complex axes.
Edit 3, much later (2015-03-29)
I wrote in Edit 2 "the inverse of a rotation around a complex axis is not a rotation".  Well, I haven't proven that actually: the only result I got was about quaternions.  Maybe rotations around complex angles make sense but biquaternions don't represent them properly.
(Btw, I solved my actual problem by avoiding trigonometry completely and avoiding the notion of rotation altogether, I'm only coming back to it out of curiosity).


text:
Q: Prevent Windows from silently disabling wallpaper slide show I generally have my wallpaper set to a slide show pulled from a folder that has around 50 images in it. However, this slide show seems to get stopped whenever I RDP into the system. There is no warning given when this happens, and it does not resume the next time that I log in locally. The only way for me to re-start it is to go back into my wallpaper settings and re-select all the pictures in the folder.
Is there a way to keep Windows from stopping the slide show during an RDP session, or at least to ensure that it will properly re-start it when I log in locally again?
I'm running Windows 7 Ultimate.

A: Open the Remote Desktop Connection app, click on "Show Options" and go to the "Experince" tab. There, the default option is "Detect connection quality automatically", set that to the manual one, which gives you the largest option of bandwidth - see if that helps. Try Satellite, or high-speed broadband...Hope this helps! It has been known that this is a bug in Windows 7, so I'm not 100% sure this will work.

A: I've encountered this same behavior on Citrix Receiver. While not a solution, I've found a fairly decent workaround that at least prevents me having to manually reselect each and every wallpaper.
First, get your wallpaper slideshow set up the way you like it. Once you've done so, in the Personalization window, click Save Theme and give it a name like "Desktop Slideshow Enabled".
Now when you connect to your RDP, open up the Personalization window and you'll find that the system has switched to "Unsaved Theme" with a static background. Just click your "Slideshow" theme to activate it; you'll most likely immediately see the wallpaper cycle to the next one. There's no OK button to click or anything, so now it's only a 4-click operation to restore your wallpaper slideshow settings, instead of the big pain it was before.


text:
Q: Accessing server through web browser using ip address redirects to localhost I'm using prestashop to set up an e-commerce website on my cloud server. I was able to successfully install it on the server and it works fine on the server locally, i.e. if I look at the website using localhost on the server. However when I try to access it from a different machine it won't work because, it gets redirected to localhost/index.php? I'm not sure what could be wrong or even where to start looking... any help would be appreciated. Only thing I could think of was the index.php file. It has following 2 lines of code and is generated by prestashop.
I apologize if this is not the correct SO website, as I wasn't sure what the issue could be related to.
Thank you.

A: When moving an CMS to another domain problems like this often occurs. Most CMS saves the domain they should run on in configuration file oder database. If there is an request for another domain they are sending an redirect (HTTP state code 302) back. I think problem here is that this one is set to localhost.
A short search on google pointed out that prestashop saves a domain name configuration in a mySQL database. Since petrashop 1.5 it should be in a table called PREFIX_shop_url. Before it was saved in PREFIX_configuration as PREFIX_shop_url. But I didn't tested on my own. You should have a look on your own and change the value in database to your new domain.
You could use mysql command line client to connect to database and change the value. If your are not so familiar with SQL you could also use a GUI like phpmyadmin.


text:
Q: Visualization software for clustering I want to cluster ~22000 points. Many clustering algorithms work better with higher quality initial guesses. What tools exist that can give me a good idea of the rough shape of the data?
I do want to be able to choose my own distance metric, so a program I can feed a list of pairwise distances to would be just fine. I would like to be able to do something like highlight a region or cluster on the display and get a list of which data points are in that area.
Free software preferred, but I do already have SAS and MATLAB.

A: Exploring clustering results in high dimensions can be done in R using the packages clusterfly and gcExplorer. Look for more here.

A: (Months later,)
a nice way to picture k-clusters and to see the effect of various k
is to build a
Minimum Spanning Tree
and look at the longest edges. For example,

Here there are 10 clusters, with 9 longest edges
855 899 942 954 1003 1005 1069 1134 1267.
For 9 clusters, collapse the cyan 855 edge; for 8, the purple 899;
and so on.

The single-link k-clustering algorithm ... is precisely Kruskal's algorithm
  ... equivalent to finding an MST and deleting the k-1 most expensive edges.

— Wayne,
Greedy Algorithms.
22000 points, 242M pairwise distances, take ~ 1 gigabyte (float32):
might fit.
To view a high-dimensional tree or graph in 2d,
see Multidimensional Scaling (also from Kruskal),
and the huge literature on dimension reduction.
However, in dim > 20 say, most distances will be near the median,
so I believe dimension reduction cannot work there.

A: I've had good experience with KNIME during one of my project. It 's an excellent solution for quick exploratory mining and graphing. On top of that it provides R and Weka modules seamless integration.

A: Also have a look at ELKI, an open-source data mining software. Wikimedia commons has a gallery with images produced with ELKI, many of which are related to cluster analysis.

A: GGobi (http://www.ggobi.org/), along with the R package rggobi, is perfectly suited to this task.
See the related presentation for examples: http://www.ggobi.org/book/2007-infovis/05-clustering.pdf

A: Take a look at Cluster 3.0.  I'm not sure if it will do all you want, but it's pretty well documented and lets you choose from a few distance metrics.  The visualization piece is through a separate program called Java TreeView (screenshot).

A: Weka is an open source program for data mining (wirtten and extensible in Java), Orange is an open source program and library for data mining and machine learning (written in Python). They both allow convenient and efficient visual exploration of multidimensional data

A: GGobi does look interesting for this. Another approach could be to treat your similarity/inverse distance matrices as network adjacency matrices and feeding that into a network analysis routine (e.g., either igraph in R or perhaps Pajek). With this approach I would experiment with cutting the cutting the node distances into a binary tie at various cutpoints.

A: DataMelt free numeric software includes Java library called JMinHep.
 Please look at the manual under the section "Data clustering". It provides a GUI to visualize multidimensional data points in X-Y, and run a number of data clustering algorithms.


text: Q: How can I find the logarithmic function of my graph? I am investigating this graph and I need to define it somehow. I know i could probably make a linear line through it but a logarithmic one would be better for the assignment. Thank you in advance


text:
Q: How i put R for pearson correlation in italic font inside an annotate function in ggplot? i used iris data for an example
`
    iris %>%
ggplot(aes(Sepal.Length,
                 fill = Species))+
  geom_density(alpha = .6,
               bw = 0.5)+
  theme_classic()+
  annotate("text",
           x = 7,
           y = c(.55, .60),
           size = 4,
           label = c(
             paste0("Mean = ", round(mean(iris$Sepal.Length),4), " cm"),
             paste0("r = ", round(cor(iris$Sepal.Length, iris$Sepal.Width),2), "")))

`

I try use force italic using Expression function, but does't work.

A: Adding parse=TRUE and using ?plotmath notation you could do:
EDIT: Getting a "," as decimal mark is a bit tricky. In the code below I use gsub to replace the "." by "*','*".
library(ggplot2)

mean <- round(mean(iris$Sepal.Length), 4)
mean <- gsub("\\.", "*','*", mean)

cor <- round(cor(iris$Sepal.Length, iris$Sepal.Width), 2)
cor <- gsub("\\.", "*','*", cor)

ggplot(iris, aes(Sepal.Length,
                 fill = Species
)) +
  geom_density(
    alpha = .6,
    bw = 0.5
  ) +
  theme_classic() +
  annotate("text",
           x = 7,
           y = c(.55, .60),
           size = 4,
           label = c(
             paste0("Mean == ", mean, "~cm"),
             paste0("italic(r) == ", cor, "")
           ),
           parse = TRUE
  )


text:
Q: Build an array from PHP and use smarty tags to display results in accordion I am trying to pull and categorize data in a jQuery accordion. I managed to get this to work at a very basic level by building a PHP array. The table 'charts_groups' contains level 1 categories, and the code (successfully) pulls all the right elements that fall under the categories by matching the element IDs with level 1 group IDs.
Now, because my population has grown, I want to add subcategories (accordion within an accordion). So I have created a third database 'chart_subgroups', and I want build the parent / child relationships in exactly the same way. So: pseudo code is as follows:
List all categories in Db1 (charts_groups), then list all subcategories in Db2 (chart_subgroups) that fall under Db1, then list all elements in Db3 ('charts') that fall under Db2 subcategories.
Could you guys let me know what's wrong with the script below? Thank you so much for your help!
This stuff should generate the array:
    $groups_result = mysql_query("SELECT * FROM `charts_groups`", $app->db());
    $chart_groups = array();

        while ($row1 = mysql_fetch_assoc($groups_result)) {

                while ($row2 = mysql_fetch_assoc($charts_result)) {
                       $subgroup_result = mysql_query("SELECT * FROM `charts_subgroups` WHERE Sub_Group = {$row1['ID']}", $app->db());
                       $subgroup_data = array();
                          while ($row3 = mysql_fetch_assoc($charts_result)) {
                                 $charts_result = mysql_query("SELECT ID, Name, Type  FROM `charts` WHERE GroupId = {$row2['ID']}", $app->db());
                                 $chart_data = array();
                                 $chart_data[] = $row3;
                                 }
                        $subgroup_data[] = $row2;
                        }
            $row2['subcategories'] = $subgroup_data;
            $row3['chart_data'] = $chart_data;
            $chart_groups[] = $row1;
        }


text:
Q: Sum children for n-array with recursive function, when input field changes old values get summed up too Im working on a Vue.js project and need to represent a custom table with rows and nested child rows. In the template, a table row is created for each node in the tree, and each node has a plus or minus icon that can be clicked to expand or collapse the node. The table row has two cells for each month (target values and actual values), as well as a sum column for both target values and actual values.
The actual Values can not be edited, they get calculated and retourned in the tree like structure.
The target Values can be edited by the user. Each month has an input field where the value can be edited. For this I'm using a @change event listener to run the reursive sum function.
Every node already has a default target value for each month of 0. When the input get's changed at first everything works fine and the values get summed up to the parent. But when the same input field is edited again. It of course takes the old values in the array of objects and sum's it up with new value. But that's of course not the expected behaviour. How can i modify my functions to get the correct values?
Here's the recursive "sumValues" function which takes the root element and performs the summing up on that element.
Two Pictures are added to get an idea of the table and the structure. The first picture with the value of 10 reflects the first change.
The second picture with the value of 5 reflects the second change in the input.
FIRST CHANGE
SECOND CHANGE
updateSumOfValuesInColumn(node, column){
      //console.log("updateTriggered")
      //console.log(column)
      this.calculateTargetValuesOfRootInColumn(node, column)
      this.calculateSumOfValuesInRow(node.data.targetValues)

    },

    calculateTargetValuesOfRootInColumn (node, column){
      //Get the root parent element of the node
      const rootElement = this.findRootElementInNode(node)

      //sum the values of the root parent element
      this.sumValues(rootElement, column)
      //console.log(rootElement)

    },

    findRootElementInNode(node){

      //find the element in the tree where the element key matches the root parent key of the node
      let foundElement = this.tree.find(element => element.key === node.data.rootKey)
      return foundElement
    },

sumValues(parent, column) {
      //console.log(column)
      if (parent.children) {

      for (const child of parent.children) {

        // at first sum the values for the child before summing up for the parent
          this.sumValues(child, column);

          const parentValue = parent.data.targetValues[column];
          parentValue.value += child.data.targetValues[column].value
      }
    }
    },

Data Structure Example for the tree and eg for one object:
    // this.tree in component
const tree =
[
    {key: "GEN-0057",
    data: {
        ame: "Kosten",
        level: 4,
        parentId:"" ,
        actualValues: [
                    {month: 1, value: -1448.85},
                    {month: 2, value: -1394.3500000000001},
                    {month: 3, value: -1104.78},
                    {month: 4, value: -1709.77},
                    {month: 5, value: -1427.7600000000002},
                    {month: 6, value: -1753.13},
                    {month: 7, value: -1633.59},
                    {month: 8, value: -1562.26},
                    {month: 9, value: -1377.7},
                    {month: 10, value: -1589.69},
                    {month: 11, value: -2057.35},
                    {month: 12, value: -1399.89}
                    ],
        targetValues: [
                    {month: 1, value: 0},
                    {month: 2, value: 0},
                    {month: 3, value: 0},
                    {month: 4, value: 0},
                    {month: 5, value: 0},
                    {month: 6, value: 0},
                    {month: 7, value: 0},
                    {month: 8, value: 0},
                    {month: 9, value: 0},
                    {month: 10, value: 0},
                    {month: 11, value: 0},
                    {month: 12, value: 0},
                ]
    },
    children: [
        {object}, {object}, ...
    ]}

]

I expected the values to be 5 after the second change. But I can't figure out how to solve this problem.


text:
Q: Making a message in Android Studio under a condition i would like to make a message under a condition if the pronounciation is correct according to google assistant,
if my speaking is correct then there will be a message sayin' that my pronounciation is correct

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = etText.getText().toString();
                textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
            }
        });

        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent mic_google = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                mic_google.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                mic_google.putExtra(RecognizerIntent.EXTRA_LANGUAGE, ID_BahasaIndonesia);

                try {
                    startActivityForResult(mic_google, RESULT_SPEECH);
                    tvText.setText("");
                }catch (ActivityNotFoundException e){
                    Toast.makeText(getApplicationContext(), "Maaf, Device Kamu Tidak Support Speech To Text", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case RESULT_SPEECH:
                if (resultCode == RESULT_OK && data != null){
                    ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    tvText.setText(text.get(0));
                }
                break;
        }
    }
}

here's my design now


text:
Q: Trying to mirror my website with wget, but nofollow attribute is found , and I cannot download anything more than index.html I am running a wordpress site on a Ubuntu 20.04 based LEMP server.
I have the pagespeed plugin enabled, and in order to force it to cache my website, I am using wget from a different box to mirror the site. However, when using wget from a 2nd box, It stops downloading at the first page (index.html), with the error

nofollow attribute found in /tmp/ramdisk/www.example.com/index.html. Will
not follow any links on this page
Below is the wget command I am using and the return results:

wget -m -p -E -k -P /tmp/ramdisk/ https://www.example.com
--2022-05-17 16:41:40--  https://www.example.com/
Resolving www.example.com (www.example.com)... 1**.2*.1**.*
Connecting to www.example.com (www.example.com)|1**.2*.1**.*|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: '/tmp/ramdisk/www.example.com/index.html'

www.example.com/index.html                                     [   <=>                                                                                ] 130.71K   210KB/s    in 0.6s

Last-modified header missing -- time-stamps turned off.
2022-05-17 16:41:42 (210 KB/s) - '/tmp/ramdisk/www.example.com/index.html' saved [133848]

nofollow attribute found in /tmp/ramdisk/www.example.com/index.html. Will not follow any links on this page
FINISHED --2022-05-17 16:41:42--
Total wall clock time: 2.0s
Downloaded: 1 files, 131K in 0.6s (210 KB/s)
Converting links in /tmp/ramdisk/www.example.com/index.html... 135.
42-93
Converted links in 1 files in 0.004 seconds.

How can I go about finding the nofollow attributes and removing them so wget will fully download my website?

A: As documented here you can tell wget to ignore the no-follow attribute by adding the parameter -e robots=off

A: I figured this out.
I had to log into my wordpress installation via the web interface, and go to Settings>Reading>Search engine visibility, then on that page I had to uncheck the

Discourage search engines from indexing this site It is up to search
engines to honor this request.

option. After I unchecked that, I could successfully mirror my site using the wget command wget -m -p -E -k -P /tmp/ramdisk/ https://www.example.com.
See the screenshot below for more info.


text:
Q: Visibility of new attribute created by Magento upgrade script I am trying to add a custom attribute programmatically within a module upgrade script. The script runs fine and creates the new attribute (i.e. it appears in the Magento admin list under Catalog->Attributes->Manage Attributes once the script has run).
At first I was using the class Mage_Eav_Model_Entity_Setup (as recommended here and neither the 'visible' nor 'apply_to' fields were being set as intended ('visible' was always false and 'apply-to' remained as "All product types" rather than using the list supplied in the script).
Then I found this, which explained that I should use Mage_Catalog_Model_Resource_Setup instead, and that has fixed the problem with 'apply_to'.
But still I can't get the attribute's 'visible' attribute to set to true. If anyone has any ideas why the 'visible' attribute is still not being set as it should I would be very grateful to hear, thanks!
Here is my upgrade script code:
$updater = $this;      // $this is class Mage_Eav_Model_Entity_Setup
$updater->startSetup();
$updater->addAttribute('catalog_product', 'my_test_attribute', array(
    'label'             => 'My Test Attribute',
    'type'              => 'int',
    'input'             => 'select',
    'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'apply_to'          => 'simple,configurable',
    'group'             => 'General',
    'visible'           => true,
    'required'          => true,
    'user_defined'      => true,
));
$updater->endSetup();

I am running Magento 1.7.0.1 in WAMP on Windows 7.

A: I have solved this now - what it needed was the "visible_on_front" attribute to be set too, rather than just the "visible". i.e. I added this line to the above script and it now works:
'visible_on_front'  => true,

A: This attribute isn't Boolean, it's integer. So you have set up 1 = true 0 = false;


text:
Q: How to add alt attributes to thumbnails of lazy loaded youtube videos Can someone give me a hand here to where can I add alt attributes to YouTube videos thumbnails, I'm using lazy loading technique to embed YouTube videos.
Google lighthouse keeps flagging my embedded videos for "Image elements do not have [alt] attributes"
Here's the JavaScript:

Here is the CSS:

And here is the HTML:

I don't have big skills in this field, I'm just running a blog and I'm trying to improve it, Thank you.
I tried to add "alt attributes" at the end of this line in the javascript and it worked in lighthouse, but it removed the thumbnails of the videos in my website
var source = "https://i.ytimg.com/vi_webp/"+ youtube[i].dataset.embed +"/hqdefault.webp ";


text:
Q: Dramatically increased Read Ops in Cassandra I am playing with Cassandra on out testing environment. I have 3 nodes of C* (version 3.11) in cluster and 3 column families with replication factor 2 and SizeTieredCompactionStrategy. Each node is deployed to AWS r4.large instance with two EBS gp2 disks - 100GB for commit log and 300GB for data.
2 column families are write-only, our applications write quite a lot to these tables (about 800 - 1000 inserts per second in total) and never read them. Third column family is a counter-table, which is used like 'Increment and Get' pattern: about 200 increments and gets per second. Each counter is updated not that frequently - about 30 times during the whole test.
Everything worked fine for a 5 days, but then read ops/sec on one of nodes stared to grow to >1000 iops, to the disk iops limit:

When it reached the limit, response time of selects from counter-table jumped from 2-digit milliseconds to seconds and read io started to grow on the second node.
Here is an output of nodetool cfstats:
Keyspace : geo
Read Count: 51744711
Read Latency: 12.840126352082631 ms.
Write Count: 201887146
Write Latency: 0.02199966441647553 ms.
Pending Flushes: 0
    Table: gpm
    SSTable count: 5
    Space used (live): 5127907030
    Space used (total): 5127907030
    Space used by snapshots (total): 0
    Off heap memory used (total): 102252166
    SSTable Compression Ratio: 0.41318162863841235
    Number of keys (estimate): 32583794
    Memtable cell count: 51001
    Memtable data size: 3072328
    Memtable off heap memory used: 0
    Memtable switch count: 176
    Local read count: 51530318
    Local read latency: NaN ms
    Local write count: 97595727
    Local write latency: NaN ms
    Pending flushes: 0
    Percent repaired: 0.0
    Bloom filter false positives: 0
    Bloom filter false ratio: 0.00000
    Bloom filter space used: 80436992
    Bloom filter off heap memory used: 80436952
    Index summary off heap memory used: 21046326
    Compression metadata off heap memory used: 768888
    Compacted partition minimum bytes: 87
    Compacted partition maximum bytes: 149
    Compacted partition mean bytes: 112
    Average live cells per slice (last five minutes): NaN
    Maximum live cells per slice (last five minutes): 0
    Average tombstones per slice (last five minutes): NaN
    Maximum tombstones per slice (last five minutes): 0
    Dropped Mutations: 0

I can't find any explanation why is it happening. I performed the same test twice (starting from empty database) and both times it failed identically after 5-6 days from the beginning.
Here is tracing of typical query which selects counter (the only type of selects performed during test):
                                                                                Execute CQL3 query | 2017-08-28 16:06:44.110000 | 172.31.16.220 |              0 | 172.31.16.220
                                            Parsing select * from geo.gpm where usr = '57469' and lat = 55.617 and lon = 37.509; [Native-Transport-Requests-1] | 2017-08-28 16:06:44.110000 | 172.31.16.220 |            187 | 172.31.16.220
                                                                                Preparing statement [Native-Transport-Requests-1] | 2017-08-28 16:06:44.110000 | 172.31.16.220 |            411 | 172.31.16.220
                                                                                reading data from /172.31.32.220 [Native-Transport-Requests-1] | 2017-08-28 16:06:44.110000 | 172.31.16.220 |            736 | 172.31.16.220
   Sending READ message to cassandra-test-skywalker.aws.local/172.31.32.220 [MessagingService-Outgoing-cassandra-test-skywalker.aws.local/172.31.32.220-Small] | 2017-08-28 16:06:44.111000 | 172.31.16.220 |           1184 | 172.31.16.220
                                                                          READ message received from /172.31.16.220 [MessagingService-Incoming-/172.31.16.220] | 2017-08-28 16:06:44.111000 | 172.31.32.220 |             35 | 172.31.16.220
                                                                                Executing single-partition query on gpm [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5675 | 172.31.16.220
                                                                                Acquiring sstable references [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5745 | 172.31.16.220
                                                                       Skipped 0/5 non-slice-intersecting sstables, included 0 due to tombstones [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5812 | 172.31.16.220
                                                                                Key cache hit for sstable 85 [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5906 | 172.31.16.220
                                                                                Key cache hit for sstable 170 [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5963 | 172.31.16.220
                                                                                Key cache hit for sstable 191 [ReadStage-3] | 2017-08-28 16:06:44.117000 | 172.31.32.220 |           5996 | 172.31.16.220
                                                                                Key cache hit for sstable 212 [ReadStage-3] | 2017-08-28 16:06:44.117001 | 172.31.32.220 |           6028 | 172.31.16.220
                                                                                Bloom filter allows skipping sstable 217 [ReadStage-3] | 2017-08-28 16:06:44.118000 | 172.31.32.220 |           6069 | 172.31.16.220
                                                                                Merged data from memtables and 4 sstables [ReadStage-3] | 2017-08-28 16:06:44.118000 | 172.31.32.220 |           6151 | 172.31.16.220
                                                                                Read 1 live and 0 tombstone cells [ReadStage-3] | 2017-08-28 16:06:44.118000 | 172.31.32.220 |           6203 | 172.31.16.220
                                                                                Enqueuing response to /172.31.16.220 [ReadStage-3] | 2017-08-28 16:06:44.118001 | 172.31.32.220 |           6228 | 172.31.16.220
                                                              REQUEST_RESPONSE message received from /172.31.32.220 [MessagingService-Incoming-/172.31.32.220] | 2017-08-28 16:06:44.119000 | 172.31.16.220 |           9891 | 172.31.16.220
Sending REQUEST_RESPONSE message to cassandra-test-kenobi.aws.local/172.31.16.220 [MessagingService-Outgoing-cassandra-test-kenobi.aws.local/172.31.16.220-Small] | 2017-08-28 16:06:44.119000 | 172.31.32.220 |           7466 | 172.31.16.220
                                                                                Processing response from /172.31.32.220 [RequestResponseStage-3] | 2017-08-28 16:06:44.120000 | 172.31.16.220 |          10013 | 172.31.16.220
                                                                                Request complete | 2017-08-28 16:06:44.124753 | 172.31.16.220 |          14753 | 172.31.16.220

Any help will be appreciated. Are there any profiling tools which can help me to realise what is wrong?


text:
Q: Determining the size of deltas in TFS Our TFSVersionControl database has grown significantly in the past couple years, and is edging on 80GB.  Unfortunately, we're in an environment where every gig of data storage is internally charged at a high rate, so there's lots of focus on keeping storage growth to a minimum.
I believe the majority of growth is happening because we chose to store binary files in our repository.  This is something we will be remedying in the medium term.
In the short-term, there are a few places where we do not need to keep a history of our binaries.  Particularly in our mainline branch and our development branch, so we're looking into doing a TF Destroy on these binaries and recreating them as part of the upcoming release.
What I'd like to know is:  Is there any way to run a query against the TFSVersionControl database to understand which files are storing deltas that are over a given size?
Ideally, what I'd like to know is for a given path (item spec), for each file, the base size, and the total size of the deltas.

A: I think this page may be what you're looking for.

A: Just like asking someone else will often drive you to find your own answer, I did some additional digging, and came up with this:
select ver.VersionFrom, ver.Command, ver.ChildItem, tf.*, ct.CreationDate, ct.OffsetFrom, ct.OffsetTo, DataLength(ct.Content) as Size
from tbl_version ver with (nolock)
inner join tbl_file tf with (nolock) on tf.FileId = ver.FileId
inner join tbl_content ct with (nolock) on ct.FileId = tf.fileid
where parentpath = '$\ProjectName\Branch\Folder\'
ORDER BY ver.ChildItem, Ver.VersionFrom

--where fullpath = '$\ProjectName\Branch\Folder\FileName.cs\'

The query as written will iterate through all files in a particular path and will retrieve a record per checkin.  The calculated Size field will show you the size in bytes of the delta.  I'm not sure if this is compressed size or "actual" size.
The commented "where" statement will show you the same for an indvidual file.
Note that the typical forward slashes ("/") are stored in the database as backslashes ("\"), and there is always a trailing backslash at the end.
If you pull this data into Excel, you can quickly create a pivot table on it to calculate the sizes (or you can add them up manually).


text:
Q: deploying web app to external glassfish4 instance with maven cargo plugin I'm trying to deploy an app using cargo, this is the config for it:
<plugin>
            <groupId>org.codehaus.cargo</groupId>
            <artifactId>cargo-maven2-plugin</artifactId>
            <version>1.4.9</version>
            <configuration>
                <wait>true</wait>
                <container>
                    <containerId>glassfish4x</containerId>
                    <type>remote</type>
                </container>
                <configuration>
                    <type>runtime</type>
                    <properties>
                        <cargo.hostname>remote-IP-address</cargo.hostname>
                        <cargo.remote.username>admin</cargo.remote.username>
                        <cargo.remote.password>######</cargo.remote.password>
                        <cargo.glassfish.admin.port>4848</cargo.glassfish.admin.port>
                        <cargo.glassfish.domain.name>domain1</cargo.glassfish.domain.name>
                    </properties>
                </configuration>
                    <deployables>
                        <deployable>
                            <groupId>${project.groupId}</groupId>
                            <artifactId>${project.artifactId}</artifactId>
                            <type>war</type>
                            <properties>
                                <context>/app</context>
                            </properties>
                        </deployable>
                    </deployables>

            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.glassfish.deployment</groupId>
                    <artifactId>deployment-client</artifactId>
                    <version>3.2-b06</version>
                </dependency>
            </dependencies>
        </plugin>

Unfortunately, the server throws this exception after after about 30s:
    [2014-09-25T11:39:47.598+0200] [glassfish 4.1] [SEVERE] [NCLS-CORE-00003] [javax.enterprise.system.core] [tid: _ThreadID=339 _ThreadName=admin-listener(44)] [timeMillis: 1411637987598] [levelValue: 1000] [[
  Exception while running a command
java.io.IOException: java.util.concurrent.TimeoutException
        at org.glassfish.admin.payload.PayloadFilesManager.extractFile(PayloadFilesManager.java:584)
        at org.glassfish.admin.payload.PayloadFilesManager.access$600(PayloadFilesManager.java:93)
        at org.glassfish.admin.payload.PayloadFilesManager$DataRequestType$1.processPart(PayloadFilesManager.java:749)
        at org.glassfish.admin.payload.PayloadFilesManager.processPartsExtended(PayloadFilesManager.java:618)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$UploadedFilesManager.extractFiles(CommandRunnerImpl.java:2074)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$UploadedFilesManager.<init>(CommandRunnerImpl.java:2046)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$UploadedFilesManager.<init>(CommandRunnerImpl.java:2025)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1155)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
        at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
        at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
        at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.portunif.PUFilter.handleRead(PUFilter.java:231)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.portunif.PUFilter.handleRead(PUFilter.java:231)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: java.util.concurrent.TimeoutException
        at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:90)
        at org.glassfish.grizzly.filterchain.TransportFilter.handleRead(TransportFilter.java:173)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.portunif.BackChannelFilter.handleRead(BackChannelFilter.java:80)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.portunif.BackChannelFilter.handleRead(BackChannelFilter.java:80)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.http.io.InputBuffer.blockingRead(InputBuffer.java:1119)
        at org.glassfish.grizzly.http.server.io.ServerInputBuffer.blockingRead(ServerInputBuffer.java:95)
        at org.glassfish.grizzly.http.io.InputBuffer.fill(InputBuffer.java:1143)
        at org.glassfish.grizzly.http.io.InputBuffer.read(InputBuffer.java:353)
        at org.glassfish.grizzly.http.server.NIOInputStreamImpl.read(NIOInputStreamImpl.java:83)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
        at java.io.FilterInputStream.read(FilterInputStream.java:133)
        at java.io.PushbackInputStream.read(PushbackInputStream.java:186)
        at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:238)
        at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
        at java.util.zip.ZipInputStream.read(ZipInputStream.java:193)
        at java.io.FilterInputStream.read(FilterInputStream.java:107)
        at org.glassfish.admin.payload.ZipPayloadImpl$Inbound$ZipEntryInputStream.read(ZipPayloadImpl.java:220)
        at org.glassfish.admin.payload.PayloadFilesManager.extractFile(PayloadFilesManager.java:549)
        ... 46 more
Caused by: java.util.concurrent.TimeoutException
        at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:126)
        at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:75)
        at org.glassfish.grizzly.AbstractReader.read(AbstractReader.java:72)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:77)
        ... 80 more

when I'm trying to do the same localy(changing the host name), it works.The only difference between those two instances is the local is 4.0 and the remote is 4.1.
Can anyone tell me what am I doing wrong? I've tried also with setting the protocol to https by using the cargo.protocol property.
Best Regards,
Marek
I forgot to post the maven command I execute, here it is:
mvn package cargo:deploy
thanx in advance!

A: The bug is already tracked in JIRA as:
https://java.net/jira/browse/GLASSFISH-21180
https://java.net/jira/browse/GLASSFISH-21196
There exists a proposed solution now from oleksiys. Try replacing Grizzly with patched version from the following thread.
https://java.net/jira/browse/GRIZZLY-1713
I'm going to try it soon myself, then I'll confirm it here.
EDIT: Solution confirmed according to our own tests and also by other user in thread Cargo remote deployment Glassfish 4.1 Fails GlassFish uses 100% CPU
Direct download of patched grizzly from Oleksiy Stashok: https://dl.dropboxusercontent.com/u/7319744/glassfish-4.1/nucleus-grizzly-all.jar
Also Grizzly 2.3.16 and later fixes the bug.


text:
Q: Como não escrever o cabeçalho em um CSV toda vez que atualizar o arquivo Quando crio um arquivo CSV com cabeçalho, todas as vezes que tento inserir novos itens o cabeçalho se repete.
# Escrevendo o arquivo
with open('Gerador.csv', 'a', newline='', encoding='utf-8') as gravar:
    fieldnames = ['Instituição', 'Senha']
    escrever = csv.DictWriter(gravar, fieldnames=fieldnames)
    escrever.writeheader()

    nome = input('Instituição: ')
    senha = input('Senha: ')

    escrever.writerow({'Instituição': nome, 'Senha': senha})

A: Uma ideia é verificar se o arquivo já existia (antes de abri-lo, já que ao abrir com a opção a, ele será criado). Aí você só escreve o header se ele não existia:
nome_arquivo = 'Gerador.csv'

# verifica se o arquivo existe

# Python >= 3.4
from pathlib import Path
arquivo_ja_existia = Path(nome_arquivo).is_file()

# Ou, para Python < 3.4
import os.path
arquivo_ja_existia = os.path.isfile(nome_arquivo)

import csv
# Escrevendo o arquivo
with open(nome_arquivo, 'a', newline='', encoding='utf-8') as gravar:
    fieldnames = ['Instituição', 'Senha']
    escrever = csv.DictWriter(gravar, fieldnames=fieldnames)
    if not arquivo_ja_existia: # só escreve o header se o arquivo não existia antes
        escrever.writeheader()

    nome = input('Instituição: ')
    senha = input('Senha: ')
    escrever.writerow({'Instituição': nome, 'Senha': senha})

Para verificar se o arquivo já existe, coloquei duas opções:

*

*para Python >= 3.4 pode ser usado o módulo pathlib

*para versões anteriores à 3.4 pode ser usado o módulo os.path
A seguir, você só escreve o header se o arquivo não existia.

Outra opção é verificar a posição do arquivo em que estamos. Se o arquivo for novo, ele estará na posição zero, e somente neste caso eu escrevo o header:
import csv
# Escrevendo o arquivo
with open(nome_arquivo, 'a', newline='', encoding='utf-8') as gravar:
    fieldnames = ['Instituição', 'Senha']
    escrever = csv.DictWriter(gravar, fieldnames=fieldnames)
    if gravar.tell() == 0: # só escreve o header se estiver no início do arquivo
        escrever.writeheader()

    nome = input('Instituição: ')
    senha = input('Senha: ')
    escrever.writerow({'Instituição': nome, 'Senha': senha})


text:
Q: Concatenating C strings     #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    int main(void){
    char pos[4][4];
    char loc[4];
    int i;

    for(i=0;i<4;i++){
        pos[i][0]=4;
        pos[i][1]=4;
        pos[i][2]=4;
        pos[i][3]=4;
    } loc[i]=" ";
    strcat(loc[i],pos[i]);
}

I am trying to save all the contents of pos[i] in a concatenated
string. I am not sure how to go about this.  I would appreciate any tips.

A: Adapted code:
#include <stdio.h>
#include <string.h>

int main(void) {
    char pos[4][4];
    char *loc;
    int i;

    for (i = 0; i < 4; i++) {
        pos[i][0] = 'a' + i;
        pos[i][1] = 'a' + i;
        pos[i][2] = 'a' + i;
        pos[i][3] = 'a' + i;
    };

    loc = (char *) pos;
    for (i = 0; i != sizeof(pos); i++) {
        fputc(loc[i], stdout);
    }
    fputc('\n', stdout);
    /* output: aaaabbbbccccdddd */

    return 0;
}

pos is already the concatenation you are looking for.
pos is the address of a memory chunk of contiguous characters
and could have been declared and initialized this way:
char pos[4][4] = {
    { 'a', 'a', 'a', 'a' }
  , { 'b', 'b', 'b', 'b' }
  , { 'c', 'c', 'c', 'c' }
  , { 'd', 'd', 'd', 'd' }
};

or this way (with a likely warning from the compiler):
char pos[4][4] = {
    'a', 'a', 'a', 'a'
  , 'b', 'b', 'b', 'b'
  , 'c', 'c', 'c', 'c'
  , 'd', 'd', 'd', 'd'
};

The two dimensions are just a view over pos, it can be flattened: (char *) pos.
If you need a flattened copy:
char cpy[sizeof(pos)];
memcpy(cpy, pos, sizeof(pos));


text:
Q: Kill only a specific Command Prompt Process Remotely with PowerShell I am trying to write a script to remote kill a specific command prompt process.
If I locally run get-process I can see that the CMD.exe process can be narrowed down by what is set in the field "MainWindowTitle"
If I get use Get-Process -computer name or get CIMInstance  the field "MainTitleWindow" comes back as blank.
$ses = New-CimSession -ComputerName $computer -Credential $cred
$process = Get-CimInstance -ClassName CIM_process -CimSession $ses -filter "name = 'cmd.exe'"
$process | Select-Object name,MainWindowTitle
Remove-CimSession -CimSession $ses

name    MainWindowTitle
----    ---------------
cmd.exe

A: Extracted from MSDN:

A process has a main window associated with it only if the process has
  a graphical interface. If the associated process does not have a main
  window (so that MainWindowHandle is zero), MainWindowTitle is an empty
  string ("").

More info here.
I tried to compare with other processes but the result is the same...

A: You could parse the output of the tasklist command. Like this:
$cmds = tasklist /v |
    Where-Object {$_ -like "cmd.exe*"} |
    ForEach-Object {
        New-Object -TypeName PSObject -Prop @{"ID"=[int]$_.Substring(30,5); `
                                              "Title"=$_.Substring(157)}
    }

$cmds

A: $Process = Get-CimInstance CIM_Process -CimSession $Ses | Where-Object{ $ProcessNames -contains $_.Name }
using this you can also get the ProcessID and ParentProcessID.
you can then use the similar commands to then find the CMD process that uses the ParentProcessID of your main script.
You must close both the main process of the script and the command prompt as well or else the script will keep running.


text:
Q: Show that $f_n(x)=\frac{1-(x/b)^n}{1+(a/x)^n}$ with $0So, I have to show that  $f_n(x)=\dfrac{1-(x/b)^n}{1+(a/x)^n}$ with $0<a<b$ and $x \in [a,b]$ is pointwise convergent, but not uniformly convergent. The pointwise convergence is pretty straight forward, I get $f_n(x) \to f(x)$ with:
$f(x) = \left\{ \begin{array}{llllllr}
1/2 &,& x=a \\
1   &,& x \in (a,b) \\
0   &,& x=b
\end{array} \right.$
And intuitively, it's pretty obvious, that function sequence is not uniformly convergent, but I'm not quite sure how to show it. I'm thinking, that I have to actually show it by definition, that is:
$\exists \epsilon>0 \forall N \in \mathbb{N} \exists n \geq N \exists x \in [a,b]: n \geq N \Rightarrow \sup\{|f_n(x)-f(x)|\} \geq \epsilon$
But I am quite stuck, to be honest. Anyone got a hint that might get me going?
Much appreciated.
EDIT: Actually I just realized, that I can just go by the fact, that if a sequence of continuous functions converges uniformly, it will converge to a continuous function - since it does not, the convergence is not uniform. That should do, right?

A: A sequence of continuous functions converging uniformly will converge to a continuous function. So assume we had uniform convergence...


text:
Q: Graph API Teams Get chatMessageHostedContent not able to get existing images I'm trying to migrate teams channel messages to another channel (or make backup of it), but I'm unable to get images embedded within the message.
I have successfully listed messages, parsed their body.content and extracted valid URI for retrieval of the image.
As stated in official documentation for GET requests finishing with ".../$value" Graph API should return a binary image file, but I'm getting a 200 OK with payload JSON containing only key-value pair of the resource ID I have sent within a request instead of the image. No error returned.
Any idea what might be wrong?

A: Mea culpa!
I have been using PowerShell and did not properly escape $ (dollar sign) in front of the ".../$value". Using ' instead of " resolved the issue, and now I'm receiving the image files.


text:
Q: Getting blank lemmatization using xx_use_lg model with Spacy Python I got a list of words using for element in text: print(element).
But when I try to use lemma_ like this (for element in text: print(element.lemma_)) it returns me blank list.
I can't understand why this append. But it probably comes because I'm using xx_use_lg model from Spacy. And so I can't do anything about it.
But if you have some solution to this problem thank you in advance !
I tried changing the input as String and also as List but still getting same blank list returning.
I tried before doing this work with another model than xx_.._.. and it worked. But I need absolutely to use xx_use_lg.


text:
Q: Why Am I not getting add a new key and value to an existence object? I Have the follow object which iterating it I can add a new key and value, but when I have to make a database search and take each result and add as a new key + value does not work, the Eslint point a Assignment to property of function parameter 'object'.eslintno-param-reassign, bellow is the example without make a database search.

const obj = {
  Cod: 43453,
  Informations: [
    {
      codPay: 802112,
      value: 80
    },
    {
      codPay: 802113,
      value: 80
    },
    {
      codPay: 802114,
      value: 80
    },
    {
      codPay: 802115,
      value: 80
    },
    {
      codPay: 802116,
      value: 80
    },
    {
      codPay: 802117,
      value: 80
    },
    {
      codPay: 802118,
      value: 80
    },
    {
      codPay: 802119,
      value: 80
    }
  ],
  status: 'OK'
}

obj["Informations"].forEach((f,index) => {
    f.more_info = index
})

console.log(obj)

By making database search:
obj["Informations"].forEach(asyn(f) => {
    const result = db.any("Select info From table where cod $1",f.codPay")
    f.more_info = result[0].info
})

by openning this db.any  the values is coming correct but I cannot add new key, where Am I missing?

A: The no-param-reassign rule is there to warn you that mutating the argument may cause undesirable effects elsewhere in the code. For example, there may be some other part of the code that relies on the assumption that each Informations sub-object contains only codPay and value properties, and nothing else (no more_info property). If such code existed, your addition of a more_info property could cause that code to stop working.
A good alternative is to use .map, to create entirely new objects instead of mutating the original ones. That will fix the linter warning.
Another issue is that it looks like db.any returns a Promise, in which case you should wait for it to resolve first. To do this in a loop, use Promise.all to wait for all Promises in an array to resolve.
const informationsWithMoreInfo = await Promise.all(
    obj.Informations.map(
        obj => db.any("Select info From table where cod $1", obj.codPay)
            .then(result => ({ ...obj, more_info: result[0].info }))
    )
);
// do stuff with informationsWithMoreInfo

For the await to work, make sure the containing function is async - either that, or call .then on the Promise.


text:
Q: Why Induction always does not work with Big-O? I am currently watching ocw video courses on Algorithms and in second lecture i stuck at a point where professor proves the following statement by induction:-
n=O(1)
proof:-

For base case
1=O(1)
suppose n-1 = O(1)
=> 1+(n-1)=O(1)+O(1)
=> n=O(1).
hence it is proved.

But the professor told that we cannot induct over Big-O and the above proof is not true but why?

A: You can induct over Big-O, but the given induction process is not correct when n is a variable instead of a constant.
When you write 1 = O(1), the interpretation would be
if f_1(n) = 1 for all n then f_1(n) = O(1)

which is correct.
Now if we define f_a(n) = a for all n, then by induction we can prove that f_a(n) = O(1) for all a, which is also correct.
But if n is not a constant but a variable you can't get n = O(1) as a result of your induction since there is no k such that f_k(n) = n for all n.

A: Mathematical induction is a tool to prove statements parametrized by integers. It cannot be applied in this case because the statement you are studying changes half way through: you take a constant 1 as the base case, and then assume a statement about the function f(n)=n-1.
The proof is correct in showing that any constant n is in O(1), though.

A: Basically in math induction is a tool, to get from a well known position a well controllable step further. This don't have to be a step like n → n+1 or n → 2⋅n, but most likely it is. In most cases the problem will be, that the well controllable step is of constant size, so in Big-O it just get lost.
But in some cases you can use the Big-O just for simplification while calculating the complexity, like

(n+a+1)(n-2⋅b)(n2-3) = n4+O(n3)                (for constants a and b)

There are also cases, where you can see the complexity in the induction step.
Example:
Find the complexity of f(n) = f(n-1) + f(n-2) with n ≥ 2 and f(0) = f(1) = 1.
The step n → n+1 yields

2⋅f(n-1) ≤ f(n+1) ≤ 2⋅f(n)

so basically the size doubles for a +1. you need n +1's to sum up to n, that yields the first value doubles about n times. The beginning (f(1)) is in O(1) so 2n ⋅ O(1) is in O(2n).
Finally there are cases in which you can proof the complexity by induction.
Example:
Find the complexity of n!.
Proof: 1 is in O(1). Suppose (n-1)! is in O(1). Then

n! = n⋅(n-1)! = n * O(1) = O(n).

Damn, n! can't be in O(1) because (n+1)! had to be also in O(1), but it isn't. Next try:
Suppose (n-1)! is in O(nk).

n! = n⋅(n-1)! = n ⋅ O(nk) = O(nk+1)

Damn, failed again. If n! is in O(nk), (n+1)! is supposed to be in

O((n+1)k) = O(nk + k⋅nk-1 + ...[smaller monomials]) = O(nk)

But for k = n this would work, since for n! in O(nn), (n+1)! is supposed to be in O((n+1)n+1) and in fact, n! is in O(nn), but it is not a tight upper bound. To proof a better complexity you have to use better methods than induction.
So this is more an example to disproof a complexity by using induction.
In general I would not say, that there is no complexity that can be proven by induction, but in most cases exits better ways to proof it.


text:
Q: replacing a single word in a string i have a null terminated and dynamically allocated string called 'text_buff' , which contain's the word "bar". i want to replace this word with another word of my choice, that can be longer or shorter than the original one.
here's my code up until now, i can't seem to figure out what am i doing wrong.
        char * toswap = "newword";
        int diff = strlen(toswap)-strlen("bar");
        int wlocation = strstr(text_buff,"bar")-text_buff;
        if (diff > 0) {
            text_buff = realloc(text_buff,strlen(text_buff)+diff);
            for (i=strlen(text_buff) ; i > wlocation+strlen("bar") -1; --i ){
                text_buff[i+diff] = text_buff[i];
            }
            for (i = 0 ; i < strlen("bar")+1; ++i){
                text_buff[wlocation+i] = toswap[i];

            }
        } else if (diff < 0){
                for (i=wlocation+diff ; i <strlen(text_buff);++i ){
                    text_buff[i]=text_buff[i-diff];
                }
                for (i = 0 ; i < strlen("bar")+1; ++i){
                    text_buff[wlocation+i] = toswap[i];
                }
}

A: You have the wrong loop condition when inserting the new word:
        for (i = 0 ; i < strlen("bar")+1; ++i){
            text_buff[wlocation+i] = toswap[i];
        }

It should be:
        for (i = 0 ; i < strlen(toswap); ++i){
            text_buff[wlocation+i] = toswap[i];
        }

Other than that you are missing error handling. If this is a school assignment you can probably manage without error handling, though.

A: You forget 1 character for the final '\0';
text_buff = realloc(text_buff,strlen(text_buff)+diff);

It should be
text_buff = realloc(text_buff,strlen(text_buff)+diff + 1);


text:
Q: Sending multiple emails in YII using YiiMail extension I am using YiiMail Extension to send mails.
I have my default contact.php file as my view. I am able to send mails for individuals but multiple emails are not allowed here.
mycontroller-
public function actionContact()
{
    $model=new ContactForm;
    if(isset($_POST['ContactForm']))
    {
    $message = new YiiMailMessage;
    $message->Body=$_POST['body'];
    $message->subject = $_POST['subject']
    $message->addTo($_POST['email']);
    $message->from = "frommail@gmail.com";
    if(Yii::app()->mail->send($message) )
        echo 'mail sent';
    else
        echo 'error while sending email';
    }
}

I have tried the following too-
foreach ($model as $value)
{
            $message->addTo($model[$value]);
}

It does not accept multiple email id's. How can this be resolved?

A: You can pass multiple recipients mail ids as array
$recipients = array('test1@example.com','test2@example.com','test3@example.com');
$message->addTo('test1@example.com');
foreach($recipients as $email) {
  $mail->AddBCC($email); // if you want more than one email
}

A: I have checked code in Yii Mailer. They haven't given such facility. If you like to achieve then you need to extend Yii Mail. It's ultimately useless because looping in your new extended class OR looping in your controller are same.
Regards...


text:
Q: How to detect if no data ingested in any IoTHub Device using Stream analytics? Basically I have multiple devices in IoTHub with 30 partition. Now, I want to detect if there is no data being ingested to any devices after 10 mins using Stream Analytics. Once detected, I want to select what device is it and send that information to Azure function for Alert.
The query is a bit tricky given that I'm new with stream analytics. Here is what I came up so far but it seems the out is not what I expected.
SELECT
  t1.[IoTHub].[ConnectionDeviceId] as DeviceId
INTO
  [NoDataAlertFunctionOutput]
FROM
  [iot-hub-data-flow] t1 TIMESTAMP BY Timestamp
LEFT OUTER JOIN [iot-hub-data-flow] t2 TIMESTAMP BY Timestamp
  ON
  t1.[IoTHub].[ConnectionDeviceId]=t2.[IoTHub].[ConnectionDeviceId]
AND
  DATEDIFF(minute,t1,t2) BETWEEN 1 and 10
  WHERE t2.[IoTHub].[ConnectionDeviceId] IS NULL

I will greatly appreciate any suggestion or comment.
Here are the references I trying to follow:

*

*Stream Analytics Common Query

*Process real-time IoT Data
On the other hand, is there a built-in functionality in IoTHub to detect if no data ingested at certain time period?

A: From the ASA perspective, I would try this pattern instead. I'm not 100% sure that it checks all your requirements, but I think it's an interesting direction to explore.

*

*Using a hopping window, every minute we scan the last 20

*First we go find the last event in that window

*Then we check if it's been more than 10 minutes if it was sent

WITH CTE AS (
    SELECT
        System.Timestamp() AS Window_end,
        DATEADD(minute,-10,System.Timestamp()) AS Window_10,
        TopOne() OVER (ORDER BY Timestamp DESC) AS Last_event
    FROM
        [iot-hub-data-flow] t TIMESTAMP BY Timestamp
    GROUP BY
        HOPPINGWINDOW(minute, 20, 1)
        -- Every 1 minute, check the last 20 minutes
)
SELECT
    Last_event.DevideId
FROM CTE
WHERE Last_event.Timestamp < Window_10

Note that after 20 minutes, the alert stop being emitted.


text:
Q: Terraform with Github Actions Pattern I am trying to implement Github Actions for Terraform Plan and Apply using Github Pull Request and Merge features.
What I am not able to achieve is, reusing the workflow for every new component in the project.
For example, I have to add a new microservice in the project, I have created a Terraform module as below,
#new-microservice.tf
module "new-microservice" {
  source = "",
  name   = "foo",
  nlb    = true,
  few other details
}

So, when a new microservice needs to be added into the project, anyone can create new TF file with module block by changing the values of the attributes.
#one-more-microservice.tf
module "one-more-microservice" {
  source = "",
  name   = "bar",
  nlb    = false,
  few other details
}

So far, so good. Issue arrives when I want to isolate each of this microservice's resource states.
Each of this TF files will go into a separate directory in the Git repo so that TF state will be isolated.
But, with Github Actions, workflow yaml should be kept in .github/workflow directory of the Git repository.
How can I find the directory which has changes in the pull request and run the workflow inside that directory?
I tried searching in the Github Actions Marketplace, couldn't find anything concrete.
I don't want to create multiple jobs inside the plan and deploy workflow yaml files, one for microservice.

A: This is tricky because you're basically saying that you want one workflow to trigger on multiple repository pushes which is not currently a thing in github actions
Option 1:
Create a Workflow Template that all it does is spin up on a service push and sends a workflow dispatcher event. You basically make an api call that triggers that workflow. The only caveat is that as of right now organizational workflow templates only work on public repos.
Option 2:
Keep track of each service last build commit. This will allow you do to scans. The problem with this is that you will need to setup a workflow on a cronjob that will then go through a list of all your repos in your organization, and do the commit diff. If there is a commit diff available then you know to do what you need to do for your deployment. How to get list of organization repos


text:
Q: WebAPI can't call Put method I have the following code on server:
public class UploadController : ApiController
{

    public void Put(string filename, string description)
    {
        ...
    }

    public void Put()
    {
        ...
    }

and try to call it from client:
        var clientDescr = new HttpClient();

        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("filename", "test"));
        postData.Add(new KeyValuePair<string, string>("description", "100"));

        HttpContent contentDescr = new FormUrlEncodedContent(postData);

        clientDescr.PutAsync("http://localhost:8758/api/upload", contentDescr).ContinueWith(
            (postTask) =>
            {
                postTask.Result.EnsureSuccessStatusCode();
            });

but this code calls second put method (without parameters). Why and how to call first put method correctly?

A: You have several options here:
You can either choose to pass the parameters in the query string, by just changing the URI to:
http://localhost:8758/api/upload?filename=test&description=100
or you can have Web API parse the form data for you by changing your action to look like this:
public void Put(FormDataCollection formData)
{
    string fileName = formData.Get("fileName");
    string description = formData.Get("description");
}

You can also choose to create a class that has a fileName and a description property and use that as your parameter and Web API should be able to bind it correctly for you.


text:
Q: How to notify Observable when CountdownTimer is finished I have a custom Android TextView which shows the amount of time left in a game via a CountDownTimer
class CountdownTextView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {

    private lateinit var countDownTimer: CountDownTimer
    private lateinit var onFinishObservable: Observable<Unit>

    fun setTime(initTime: Int) {
        this.text = "$initTime:00"
        countDownTimer = object : CountDownTimer((initTime *1000).toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
            val minutes = millisUntilFinished / 60000
            val seconds = (millisUntilFinished % 60000) / 1000
            if (seconds / 10 > 0) {
                text = "$minutes:${(millisUntilFinished % 60000) / 1000}"
            } else {
                text = "$minutes:0${(millisUntilFinished % 60000) / 1000}"
            }
        }

        override fun onFinish() {

        }
    }

    fun startCountdown() {
        countDownTimer.start()
    }
}

How do I set up an observable that emits a value when the countDownTimer's onFinish() method is called? I need this so that on the main activity, I can subscribe to that observable and perform the necessary actions when the countdowntimer expires.

A: You could provide a Subject.
val onFinishObservable = CompletableSubject.create()

override fun onFinish() {
    onFinishObservable.onComplete()
}

Or you could use Rx for the timer instead of CountDownTimer.
fun countDownTimer(
        time: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS,
        tick: Long = 1, tickUnit: TimeUnit = TimeUnit.MILLISECONDS
): Observable<Long> {
    val timeNanos = timeUnit.toNanos(time).also { require(it >= 0) }
    val tickNanos = tickUnit.toNanos(tick).also { require(it > 0) }
    val ticks = timeNanos / tickNanos
    return Observable
        .intervalRange(
            1L, ticks, timeNanos % tickNanos, tickNanos, TimeUnit.NANOSECONDS)
        .map { ticks - it }
        .startWith(ticks)
}

fun start(time: Long, timeUnit: TimeUnit = TimeUnit.SECONDS): Completable {
    timerSubscription?.dispose()
    val timer = countDownTimer(time, timeUnit, tickUnit = TimeUnit.SECONDS)
    timerSubscription = timer.subscribe {
        text = String.format("%d:%02d", it / 60, it % 60)
    }
    return timer.ignoreElements()
}

Either way, the caller can subscribe to that Completable.


text:
Q: Why is line going through node in Sankey diagram in plotly Python? Line of Sankey diagram is going through one of the nodes while it should be seperate like all the other ones. Any idea why this is happening or how to prevent this?
fig = go.Figure(data=[go.Sankey(

node = dict(

  pad = 100,
  thickness = 30,

  line = dict(color = "black", width = 2),
  label = [" Gas: 47 MW",
           " Stoom: 35 MW",
           " Elektriciteit: 12 MW",
           "Verlies: 1 MW ",

           "R: 17 MW ",
           "F: 14 MW ",
           "Fe: 8.5 MW ",
           "Ut: 4.5 MW ",
           "VN: 4.5 MW ",
           ],

link = dict(
  source = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2],
  target = [1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8],
  value = [35, 12, 1, 13.8, 11.3, 7.3, 2.8, 3.4, 2.4, 1.1, 1.5, 3.6],)])

A: i put some randoms values for the links so look at it and change them
This is the code

A: because you made a link beetween "Gas" and "Verlies" when you did source = 0 and target = 3


text:
Q: How programmatically remove default import in Groovy? By default some packages are imported in a Groovy class. I know that you can add new one with an ImportCustomizer but is there a way to remove them programmatically?
Thanks in advance for your answers.

A: No. If you look through the code, then you'll see that the standard imports like java.io and java.math.BigDecimal are not handled by ImportCustomizer.
Which is a pity.
The default imports are handled in ResolveVisitor.java. The code doesn't allow to modify the default imports or the method where they are added.
Kudos to andrei-krotkov for finding the code.

A: It is not a pretty good solution but it works:
Arrays.fill(ResolveVisitor.DEFAULT_IMPORTS, "java.lang.");


text:
Q: ASP.Net MVC: How can I easily change the tab color of my navigation menu based on the tab that I'm on? I want to implement my navigation tabs somewhat like the ones on this site, and I've heard that this was built using ASP.Net MVC.  If I'm on stackoverflow.com/users, than the "Users" menu tab is orange and all others stay grey, same if a different tab is selected.
I am pretty good with manipulating the css to change color when it's hovered or selected, etc, and adding/removing/authorizing items in the menu container, but not familiar with how to change the color of the tab based on the tab page that I'm on. Any quick and dirty way to accomplish this?

A: Assign a unique id to the body element of each page (e.g. ). In ASP.NET MVC you could have the body tag in your master page written like:
<body id="<%= ViewData["bodyId"] %>">
And in the Controller methods for each page put something like ViewData["bodyId"] = "users"; to dynamically assign the id for each page.
Then in your nav markup, assign a class with the same name on the  tag that links to that page:

Users

Then in the css do something like this:
body#users a.users, body#another-page a.another-page {
    /* include rules for how you want the current page tab to appear */
}

That will assign your "current page" styles to any link tag with a class that matches the body tag id.

A: Further to what Bryan mentioned, I usually add a "CssClass" property to my view model in cases like this. It's also useful for the situation where the calculation of the CssClass is a little complex (since it can be tested in a VM).


text:
Q: using mysql and php with google maps I'm trying loop through every row in a table and set a marker using the value provided in the "address column". The js code and the php code until  setMarker() works fine but I'm not sure how to go about using the function inside php code.
<?php
require 'private/database.php';

$sql = "SELECT * FROM form;";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<script>setMarker($row["address"]);</script>';
    }
} else {
    echo '<script>console.log("ERROR: marker database empty");</script>';
}

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
  zoom: 15,
  center: {lat: 24.149950, lng: 120.638610},
  mapId: '63d22d3ae6cf15ff'
  });
}

// geocoder
function setMarker(address) {
    const geocoder = new google.maps.Geocoder();
  geocoder.geocode({address: address, componentRestrictions: {
    country: 'TW'}}, (results, status) => {
    if (status === 'OK') {
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
    }
  });
}

A: This is more or less what I meant with the comment I made - this way the map is created by the initMap callback function before any attempts to create the markers is made - which might not be the case in the original. This is quickly put together and not tested.
<script>
    var map;
    <?php

        require 'private/database.php';

        $sql = "SELECT * FROM form;";
        $result = mysqli_query($conn, $sql);
        $data=array();

        while ($row = mysqli_fetch_assoc($result)) {
            $data[]=$row;
        }
        // create the js variable
        printf(
            'var json=%s;',
            json_encode( $data )
        );
    ?>

    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
          zoom: 15,
          center: {lat: 24.149950, lng: 120.638610},
          mapId: '63d22d3ae6cf15ff'
      });
      Object.keys(json).forEach( key => {
        let obj=json[ key ];
        setMarker( obj['address'] )
      })
    }

    function setMarker(address) {
        const geocoder = new google.maps.Geocoder();
        geocoder.geocode( { address: address, componentRestrictions: { country: 'TW'} }, (results, status) => {
            if (status === 'OK') {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
            }
        });
    }

</script>