Remove duplicated objects that has the same value for a certain key, (wordpress: do not retrieve posts with same title)

Question: i looked for everywhere but i can't find an answer anywhere, and i'm a beginner with php so i hope that there will be someone so kind to help me.
i'm working with wordpress and i'm using this line
$post_IDs = get_posts('category_name=glicinie');

to retrieve all posts in a category, but in this category i have lot of duplicates posts, here's a portion of the array that i obtain [ with print_r($post_IDs) ]
Array (
[0] => stdClass Object
( [ID] => 761 [post_author] => 2 [post_date] => 2011-07-26 12:07:17
[post_title] => Flower )
[1] => stdClass Object
( [ID] => 760 [post_author] => 2 [post_date] => 2011-07-26 12:04:46
[post_title] => Rainbow )
[2] => stdClass Object
( [ID] => 770 [post_author] => 2 [post_date] => 2011-07-26 12:03:18
[post_title] => Coconut )
[3] => stdClass Object
( [ID] => 743 [post_author] => 5 [post_date] => 2011-07-26 11:38:48
[post_title] => Coconut )
)

after this i use this code below to populate a select in a form with title and year (that is a custom field of the post) for each post.
foreach ($post_IDs as $post_ID) {
$anno = get_post_meta($post_ID->ID, 'year', true);
$title = $post_ID->post_title;
echo '<option value="'.$title.'">' . '[' . $year . '] ' . $title . '</option>';
}

now you've seen before that i have two posts titled as "Coconut"..so in the list in the form i'll have the post Coconut displayed twice.
what i want is obvously to display the duplicated posts (like "Coconut") only once..
i think i should make a kind of check of the array before the foreach but i don't know how..so that in the foreach i loop only through the ID's that have a different "post_title" value..but how?
forgive my english.
thank in advance :)
Answer: I think this should do it.
$got = array();
foreach($post_IDs as $i => $d)
{
    if(!in_array($d[post_title]),$got)
    {
        $got[] = $d[post_title];
        $out[] = $d;
    }
}
print_r($out);


I have two grub.cfg files

Question: I'm trying to dual-boot Windows 10 and Kubuntu but since I tried setting grub as my boot manager with bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi in Windows' BCDEdit, my screen is Black until I log in to Windows (no BIOS POST or Grub menu). I just found out that I have to grub.cfg files. One in /boot/grub/grub.cfg on my / Partition and one on an unnamed FAT32 boot partition under \EFI\ubuntu\grub.cfg. I don't know which on is read when booting, I don't know if I should delete. Also if I'd run update-grub would only one file update? Maybe the one I don't need?
If you know what's going on here, please help me because I don't.
Thanks in advance!
Comment: Also I just noticed it changes my bootmanager to SHIMX6.EFI every time I reboot.
Comment: Shimx64.efi is for UEFI boot, but also works if Secure Boot is off. Ubuntu has a tiny 3 line grub.cfg in ESP that using configfile to load the full grub.cfg in your install. You need both. Better to use grub to dual boot. example UEFI configfile:
https://askubuntu.com/questions/1205982/how-make-external-usb-disk-bootable-for-bios-and-uefi
Answer: Do not delete any of this two files. In recent versions of grub-efi both files are needed.
/boot/efi/EFI/ubuntu/grub.cfg is created during bootloader-installation and will be overwritten with grub-install. The file contains only a few lines which tell grub where to find further configuration files.
/boot/grub/grub.cfg is this further configuration file. It contains detailed configuration about grub's behaviour (menu, timeout, etc) and the menuentries (including submenus). This is the file which will be updated (overwritten) by update-grub.
shimx64.efi is needed when you have secure boot enabled in your firmware settings, you may try to disable secure boot and see if things work as expected then.

I have two grub.cfg files


Unable to complete "POST" Call successfully through Robot Framework

Question: I'm creating a session along with a name and Service URL followed by performing a post request with passing a file(XML file in the form of Dictionary) as a parameter.
But response code is '500 'instead of '200' (i.e. success).
Library Used:
Library  RequestsLibrary

Snapshot of code used in Testcases section:
create session  session  http://myservice.com/method     #(Just an example)
${response}=  Post Request  session  /post  files=${files}

Error: Not getting any error. Moreover Line of Code which has "Post
  Request" is passing. But the status of response code is "500"
  (Supposed to be "200").
Comment: please share more information: what lib are you using, what exact error do you get etc.
Comment: Library Used:  RequestsLibrary
Error:              No Error. But status of response is "500" (Supposed to be "200" ).
Answer: A 500 response code means your request worked, but that the server threw an error. You need to check the server logs for more information.


Ajax call after reading the current text input value

Question: I am following this answer https://stackoverflow.com/a/20698523/1695685 in order to read value from a handheld barcode scanner. The code works fine as mentioned in the answer (fiddle is attached in the above link)
However, what I am trying to do is to make some ajax calls based on the current value of text input after reading a barcode.
The problem I'm facing is that if I scan barcode multiple times I am making ajax calls the same number of times after I press a button (which triggers the ajax call). For e.g. If I read 4 barcodes, I am making the same ajax call( in my case http://localhost:51990/Home/DecodeScanner) 4 times. What I am after is to make only one call after pressing a button, but only read the latest value from the text input box.
Every time I can scan a barcode the text input box is showing the new value (previous values are overridden). However, the ajax call is firing all the previous scans as well on pressing #scanner-verify-button button.
This is my modified Fiddle with my custom ajax calls
/*
    This code will determine when a code has been either entered manually or
    entered using a scanner.
    It assumes that a code has finished being entered when one of the following
    events occurs:
        • The enter key (keycode 13) is input
        • The input has a minumum length of text and loses focus
        • Input stops after being entered very fast (assumed to be a scanner)
*/

var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;

// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function(e) {
  // restart the timer
  if (timing) {
    clearTimeout(timing);
  }

  // handle the key event
  if (e.which == 13) {
    // Enter key was entered

    // don't submit the form
    e.preventDefault();

    // has the user finished entering manually?
    if ($("#scanInput").val().length >= minChars) {
      userFinishedEntering = true; // incase the user pressed the enter key
      inputComplete();
    }
  } else {
    // some other key value was entered

    // could be the last character
    inputStop = performance.now();
    lastKey = e.which;

    // don't assume it's finished just yet
    userFinishedEntering = false;

    // is this the first character?
    if (!inputStart) {
      firstKey = e.which;
      inputStart = inputStop;

      // watch for a loss of focus
      $("body").on("blur", "#scanInput", inputBlur);
    }

    // start the timer again
    timing = setTimeout(inputTimeoutHandler, 500);
  }
});

// Assume that a loss of focus means the value has finished being entered
function inputBlur() {
  clearTimeout(timing);
  if ($("#scanInput").val().length >= minChars) {
    userFinishedEntering = true;
    inputComplete();
  }
};

// reset the page
$("#reset").click(function(e) {
  e.preventDefault();
  resetValues();
});

function resetValues() {
  // clear the variables
  inputStart = null;
  inputStop = null;
  firstKey = null;
  lastKey = null;
  // clear the results
  inputComplete();
}

// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
  return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}

// Determine if the user is just typing slowly
function isUserFinishedEntering() {
  return !isScannerInput() && userFinishedEntering;
}

function inputTimeoutHandler() {
  // stop listening for a timer event
  clearTimeout(timing);
  // if the value is being entered manually and hasn't finished being entered
  if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
    // keep waiting for input
    return;
  } else {
    reportValues();
  }
}

// here we decide what to do now that we know a value has been completely entered
function inputComplete() {
  // stop listening for the input to lose focus
  $("body").off("blur", "#scanInput", inputBlur);
  // report the results
  reportValues();
}

function reportValues() {
  // update the metrics
  $("#startTime").text(inputStart == null ? "" : inputStart);
  $("#firstKey").text(firstKey == null ? "" : firstKey);
  $("#endTime").text(inputStop == null ? "" : inputStop);
  $("#lastKey").text(lastKey == null ? "" : lastKey);
  $("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
  if (!inputStart) {
    // clear the results
    $("#resultsList").html("");
    $("#scanInput").focus().select();
  } else {
    // prepend another result item
    var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
    $("#resultsList").prepend("
" +
      "Value: " + $("#scanInput").val() + "
" +
      "ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "
" +
      "InputMethod: " + inputMethod + "
" +
      "

");
    $("#scanInput").focus().select();
    inputStart = null;

    // Some transformations

    const barcodeString = $("#scanInput").val();

    const productCode = barcodeString.substring(5, 19);
    const serialNumber = barcodeString.substring(36, 46);
    const batch = barcodeString.substring(29, 34);
    const expirationDate = barcodeString.substring(21, 27);

    // AJAX calls
    $('#scanner-verify-button').click(function() {
      $.ajax({
        url: "DecodeScanner",
        type: "POST",
        data: {
          productCode: productCode,
          serialNumber: serialNumber,
          batch: batch,
          expirationDate: expirationDate,
          commandStatusCode: 0
        },
        async: true,
        success: function(data) {
          $('#pTextAreaResult').text(data);
        }
      });
    });
  }
}

$("#scanInput").focus();

HTML
<form>
    <input id="scanInput" />
    <button id="reset">Reset</button>
</form>

Event Information
 Start:

First Key:

Last Ley:

End:

Elapsed:

Results

    <button id="scanner-verify-button" type="submit">Verify</button>

Answer: As per the code, the click handler for the scanner button seems to be registered multiple times.
The click handler should be registered only once.
The reportValues() is called multiple times which registers the click handler multiple times. This means when you press the button, all the click handlers get called and ajax request gets triggered.
You need to put the click handler outside of any function which can get called multiple times.
Also as per the code, all the variables which need to be accessed by the click handler should be declared outside reportValues.
Comment: How do I avoid that?
Comment: I can put the click handler outside the `reportValues()` but then how do I fetch the latest updated text input value?
Comment: You can set the latest updated text values in variables defined outside reportValues. Then the click handler can access those variables.
Comment: Can you show me a sample code on how do I fetch the text values in variables outside the `reportValues` block and call the click handler afterwards?
Answer: The problem was the ajax call inside block $('#scanner-verify-button').click(function() {} was attaching new listener to the button on everytime the reportValues() call waas made.
I was able to solve this by moving the ajax calls in its own block
// Check for any input changes

var productCode, serialNumber, batch, expirationDate;

$("#scanInput").on("change paste keyup", function () {
    barcodeString = $("#scanInput").val();
    productCode = barcodeString.substring(5, 19);
    serialNumber = barcodeString.substring(36, 46);
    batch = barcodeString.substring(29, 34);
    expirationDate = barcodeString.substring(21, 27);
});

// Ajax calls
$("#scanner-verify-button").click(function () {
    $.ajax({
        url: "DecodeScanner",
        type: "POST",
        data: {
            productCode: productCode,
            serialNumber: serialNumber,
            batch: batch,
            expirationDate: expirationDate,
            commandStatusCode: 0
        },
        async: true,
        success: function (data) {
            $('#pTextAreaResult').text(data);
        }
    });
});

Working Fiddle


Storing information of last frames in real time video acquisition MATLAB

Question: This code processes a video in real time through a webcam in Matlab. For each frame, I perform some operations and the final result is 'degrees'.
I need to store the result of degrees for, let's say, the last 15 frames, and check that they are all in the same range (for example between 50 and 80 degrees), all this while the video is still running. But I would like to be deleting the previous ones in order to save memory (since it is video acquisition it can run forever), or if not possible how can I always compare with the last 15 frames?
    function DetectTarget2()
    clc;imaqreset;close all;

    try
        % For linux
        Vid = videoinput('linuxvideo', 1);
    catch
        try
            % For mac
            Vid = videoinput('macvideo', 1);
        catch
            errordlg('No webcam available');
        end
    end

    set(Vid,'FramesPerTrigger',1);  %capture 1 frame every time Vid is triggered
    set(Vid,'TriggerRepeat',Inf);   %infinite amount of triggers
    set(Vid,'ReturnedColorSpace','RGB');
    triggerconfig(Vid, 'Manual');   %trigger Vid manually within program

    t = timer('TimerFcn',@dispim, 'Period', 0.04,...
        'executionMode','fixedRate');

    function dispim(~,~)
            trigger(Vid)%trigger Vid to capture image
            im=getdata(Vid,1);
            detector = vision.CascadeObjectDetector('Cascade1Matlab.xml');
            bbox = step(detector, im);

    % CALCULATIONS

    degrees=result;
    end
    end

Comment: Have you solved your problem? If my answer solved your problem I would be very happy if it can be marked as solution and maybe receive an upvote. If not I would be interested in hear some additional explanation to your problem or why my answer does not solve your problem.
Comment: Oh, yes, I am so sorry, I was doing it some days ago when I had an Internet connection problem and I totally forgot after that. Thanks a lot!
Answer: No problem at all, use the modulo function to access cells in a cell array.
In somewhat pseudocode:
result_buffer = cell(1, 15);
index = 1;
while ~finished
  ... % some calculation
  result_buffer{mod(index, 15) + 1} = result;
  % access some previous result
  result_buffer{mod(index - 5, 15) + 1}; % the image of 5 iterations before
  index = index + 1;
end

This is a simple circular buffer.
Comment: The problem and solution is quite independent of the image processing context.
Comment: Okay, I'm new to image processing, so I didn't know if there was a special case.
This works fine, so thank you!


Loading System.Windows.Controls.Image to WritableBitmap object

Question: I've created Image object in xaml code:
<Image Name="Square" Source="Square.png" Height="400" Width="640"/>

In code-behind I've written:
WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);

If I'm creating pixel array, puting to WritableBitmap and then to Image like this:
    int width = 300;
    int height = 300;
    WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
    uint[] pixels = new uint[width * height];

    bitmap.WritePixels(new Int32Rect(0, 0, 300, 300), pixels, width * 4, 0);
    **Square.Source = bitmap;**

I haven't any problem, but when I'm trying to load my image created in xaml code to WritableBitmap, I can't do this:
WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);
bitmap = Square.Source; // Cannot implicitly convert type 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.WriteableBitmap'

So if I can't convert type 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.WriteableBitmap', why I can convert 'System.Windows.Media.Imaging.WriteableBitmap' to 'System.Windows.Media.ImageSource'?
    Square.Source = bitmap;
    bitmap = Square.Source; // Why it does not work?

Thanks for any help.
Comment: Have you tried something like this?: `WriteableBitmap writeableBitmap = new WriteableBitmap(Square.Source);`
Comment: Hi Sheridan, I've put your code in visual but I have to errors:
*The best overloaded method match for 'System.Windows.Media.Imaging.WriteableBitmap.WriteableBitmap(System.Windows.Media.Imaging.BitmapSource)' has some invalid arguments*
**and**
*Argument 1: cannot convert from 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.BitmapSource'*
Comment: Ahh sorry, I forgot to cast the `ImageSource` to a `BitmapSource`. See @Clemens' answer.
Answer: You can't directly create a WriteableBitmap from any ImageSource, because the ImageSource might not be a BitmapSource (which is what the Writeablebitmap constructor takes as argument).
However, in your case it is safe to cast the Source property to BitmapSource:
var bitmap = new WriteableBitmap((BitmapSource)Square.Source);

Note that the Source property of Image control is of type ImageSource (and not BitmapSource) because the control is able to display other types of images than only bitmaps, e.g. vector images.


Is the tautological line bundle orientable as a vector bundle?

Question: Question
Let $\gamma$ be the tautological line bundle of the $n$-dimensional real projective space $\mathbb{P}^n$.
Is $\gamma$ is orientable as a vector bundle?
My guess
I only consider in case of $n=1$.
Let $n=1$, and consider the one dimensional projective space.
let $\nu$ be a normal bundle on the two dimensional sphere $\mathbb{S}^1 \subset \mathbb{R}^2$. Then, there is a bundle map $ \nu \to \gamma$. Then the pull back of the cohomology class $u_F$ of $\gamma$ also gives a orientation of the bundle $\nu$. However, the antipodal points of $\mathbb{S}^1$ are sended to the same point of $\mathbb{P}^1$ and thus, such orientation will be given by some same vector in $\mathbb{E}^2$. But it is impossible, because the orientation of antipodal points should be opposite directions. Thus $\gamma$ is not orientable as a vector bundle.

Definition of orientation 1   Each fiber $F$ of $\gamma$ is given an orientation as an vector space and  ,in addition, for each $p \in
\mathbb{P}^n$ there are a neighborhood $N$ of $\mathbb{P}^n$ centered
  at $p$ and a local section $s$ of $\gamma$ defined on $N$ such that
  the value of section $s$ at each $q \in N$ gives the orientation of
  the fiber at $q$.
Definition of orientation 2   For each fiber, there is a generator $u_F \in  H^1(F,F-0,\mathbb{Z})$  such that   for each $q \in
 \mathbb{P}^n$ there is an element $u \in
 H^1(\pi^{-1}(N),\pi^{-1}(N)-0,\mathbb{Z})$  whose restriction to $F$
  is coincides with $u_F$.
Answer: It is not orientable since it is not trivial a $1$-dimensional vector bundle is orientable if and only if it is trivial. A way to see this, if $E\rightarrow M$ is a $1$-dimensional orientable vector bundle, there exist coordinate change $(U_i,g_{ij}:U_i\cap U_j\rightarrow \mathbb{R}_+^*$ so the bundle has a $\mathbb{R}_+^*$ reduction since this group is contractible, the bundle is trivial.
See also the answer here to see why the tautoligical line bundle is not trivial.
How to distinguish the tautological line bundle and the trivial line bundle on $P^n$?
Comment: Hi! I see your answers on MSE a lot, thanks for your contributions! Just a heads up (I'm not going to downvote your answer) but your answer is wrong. Your claim that a line bundle is orientable if and only if trivial is also wrong. See https://math.stackexchange.com/questions/1486105/is-the-total-space-of-the-tautological-line-bundle-over-mathbbrpn-a-non?rq=1 which shows that the tautological line bundle over real projective space $ \mathbb{R}P^n $ is orientable if & only if $ n $ is even. Fun fact: tautological bundle of $ \mathbb{R}P^2 $ covers orientable $ \mathbb{R}P^3 \# \mathbb{R}P^3 $!


Optimizing the redirect code

Question: I found this from a shortcode and we're having a bit of an issue with the loading time using this function. I was wondering if there's a way to further optimize this or perhaps use a php redirection instead of javascript?
function gdp_mss_after_login() {
$user = wp_get_current_user();

if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {

    $user_level = get_user_meta($user->ID, 'gdp_level', true);

    ob_start();

    if ( !empty($user_level) ) {
        $post_id = get_option('gdp_mss_course_level_' . $user_level);
        $url = esc_url(get_permalink($post_id));
        ?>

        <?php
    }

}
return ob_get_clean();
}
add_shortcode( 'gdp_mss_login_redirect', 'gdp_mss_after_login' );

Comment: why not wp_redirect()?
Answer: Use wp_redirect()
function gdp_mss_after_login() {
  $user = wp_get_current_user();
  if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
    $user_level = get_user_meta($user->ID, 'gdp_level', true);
    if ( !empty($user_level) ) {
        $post_id = get_option('gdp_mss_course_level_' . $user_level);
        $url = esc_url(get_permalink($post_id));
        wp_redirect($url);
    }else{
       return false;
    }
  }
}
add_shortcode( 'gdp_mss_login_redirect', 'gdp_mss_after_login' );

Comment: Thanks Rakesh. Doesn't seem to be working. The redirection for some reason is not happening. Anything I'm missing?

Optimizing the redirect code


Difference between ibatis and mybatis

Question: What is the difference between iBatis and myBatis? Where can I find a perfect example of those?
Answer: MyBatis is a fork from iBATIS, and according to Wikipedia most of iBATIS' developers moved over to MyBatis too. The iBATIS project is currently marked as Inactive, therefore you should go with MyBatis for new projects and only use iBATIS if you're maintaining an existing project which already uses iBATIS.
http://en.wikipedia.org/wiki/MyBatis

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS.

http://en.wikipedia.org/wiki/IBATIS

On May 21, 2010 the development team forked the code creating a new project called MyBatis and making new releases there. As a consequence the Apache iBATIS project became inactive and was moved to the Apache Attic in June 2010.
Answer: It is the same thing, a persistence framework! But until June 2010, iBatis was under Apache license and since then, the framework founders decided to move it to Google Code and they renamed it to MyBatis.
The framework is still the same though, it just has a different name now. (of course it should be kept in mind that when time pass, components/features etc, might get updated, so there are more powerful functions added to MyBatis).
Answer: 1.Development team: iBatis was developed by the Apache Foundation, and MyBatis is a branch of iBatis maintained by the original Google team of iBatis.
2.Configuration method: iBatis uses complex XML configuration, while MyBatis simplifies the configuration of XML and annotations, making SQL statement writing and debugging more convenient.
3.Flexibility: MyBatis has higher flexibility compared to iBatis. MyBatis allows you to directly write native SQL statements, while iBatis requires encapsulating SQL statements in XML.
4.Plugin mechanism: MyBatis provides a plugin mechanism, allowing developers to extend the functionality of MyBatis through plugins, while iBatis does not have such a mechanism.
5.Dynamic SQL: MyBatis supports more powerful dynamic SQL statements, which can generate SQL statements at runtime, while iBatis has weaker dynamic SQL capabilities.
Community activity: As MyBatis is a successor product to iBatis, MyBatis has a higher community activity and update speed than iBatis.
Overall, MyBatis outperforms iBatis in terms of functionality and ease of use, making it an improved version of iBatis.

Difference between ibatis and mybatis


Let $I$ be an interval and let $f : I\rightarrow\mathbb{R}$ be a function. Show that $f$ is convex on $I$

Question: Let $I$ be an interval and let $f : I\rightarrow\mathbb{R}$ be a function. Show that $f$ is
convex on $I$ if and only if the slope of the chord joining $(x_1, f(x_1))$ and
$(x, f(x))$ is less than or equal to the slope of the chord joining $(x, f(x))$
and $(x_2, f(x_2))$ for all $x_1 < x < x_2$ in $I$.
Geometrically the result I have verified but I have not been able to give a formal proof.
Comment: What did you try? Write down the definition fo convexity, for $x=tx_1+(1-t)x_2,$ and you will easily see it is equivalent to this condition on slopes.
Comment: See https://math.stackexchange.com/q/1140679/42969
Answer: for any $x \in (x_1,x_2)$ we can write : $x=tx_1+(1-t)x_2$ which $t \in (0,1)$. if you solve it for $t$ you get :
$$
t = \frac{x_2-x}{x_2-x_1}
$$
so $x$ become :
$$
x = \big( \frac{x_2-x}{x_2-x_1} \big)x_1 + \big( \frac{x-x_1}{x_2-x_1} \big)x_2
\quad \forall x \in (x_1,x_2) $$
with this transformation the proof of both side is just writing down given equation:
$$
\frac{f(x)-f(x_1)}{x-x_1} \leq \frac{f(x_2)-f(x)}{x_2-x}
\\ \iff (x_2-x+x-x_1)f(x) \leq (x_2-x)f(x_1)+(x-x_1)f(x_2)
\\ \iff f(x) \leq  \big( \frac{x_2-x}{x_2-x_1} \big)f(x_1) +\big( \frac{x-x_1}{x_2-x_1} \big)f(x_2)
\\ \iff f(tx_1+(1-t)x_2) \leq tf(x_1)+(1-t)f(x_2) \qquad \forall t \in (0,1) \quad \square$$
Answer: You want to show that for any fixed $x_1<x<x_2$ in $I$ the following statements are equivalent:
(a) $\quad$ $(x,f(x))$ is below the line joining $x_1,f(x_1)$ and $x_2,f(x_2)$;
(b) $\quad$ the slope of the chord joining $(x_1, f(x_1))$ and
$(x, f(x))$ is less than or equal to the slope of the chord joining $(x, f(x))$
and $(x_2, f(x_2))$.
Let us formalise the geometric intuition: Define $\lambda \in (0,1)$ be such that $x = (1-\lambda) x_1 + \lambda x_2$, and let $a_1$ and $a_2$ the slopes of the cords from condition (b):
$$
  a_1 = \frac{f(x)-f(x_1)}{x-x_1},
\quad \text{and} \quad
  a_2 = \frac{f(x)-f(x_2)}{x-x_2}.
$$
Then conditions (a) and (b) can be formulated as:
(a) $\quad$ $f(x) \leq (1-\lambda) f(x_1) + \lambda f(x_2) \tag{*};$
(b) $\quad$ $a_1\leq a_2$.
Subtracting $f(x)$ from both sides of the inequality (*) we obtain an equivalent inequality
$$
 0 \leq (1-\lambda) [f(x_1)-f(x)] + \lambda [f(x_2)-f(x)],
$$
$$
 0 \leq (1-\lambda) a_1(x_1-x) + \lambda a_2 (x_2-x), \tag{**}
$$
From the definition of $\lambda$ we have
$$
 0 = (1-\lambda) (x_1-x) + \lambda (x_2-x).
$$
Multiplying this equation by $a_1$ and subtracting it from (**), we obtain the following equivalent inequality
$$
 0 \leq \lambda (a_2-a_1) (x_2-x).
$$
Since $\lambda>0$ and $x_2>x$, the obtained inequality is equivalent to $a_2 \geq a_1$.
We conclude that conditions (a) and (b) are equivalent for any $x_1<x<x_2$ in $I$.


The map $C : \mathcal{H} \to L^2 (X)$ is bounded whenever it is bounded on a dense subspace $\mathcal{D} \subset \mathcal{H}$.

Question:
Let $\mathcal{H}$ be a Hilbert space, let $\mathcal{D} \subset \mathcal{H}$ be a dense subspace and let $(\eta_x)_{x \in X} \subset \mathcal{H}$ be indexed by a $\sigma$-finite measure space $(X, \Sigma_X, \mu_X)$. Suppose there exists a $K > 0$ such that, for all $f \in \mathcal{D}$,
  $$ \int_X | \langle f, \eta_x \rangle |^2 \; d\mu_X (x) \leq K \| f \|^2_{\mathcal{H}} \quad \quad \quad \quad (*)$$
  Then the inequality $(*)$ holds for all $f \in \mathcal{H}$.

I am aware of a proof of the above stated result that is quite ingenious and heavily depends on the fact that the involved measure space is $\sigma$-finite. However, I am curious if this is really necessary.
I am approaching the above stated result by considering the linear operator
$$C : \mathcal{H} \to L^2 (X), \; f \mapsto \{ \langle f, \eta_x \rangle \}_{x \in X},$$
which is bounded on $\mathcal{D}$. However, boundedness of a dense subspace is, in general, not sufficient for a linear operator to be bounded on its entire domain. Thus the result is not trivial, and is a special property of $C$.
Any help or comment is highly appreciated.
Answer: Let $f_0 \in H $. By density, there is a sequence $(f_n)_n $ in $D $ such that $f_n \to f $.
Now,  for $F_n (x) := |\langle f_n, \eta_x\rangle |^2$, we have $F_n \to F_0$ pointwise. Hence, by Fatou's Lemma,
$$
\int F_0 \leq \liminf_n \int F_n \leq \liminf K \|f_n \|^2 = K \|f\|^2.
$$
Thus, no fancy functional analysis is neede; only Fatou's Lemma.


Check if it absolutely converges or not

Question: I'm trying to determine if $\sum \limits_{n=1}^{\infty} \sin(n\pi + \frac{1}{2n})$ absolutely converges or not.
Help me check it. I don't know how to do it. Advance thanks. :)
Comment: \frac{1}{2n}
 Thanks
Answer: Observe
\begin{align}
\sin\left(n\pi +\frac{1}{2n}\right) = (-1)^n\sin\frac{1}{2n}
\end{align}
then apply alternating series test.
It should be noted for large enough $n$ the terms $\sin\frac{1}{2n}$ decreases monotonically to zero.
Hence the series converges conditionally.
Edit: Let us consider the case of absolute convergence. Observe
\begin{align}
\sin x = x-\frac{x^3}{3!} +\mathcal{O}(x^5)
\end{align}
which means
\begin{align}
\sin x \geq x-\frac{x^3}{3!}
\end{align}
for a neigbhorhood close to $0$. Hence it follows
\begin{align}
\sum^\infty_{n=N} \sin \frac{1}{2n} \geq \sum^\infty_{n=N} \frac{1}{2n} -\frac{1}{3!}\sum^\infty_{n=N} \frac{1}{8 n^3}
\end{align}
which shows that the series diverges absolutely because $\sum^\infty_{n=N} \frac{1}{n} = \infty$.
Comment: The question is about absolute convergence.
Comment: You did a good job at answering a wrong question :)
Comment: @Wojowu I think it's a habit. I'm kind of absent-minded.
Answer: For each $n>0$
$\sin(n\pi+\frac{1}{2n})=(-1)^n\sin(\frac{1}{2n})$
and
$$|\sin(n\pi+\frac{1}{2n})|=\sin(\frac{1}{2n}).$$
but
$$\sin(\frac{1}{2n})=\frac{1}{2n}(1+(2n\sin(\frac{1}{2n})-1))$$
$$=\frac{1}{2n}(1+\epsilon(n))$$ with
$$\lim_{n\to+\infty}\epsilon(n)=0.$$
thus for large enough $n$,
$$\frac{1}{2}\frac{1}{2n}<\sin(\frac{1}{2n})$$
and by comparison with harmonic series, $$\sum \sin(\frac{1}{2n})$$ is divergent.
Comment: Thanks for the comment. I have edited my post and (+1) for your solution.
Answer: Another approach, perhaps simpler but I think that shorter anyway: the limit comparison theorem with $\;b_n=\frac1{2n}\;$ , then
$$\frac{a_n}{b_n}=\frac{\sin\frac1{2n}}{\frac1{2n}}\xrightarrow[n\to\infty]{}1$$
and thus the series $\;\sum\sin\frac1{2n}\;,\;\;\sum\frac1{2n}\;$ converge or diverge together...but the latter is just a constant multiple of the harmonic one.
Comment: That is what i did friend DonAntonio.
Comment: @AbdallahHammam No, you didn't at all. Your last step is direct comparison using a function $\;\epsilon(n)\;$ which comes from another limit.
Comment: Didn't you see  what is $\epsilon(n)$ in my answer.
Comment: @AbdallahHammam Of course: it is $\;\epsilon (n)=2n\sin\frac1{2n}-1\;$ ...so what? This approaches zero, that's a basic, elementary limit, which then allowed you to use direct comparison test, as opposed to the **limit** comparison test (google it) I use above.
Comment: If you don't know it, The limit comparison test  comes from the direct comparison one.
Comment: @AbdallahHammam No, it doesn't.  That would be like saying that the $\;n\,-$ th root test comes or yields the quotient test: they are different ones. Of course, we *use* the direct comparison test to prove the limit comparison test ...  Didn't you google it as I adviced you? Take a peek at  http://tutorial.math.lamar.edu/Classes/CalcII/SeriesCompTest.aspx , and you will be able to see it is a separate test, and sometimes very useful as it allows you to prove convergence/divergence faster/easier than other tests. You can also read here: https://en.wikipedia.org/wiki/Limit_comparison_test
Comment: @AbdallahHammam Any time.
Answer: Notice that $|\sin(n\pi +{1\over2n})| = \sin({1\over2n}) \sim {1\over2n}$ and therefore $\sum \sin(n\pi +{1\over2n})$ is absolutely divergent (because $\sum{1\over n}$ is)

Check if it absolutely converges or not


GLKMathProject gives me estrange numbers

Question: I can not get the screen coordinates, I only get big numbers when I use the code below, can somebody tell me why, the position of x, y is in radians, is that a wrong ?
<code>float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(_overture),
                                                        aspect,
                                                        0.1f,
                                                        400.0f);
projectionMatrix = GLKMatrix4Rotate(projectionMatrix, ES_PI, 1.0f, 0.0f, 0.0f);

GLKMatrix4 modelViewMatrix = GLKMatrix4Identity;
modelViewMatrix = GLKMatrix4Scale(modelViewMatrix, 300.0, 300.0, 300.0);

modelViewMatrix = GLKMatrix4RotateX(modelViewMatrix, 0.296706);
modelViewMatrix = GLKMatrix4RotateY(modelViewMatrix, -0.858702);

_modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

CGSize viewSize = self.view.bounds.size;
int viewPort[4];
viewPort[0] = 0;
viewPort[1] = 0;
viewPort[2] = (int)viewSize.width;
viewPort[3] = (int)viewSize.height;

pos.x = 0.296706; //radians
pos.y = -0.858702; //radians
GLKVector3 coor2 = GLKVector3Make(pos.x, pos.y, 0);

GLKVector3 windowVector = GLKMathProject(coor2, modelViewMatrix, projectionMatrix, viewPort);
</code>

projectionMatrix
     0.818481, 0.000000, 0.000000,  0.000000
     0.000000, -1.091309, 0.000000,  0.000000
     0.000000, 0.000000, 1.000500,  1.000000
     0.000000, 0.000000, -0.200050,  0.000000
modelviewmatrix
     196.026169, -66.397179, 217.175415,  0.000000
     0.000000, 286.891449, 87.711510,  0.000000    -227.098526, -57.312504, 187.460770,  0.000000
     0.000000, 0.000000, 0.000000,  1.000000
_modelViewProjectionMatrix :
     160.443787, 72.459831, 217.284042,  217.175415
     0.000000, -313.087097, 87.755409,  87.711533    -185.875931, 62.545647, 187.554535,  187.460770
     0.000000, 0.000000, -0.200050,  0.000000
Comment: coord2 should be in object space. Not in radians.
Comment: NSLog the projection matrix and the modelview matrix.
Comment: @lead_the_zeppelin thanks for your time, I added more code, as a result I get this numbers  windowVector.x = -1725.853271, windowVector.y -9824.593750 what I want to know is where in the window coordinates the x, y radians are.  so how do I know which is the position inside my object space for the x,y radians in order to calculate the window coordinates ??? my object is a sphere with an image in 360 degrees inside, thanks...
Comment: @lead_the_zeppelin should I use  _modelViewProjectionMatrix intend of modelViewMatrix  in the GLKMathProject function ??
Answer: It looks like your camera is at (0,0,0) looking at m41,m42,m43 of your modelViewMatrix and your object's coor2.z = 0. Your are at the center of the object. This might be the problem?
Comment: I don't think so, because if you look at the code I rotate the modelViewMatrix modelViewMatrix = GLKMatrix4RotateX(modelViewMatrix, 0.296706);
modelViewMatrix = GLKMatrix4RotateY(modelViewMatrix, -0.858702); the modelViewMatrix you see is after rotation, the rotation changes only the y,x,z axis and not the camera, thats why the camera is 0.
Comment: @user1241006 can you try it with coor2 = (10,10,10)? just to make sure values are not too high?
Comment: thanks, now is working, the problem was that i was not using the exact coordinates, I tried  coor2 = (10,10,1) and it was working perfect every time I rotated the matrix the new coordinates on the screen were calculated for the point (10,10,1), I left the z value in 1 always and is working perfect,   thanks for your help...


Cutting Ceramic Glass Glazed Tile

Question: I have some glass glazed ceramic mosaic tile that I will soon install as our new kitchen backsplash.  The tiles are 4" x 4", with pre-scoring into 1" x 1" mosaics with a grout line of 1/16".  They are 3/8" thick.
I only have a wet tile saw at the moment.  The manufacturer recommends dry cutting these tiles.  What is the best way to cut them and minimise chipping of the glass glazed finish?
Many Thanks,
Simon
Answer: Unplug the water pump on your wet tile saw and go ahead and use it. If you are worried about damaging your wet blade (I wouldn't be) you can buy a dry cut diamond blade for your wet saw.

Cutting Ceramic Glass Glazed Tile


Cannot assign value of type '(String?, Bool, [AnyObject]?, NSError?) -> ()' to

Question: After I update Xcode Version 8.0 (8A218a) swift 3, I got this error

Cannot assign value of type '(String?, Bool, [AnyObject]?, NSError?) -> ()' to type 'UIActivityViewControllerCompletionWithItemsHandler?'

activityview.completionWithItemsHandler = {(activityType: String?, completed:Bool, returnedItems:[AnyObject]?, error: NSError?) in
            if !completed {
                print("cancelled")
                return
            }else{
                complele()
            }

        }

I have been following this Cannot assign a value of type '(String!, Bool, [AnyObject]!, NSError!)->Void to a value of type UIActivityViewControllerCompletionWithItemsHandler?'
But i still got the error message.
It works well in previous version 7.3.1 swift 2.
Answer: Use UIActivityType instead of String, [Any] instead of [AnyObject] and Error instead of NSError like this.
activityview.completionWithItemsHandler = {(activityType: UIActivityType?, completed:Bool, returnedItems:[Any]?, error: Error?) in
    if !completed {
        print("cancelled")
        return
    }else{
        complele()
    }
}

Check apple documentation for more detail.
Comment: still got the error message : Cannot assign value of type '(String?, Bool, [Any]?, Error?) -> ()' to type 'UIActivityViewControllerCompletionWithItemsHandler?'
Comment: Thanks you save my day :D
Comment: Welcome mate, Happy Coding :)


Probability density function $\max\{2,X\}$

Question: Let $X$ be a random variable with a PDF $f(x)=\frac{1}{9}x^2\mathbb{1}_{(0,3)}(x)$. Find the distribution and PDF of $Y=\max\{2,X\}$ .
$F_X(t)=\int\limits_0^tf(x)dx=\int\limits_0^t\frac{1}{9}x^2dx=\frac{t^3}{27}$
$Y=\begin{cases}
                    2 &\text{for $X \in (0,2)$} \\
                    X &\text{for $X \in [2,3)$}
\end{cases}$
$F_Y(t)=\Bbb P(Y \leq t)=\Bbb P(\max\{2,X\}\leq t)=\Bbb P(2\leq t, X\leq t)= \ ?$
PDF:
$f_Y(t)=\begin{cases}
                    C &\text{for $X \in (0,2)$} \\
                    \frac{1}{9}x^2 &\text{for $X \in [2,3)$}
\end{cases}$
$\int\limits_0^2Cdt+\int\limits_2^3\frac{1}{9}t^2dt=2C+\frac{19}{27}=1$, then:
$C=\frac{4}{27}$
Answer: The pdf is correct and you can find the CDF as well by integrating the pdf, but if you wish to find $\Pr\{\max(X,2)\le t\}$ directly, I suggest you the following way:
$$
\Pr\{\max(X,2)\le t\}{=
\Pr\{\max(X,2)\le t|X<2\}\Pr\{X<2\}\\+
\Pr\{\max(X,2)\le t|X\ge 2\}\Pr\{X\ge 2\}
}
$$
Answer: First observe that Y-support is the following: $y \in[2;3]$
Then observe that $P(Y=2)=F_X(2)=\int_0^2 f(x)dx=\frac{8}{27}$
Concluding, Y-distribution is the following
$$ F_Y(y) =
\begin{cases}
0,  & \text{if $y<2$} \\
\frac{8}{27},  & \text{if $y=2$} \\
\frac{y^3}{27},  & \text{if $2<y<3$} \\
1,  & \text{if $y\geq 3$}
\end{cases}$$
As you can see the distribution function has "a jump" in $Y=2$ thus the rv is not absolutely continuous (it is a mixed distribution)
So technically the PDF (as it is defined only for continuous rv) does not exist.
Actually there is a generalization of density called "mixed density", or "mixed PDF". You can calculate it by derivating F where the variable is continuous and calculating $p(y_0)=F_Y(y_0^+)-F_Y(y_0^-)$ where Y is discrete (in your case in $Y=2$)

Here is a drawing of the transformation function. The line in red is $Y=max(2;X)$

As you can see, when $X \in (0;2]$, a mass of probability $p=\frac{8}{27}$ is concentrated in a singleton: $Y=2$. This means that the resulting Law of Y is discret in this point...in the rest of Y-support, Y is continuous being $Y=X$
Comment: thanks! but why can't I just write $\frac{y^3}{27}$ for $y \in [2,3)$?
Comment: @itsme: of course you can. I just wanted to underline that the distribution is mixed and in $Y=2$ it is discrete
Comment: thanks again. But I don't think I completely see that the distribution is mixed. In $Y=2$ there is a peak indeed, but $Y \in [2,3)$ and inside of this interval $F_Y(y)$ is differentiable, isn't it?
Comment: @itsme: F is discontinuous
Comment: @itsme : I edited my answer with further details to explain you why Y law is mixed. Since you're new here, I would like to encourage you to click the check mark if this answer was helpful for you. It'll encourage others to answer your questions in the future


Why does the main thread wait the thread created by std::async() if the return value is not hold by lvalue?

Question: When I run the following code,
#include <thread>
#include <iostream>
#include <future>

int main() {
    auto fut = std::async(
        std::launch::async,
        []{
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "sub : " << std::this_thread::get_id() << std::endl;
        }
    );

    std::cout << "do some on main thread" << std::endl;

    fut.get();

    std::cout << "main: " << std::this_thread::get_id() << std::endl;
}

I got the following output.
do some on main thread
sub : 139899103246080
main: 139899103250240

Running demo: https://godbolt.org/z/c9WedY4oq
It is the same behavior as I expected.
"do some on main thread" outputs first, because the sub thread created by std::async() waits 1 second the beggining of the thread.
So far, so good.

However, when I removed the variable fut, then I got weird behavior for me.
NOTE: This code is for only experimental purpose
#include <thread>
#include <iostream>
#include <future>

int main() {
    std::async(
        std::launch::async,
        []{
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "sub : " << std::this_thread::get_id() << std::endl;
        }
    );

    std::cout << "do some on main thread" << std::endl;

    std::cout << "main: " << std::this_thread::get_id() << std::endl;
}

Here is the output:
sub : 139716056966912
do some on main thread
main: 139716056971072

Running demo: https://godbolt.org/z/obzzceGGr
It seems that the main thread waits until finishing the sub thread before outputing "do some on main thread".
I want to know why this behavior happens.
I got the warning message ":6:5: warning: ignoring return value of function declared with 'nodiscard' attribute [-Wunused-result]".
Since C++20, the nodiscard attribute has been added.
See https://en.cppreference.com/w/cpp/thread/async
I guess that I got an undefined behavior due to ignoring the return value of std::async(), but I couldn't find such document, so far.
Comment: On another note, using `std::async` for doing an operation which doesn't return anything is rather useless. For that use plain `std::thread` (or [`std::jthread`](https://en.cppreference.com/w/cpp/thread/jthread)).
Answer: In the second case, a std::future object will still be created and returned.
That object is ephemeral and will be destructed immediately, and that leads to your problem because the std::future destructor will wait for the future to be ready before destruction continues.
Comment: Thans you! I clrearly understand. I wrote another PoC code https://godbolt.org/z/j8b4aY9j9 and confirm the behavior.


XSD : Check order of child elements based on attribute

Question: I am trying to check the order of the child elements in an xml,
My xml is

<col name="name1">test1</col>
<col name="name2">test2</col>
<col name="name3">test3</col>
<col name="name4">test4</col>
<col name="num1">true</col>

and I need to verify if the child elements are getting displayed in the correct order. The child elements in my file all have the same name but different attributes.
<xs:element minOccurs="0" maxOccurs="unbounded" name="col">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name" type ="OrderCheck" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

I would ideally like to do
<xs:complexType name="OrderCheck">
    <xs:sequence>
    <xs:element name="name1" type="xs:string"/>
    <xs:element name="name2" type="xs:string"/>
    <xs:element name="name3" type="xs:string"/>
    <xs:element name="name4" type="xs:string"/>
    <xs:element name="num1" type="xs:boolean"/>
    </xs:sequence>
    </xs:complexType>

For me to be able to use xs:sequence I need to define a xs:complexType but I am not able to define a complexType under the "attribute" type, I can define only a simple type.But I cannot use xs:sequence under simpleType. How can I fix this?
Answer: If you can use XSD 1.1 (implemented in Xerces beta and in Saxon-EE) then you can do this with assertions.
Another technique that can sometimes be useful in cases like this is to implement your validation process as a two-stage pipeline, consisting of a transformation followed by a validation step. The transformation would typically convert
<col name="name1">test1</col>

to
<name1>test1</name1>

and then you have a structure that is readily amenable to XSD 1.0 validation.
Answer: Unfortunately what you want to do is not possible with XSD 1.0. With sequence you can specify the required order of different types, but not the same type with different data.
I believe that Schematron can be used for this.


Idempotent elements of Jacobson Ring

Question: Let $R$ be a Jacobson ring, namely for each element $a \in R$ there exists an integer $n$, $n>1$ such that $a ^ n = a$. How can we prove that an idempotent element of $R$ must be a central element of $R$?
Comment: For future reference, "Jacobson ring" is more commonly used to refer to a ring whose prime ideals are intersections of maximal ideals.  I thought the rings you are describing were called "periodic", but I have found that actually that may be used for a broader class of rings where $x^n=x^m$ for some $n<m$ depending on $x$.
Comment: sorry, I left out $n>1$.
Comment: see https://math.stackexchange.com/questions/67148/if-a3-a-for-all-a-in-a-ring-r-then-r-is-commutative Math Gems's answer.
Answer: You can show that $R$ has no nonzero nilpotents. Indeed, if $a^n=0$ and $a^m=a$, then $a=a^{m^k}$ for any $k$, so taking $k$ large enough so that $m^k>n$ we get $a=a^{m^k}=0$.
Now, in a ring with no nonzero nilpotents, every idempotent is central. To see this, let $x\in R$ and $e=e^2$; we want to show the commutator $[e,x]$ is zero. But $[e,ex]^2=0$ (compute it!), so since there are no nilpotents, this shows $ex=exe$. Similarly $[e,xe]^2=0$, so $xe=exe$. Therefore $ex=exe=xe$ as required.

Idempotent elements of Jacobson Ring


payroll program, need help simply a patterned event, new to python

Question: so i'm learning python and decided to program a payroll for my company as practice.
for the usa bi-weekly  tax, there is pattern to the amount you need to pay, here is a short code for example

<code>    if n >= 760 and n < 780:
       gt = 45
    if n >= 780 and n < 800:
       gt = 47
    if n >= 800 and n < 820:
       gt = 49
    if n >= 820 and n < 840:
       gt = 51
</code>

here n is the salary, and gt is the tax to be paid.
as you can see, the range of n is a constant 20, and tax increase by a constant 2
this is true from 720 - 1000, starting from 1000 however, the rate of the tax increases by constant 3
i want to to be able  to include a salary range from 720 to 2000, is there a way to do this, or do i have to do it the hard way and write them all out?
Comment: If n = 20, won't it always be less than all those numbers? I see you're checking to see if it is or not. I think you might be doing this wrong, or else I'm misunderstanding something
Comment: You mentioned you're learning python; I suggest checking out [project euler](http://projecteuler.net/). It's got a bunch of programming problems on there that I find helpful when learning a new language.
Answer: I'd branch on your two ranges and then use some math to get the tax amount:
<code>if n >= 720 and n < 1000:
    gt = 2*(( n - 720 ) / 20) + 41
elif n >= 1000 and n < 2000:
    gt = 3*(( n - 1000 ) / 20) + 67
</code>
Comment: thanks you! how did you figure the math out? btw, how do i mark this solved?
Comment: To mark it solved click the empty tick mark next to the answer - it should go green. The math I did with some trial and error, but mainly you subtract the starting value from n (720 or 1000) to give 0 at the start of the range, divide by 20 to get 0,1,2,3 etc representing each block of 20, multiply by the step value (2 or 3) to get a sequence of 0,2,4,6 etc and 0,3,6,9 then add on the value at which each range starts.


Change the position on BOX2d Body in Cocos2d-iphone

Question: I have a condition in which i have to continuously move box2d body.
I can guess two ways to move box2d body.

first, what can i do in transformed box2d body to new position
Second way is, I delete the previous body and recreate new one at new position.

Now, I want to know, which is the best way to do this? And also eager to here other way if possible.
Answer: Move the body. Reset the velocities if needed.
Deleting and recreating the body would work, but it would completely reset the body's state and you'd have to create the fixtures and shapes again too. That's overkill.
Comment: the world doesn't have velocities
Comment: That was embarrassing from my side..!


Trying to change the style color of a calendar date when the user clicks on it. The "Style" property changes but won't update the html

Question: I have a calendar that when the user clicks on the date I would like to change the style on the div to show the user that the date has been selected. I am iterating through a list of a CalendarModel and updating the actual style in the list but for some reason my html is not updating and it keeps the default styling.
Here is my code for he page:
@inject IBookingRepository bookingRepository
@inject NavigationManager navigationManager
@inject TimerService timerService

    <CalendarDisabledDays calendarMonth="calendarMonth" offsetDays="offsetDays" />

    @for (int i = 0; i < calendarModel.Count; i++)
    {
        var index = i;

            <button @onclick="() => CalendarHasChanged(index)">@calendarModel[index].Date.Day</button>

    }

    <EditForm OnSubmit="CreateDates" EditContext="editContext">

            <button type="reset" class="btn btn-main" @onclick="ClearDates">Clear Dates</button>
            <button type="submit" class="btn btn-main">Book Dates</button>

            <DataAnnotationsValidator />
            <ValidationSummary />

    </EditForm>

@code {
    [Parameter]
    public int daysInMonth { get; set; }
    [Parameter]
    public bool status { get; set; }
    [Parameter]
    public DateOnly calendarMonth { get; set; }
    [Parameter]
    public int offsetDays { get; set; }
    [Parameter]
    public BookingDatesVM? booking { get; set; }

    private DateTime date;
    private int startDay;
    private bool valid;
    private EditContext? editContext;
    private ValidationMessageStore? validationMessages;
    private List<CalendarModel>? calendarModel;

    public EventCallback<List<CalendarModel>> calendarChanged { get; set; }

    public async Task CalendarHasChanged(int index)
    {
        calendarModel[index].Style = "color:red;";

        await calendarChanged.InvokeAsync(calendarModel);
    }

    protected override async Task OnInitializedAsync()
    {
        editContext = new(booking);
        validationMessages = new(editContext);
        await base.OnInitializedAsync();
    }

    protected override Task OnParametersSetAsync()
    {
        SetStartDate();
        PopulateCalendar();
        return base.OnParametersSetAsync();
    }

    ///
    /// Sets the start day of the month. Used primarily if the selected month is the current month we are in.
    ///
    private void SetStartDate()
    {
        startDay = 1;
        if ((calendarMonth.Month == DateTime.Now.Month) && (calendarMonth.Year == DateTime.Now.Year))
        {
            startDay = DateTime.Now.AddDays(1).Day;
        }
    }

    ///
    /// Sets the date the user selects to the model before saving to the database.
    ///
    /// <param name="date">The selected date.</param>
    private void SetDate(DateOnly date)
    {
        if (status)
        {
            booking.CheckInDate = date;
        }
        else
        {
            booking.CheckOutDate = date;
        }
    }

    ///
    /// Clears the date in the model and sets them to the default MinValue.
    ///
    private void ClearDates()
    {
        booking.CheckInDate = DateOnly.MinValue;
        booking.CheckOutDate = DateOnly.MinValue;
    }

    ///
    /// Saves the selected dates to the database along with the sessionId.
    ///
    /// <returns></returns>
    private async Task CreateDates()
    {
        valid = ValidateForm();
        if (valid)
        {
            await bookingRepository.CreateAsync(BookingMapper.FromDatesVM(booking));
            timerService.ShowTimer();
            navigationManager.NavigateTo("/bookings/info");
        }
    }

    ///
    /// Manual validation of the calendar control used to check whether the dates selected are valid before storing them in the database.
    ///
    /// <returns>True is the dates are allowed and false if the dates have some conflict with them.</returns>
    private bool ValidateForm()
    {
        valid = editContext.Validate();
        validationMessages?.Clear();

        var checkOutDate = editContext.Field(nameof(booking.CheckOutDate));
        var checkInDate = editContext.Field(nameof(booking.CheckInDate));

        if (booking.CheckInDate == DateOnly.MinValue)
        {
            validationMessages.Add(checkInDate, "Check in date is required.");
            valid = false;
        }
        if (booking.CheckOutDate == DateOnly.MinValue)
        {
            validationMessages.Add(checkOutDate, "Check out date is required.");
            valid = false;
        }

        return editContext.Validate();
    }

    private void PopulateCalendar()
    {
        calendarModel = new();

        for (int i = startDay; i <= daysInMonth; i++)
        {
            CalendarModel model = new();
            date = new DateTime(calendarMonth.Year, calendarMonth.Month, i);
            model.Date = DateOnly.FromDateTime(date);
            model.isAvailable = true;

            calendarModel.Add(model);
        }
    }

    public class CalendarModel()
    {
        public string Style { get; set; } = "active";
        public DateOnly Date { get; set; }
        public bool isAvailable { get; set; } = true;
    }
}

Im not sure what is wrong here but the code inside the CalendarHasChanged method is being executed because when I debug it the list item that was clicked on is changed to the "color:red;" string I have set in the method but the html remains the same.
Answer: Once you click the button,you would modify the class attribute of the div, instead of append    style attribute to  your button

    <button @onclick="() => CalendarHasChanged(index)">@calendarModel[index].Date.Day</button>

....
public async Task CalendarHasChanged(int index)
    {
        calendarModel[index].Style = "color:red;";

        await calendarChanged.InvokeAsync(calendarModel);
    }

You have to add a css file name of calendar.razor.css(css isolate) to your page folder
div .targetclass > button {
    // you could modify the color based on your requirement
    color: red;
    background-color: aqua
}

....
public async Task CalendarHasChanged(int index)
{
    calendarModel[index].Style = "targetclass";

    await calendarChanged.InvokeAsync(calendarModel);
}

Result:
Comment: of course that was a huge oversight on my end. Quick question why dobwe have to create the isolation file in the css? Why does this not work with the regular css files?
Comment: It would also work with regular css file,but css isolation would simplify CSS and avoid collisions with other components or libraries


How do I dynamically create a data object from an API in React Native?

Question: I am adding a feature to a React Native app that will give the current time in different places throughout the world. I'm using timezonedb to fetch the country name, zone name etc. Is it possible to create a data object from the API dynamically instead of manually typing in each country as there are several hundred? This is how I want it to look.
  const data = [
    { label: 'Afghanistan Asia/Kabul', value: 0 },
    { label: 'Albania Europe/Tirane', value: 1 },
    { label: 'Algeria Africa/Algiers', value: 2 },
  ];

The data will be used for a drop down menu to select from the various countries/time zones.
import { Text, StyleSheet, View, TextInput, Pressable } from 'react-native';
import { useState, useEffect } from 'react';
import axios from 'axios';
import { ScrollView } from 'react-native';
import TimeZoneDropDown from '../dropdowns/TimeZoneDropDown';

const tzUrl = 'http://api.timezonedb.com/v2.1/list-time-zone?key=myKey&format=json';
const TimeZone = () => {

    const [timeZones, setTimeZones] = useState([])
    const [dayOfWeek, setDayOfWeek] = useState('');
    const getTimeZone = async () => {
        await axios.get(tzUrl)
            .then(res => {
                setTimeZones(res.data.zones.map((z) => {
                    return (
                        z.countryCode
                    )
                }))
            }).catch(err => {
                console.log(err)
            })
    }

    useEffect(() => {
        getTimeZone();

    }, []);
    return (
<Text>
    {timeZones}
</Text>
)

}

export default TimeZone;

Here is an example of the response.
{
    "status":"OK",
    "message":"",
    "zones":[
        {
            "countryCode":"AD",
            "countryName":"Andorra",
            "zoneName":"Europe\/Andorra",
            "gmtOffset":7200,
            "timestamp":1464453737
        },
        {
            "countryCode":"AE",
            "countryName":"United Arab Emirates",
            "zoneName":"Asia\/Dubai",
            "gmtOffset":14400,
            "timestamp":1464460937
        },
        {"
            countryCode":"AF",
            "countryName":"Afghanistan",
            "zoneName":"Asia\/Kabul",
            "gmtOffset":16200,
            "timestamp":1464462737
        }
        .
        .
        .
    ]
}

Any help would be appreciated.
Comment: I want to help you out but im having an issue with getting the api to work on [expo snack](https://snack.expo.dev/)
Comment: I've updated my question to show an example of the response. I didn't include my key in the fetch request as it is paid and I didn't want to post online. Basically I want to take the countryName and zoneName from above and make those the labels in my data object. I also want to increment the value each time dynamically so I can use all of the zones in the API without typing each one out manually. There are a lot of them so I'm trying to find the most efficient way to do this.
Comment: After you do your fetch request you can modify the zone array to fit your needs
Comment: https://snack.expo.dev/nXfbHS5FC
Answer: You can modify the api data to fit however you need it to.
useEffect(() => {
  const getTimeZone = async () => {
    try {
      const res = await axios.get(tzUrl);
      const data = res.data.map((z, i) => {
        return {
          label: z.zoneName,
          value: i,
        };
      });
      setTimeZones(data);
    } catch (err) {
      console.log(err);
    }
  };
  getTimeZone()
}, []);

That would get you  your desired result. If you are using react native dropdown picker then when a selection is made, the only data you would have about the selection would be a number. To get anything else, you would have to find it in timeZones.
An alternative would be to store the zone data as value, have your incrementing logic exist independently:
useEffect(() => {
  const getTimeZone = async () => {
    try {
      const res = await axios.get(tzUrl);
      const data =  res.data.zones.map((z, i) => {
          return {
            label:z.zoneName,
            value: z,
          };
        });
      setTimeZones(data);
    } catch (err) {
      console.log(err);
    }
  };
  getTimeZone()
}, []);

If you are using RNDP, you can use schema to tell it that the label should be zoneName and remove the label from the mapping above
 <DropDownPicker
        {...dropdownState}
        schema={{label:'zoneName'}}
        items={timeZones}
        setItems={setTimeZones}
        min={0}
        max={timeZones.length}
        multiple
/>

A demo
Comment: Ok. Thanks. a lot. I see how this works now. I'm using React Native Element Dropdown so I should be able to make it work.
Comment: https://snack.expo.dev/QlwBYTPk8


Android Studio default XML bool value not being used for managed configuration setting

Question: this is a simple question: I use the Android Mgmt. API for fully managed devices (Android tablets) in the field. Through that, I have numerous managed configuration settings defined in the code. There are some booleans which all default to false EXCEPT one:
<restriction
    android:key="autoLaunch"
    android:title="@string/auto_launch_title"
    android:defaultValue="@bool/auto_launch_default"
    android:restrictionType="bool" />

I'm pretty certain this was working properly when I set it up a year or so ago. Recently, however, I was creating a policy in an MDM I have built, which queries for a Google Managed Config iframe that displays all of the settings.  The field for autoLaunch is defaulting to false.
The bool default value, @bool/auto_launch_default, is defined in res/values/bools.xml:
<bool name="auto_launch_default">true</bool>

I would like to keep using this format if possible.  I'm really just wondering why this is not working anymore, if anyone has any input on this. I do recall that the format of my managed config iframe changed about a month ago, so wondering if something happened with that, also.
Lastly, if I do an enterprises.applications.get for my app, I see the following (for this field, there are others I have set up):
{
      "key": "autoLaunch",
      "type": "BOOL",
      "title": "Auto launch?",
      "defaultValue": false
},

Appreciate the help!
Answer: It seems that the API does not properly parse the defaultValue of BOOL restrictionType when a bool reference is used.
For now, I recommend using either a string reference (<string name="key_string_default">true</string>) or an integer reference (<integer name="key_integer_default">1</integer>), and avoid using bool reference.


Swift: Changing a Parse Object's ACL for a Single User

Question: I've got an app where one user (current user) grants access to his data to another user. The current user enters the user name of the person he wants to grant access to. Here's my code:
var generalInfo = PFObject(className:"ClientData")
generalInfo.objectId = clientIDPassed //This makes sure that I'm changing the right object.
generalInfo.ACL = PFACL.ACLWithUser(newUserEmail.text) //newUserEmail.text is the text field. Error on this line.
generalInfo.saveInBackground()

Here's the error:

Cannot invoke "ACLWithUser" with an argument list of type '(String)'

I'm thinking that my problem is that newUserEmail.text is a string, but Parse is looking for a PFUser. Any idea how to resolve that?
Comment: By passing a `PFUser` object instead of a `String`.
Comment: @nhgrif how do i convert newUserEmail.text to PFUser? This didn't work: userPF = newUserEmail.text as? PFUser didn't work. Thanks!
Comment: I don't know.  Look at some documentation.  I'm assuming you can't just convert a string to a user... that wouldn't make much sense necessarily.
Comment: I'm sorry, my answer was false.. I changed it.
The Installation Table is not accessible from the user.
Answer: You need to pass a PFUser object.
You can login and get the current user by this:
var generalInfo = PFObject(className:"ClientData")
PFUser.logInWithUsernameInBackground(<#username: String#>, password: <#String#>, block: { (user, error) -> Void in
                    if user != nil && error != nil {
                        // user has logged in
                        generalInfo.objectId = clientIDPassed //This makes sure that I'm changing the right object.
                        generalInfo.ACL = PFACL.ACLWithUser(user) // user which is passed by the login function.
                        /*
                           In my parse api (v1.7.1) PFACL.ACLWithUser is not available, instead I have to use:
                           PFACL(user: <#PFUser#>)
                        */
                        generalInfo.saveInBackground()
                    } else {
                        // do your error handling
                        println(error!.localizedDescription)
                    }
                })

In other functions and classes you can use PFUser.currentUser() to get the logged in user. If the user is not logged in, returns nil
If you want to search for a User you do:
var query = PFUser.query()!
query.whereKey("email", equalTo:userNameObject)
query.getFirstObjectInBackground { newUser, error in
  if error == nil {
    println(newUser)
    var userVariable = newUser.objectId as String
  }
}


Compare each pandas row to a dictionary of list and append new variable to the dataframe

Question: I would like to check each row of a pandas dataframe string column and append a new column that returns 1 if any element of the text column is found in a dictionary of list.
Example:
# Data
df = pd.DataFrame({'id': [1, 2, 3],
                   'text': ['This sentence may contain reference.',
                'Orange, blue cow','Does the cow operate any heavy machinery?']},
                 columns=['numbers', 'text'])

# Rule dictionary
rule_dict = {'rule1': ['Does', 'the'],
             'rule2':['Sentence','contain'],
             'rule3': ['any', 'reference', 'words']}

# List of variable names to be appended to df
rule_list = ['has_rule1','has_rule2','has_rule3']

# Current for loop
for Key in rule_dict:
    for i in rule_list:
        df[i] = df.text.apply(lambda x: (
            1 if any(ele in x for ele in rule_dict[Key]) == 1 and (len(str(x)) >= 3)
            else 0))

# Current output, looks to be returning a 1 if text is found in ANY of the lists
df = pd.DataFrame({'id': [1, 2, 3],
                       'text': ['This sentence may contain reference.',
                    'Orange, blue cow','Does the cow operate any heavy machinery?'],
                    'has_rule1': [1,1,1],
                    'has_rule2': [0,0,0],
                    'has_rule3': [1,1,1]},
                     columns=['id', 'text','has_rule1','has_rule2','has_rule3'])

# Anticipated output
df = pd.DataFrame({'id': [1, 2, 3],
                       'text': ['This sentence may contain reference.',
                    'Orange, blue cow','Does the cow operate any heavy machinery?'],
                    'has_rule1': [0,0,1],
                    'has_rule2': [1,0,0],
                    'has_rule3': [1,0,1]},
                     columns=['id', 'text','has_rule1','has_rule2','has_rule3'])

Comment: Note that there is no guarantee in ordering of `rule_dict` when you do `for Key in rule_dict`. That is, you wouldn't know `Key` will come in order of `'rule1', 'rule2', 'rule3'` or `'rule2', 'rule3', 'rule1'` or the like.
Comment: One way is to have `rule_list` also as a dictionary: `{'rule1': 'has_rule1', }` and access both by keys. Another way is to use [OrderedDict](https://www.tutorialspoint.com/ordereddict-in-python). But that also depends on your rules' names.
Comment: @QuangHoang I did not know that, thank you. I had assumed it would be index based. How can I ensure it maintains the order I specify (i.e., 'rule1', 'rule2', 'rule3')?
Answer: Assuming you sorted out the issue regarding dict comprehension mentioned in the comment, you should not use nested for loop. Instead, use a single for loop with zip:
for (k,v), n in zip(rule_dict.items(), rule_list):
    pat = rf'\b{"|".join(v)}\b'
    df[n] = df.text.str.contains(pat).astype(int)

Output:
      id  text                                         has_rule1    has_rule2    has_rule3
--  ----  -----------------------------------------  -----------  -----------  -----------
 0     1  This sentence may contain reference.                 0            1            1
 1     2  Orange, blue cow                                     0            0            0
 2     3  Does the cow operate any heavy machinery?            1            0            1


Asyncio - endless running tasks - modifying pymodbus example

Question: I am working with asynchronous PyModbus server with the refreshing task, everything is asyncio-based and based on pymodbus example code, which can be found here:
https://pymodbus.readthedocs.io/en/latest/source/examples.html#updating-server-example
I am not very experienced with asyncio (just a few tutorial and simple experiments which were working correctly but this is my first attempt in creating anything more complicated) and I think I'm missing something.
In the example there is the asyncio.run(...) called in the __main__ part. However, I want to modify this code and therefore I would like to have the server started outside of __main__, something like this:
async def myFunction(args):
    # do some other stuff
    asyncio.create_task(run_updating_server(run_args))

if __name__ == "__main__":
    cmd_args = get_commandline(
        server=True,
        description="Run asynchronous server.",
    )
    run_args = setup_updating_server(cmd_args)
    asyncio.run(myFunction(run_args), debug=True)

However, this doesn't create a nice, endless running task as in the example, everything is performed just once and that's all, the program finishes.
I don't understand what is the difference and why was the server running endlessly in the example but runs only once in my modification - is there something in create_task() vs run() functionalities that I'm missing?
I have found this topic and tried implementing it with explicit call of the event loop like this:
async def new_main(args):
    asyncio.Task(run_updating_server(args))

if __name__ == "__main__":
    cmd_args = get_commandline(
        server=True,
        description="Run asynchronous server.",
    )
    run_args = setup_updating_server(cmd_args)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(new_main(run_args))
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()

However, in such case I just got Task was destroyed but it is pending! errors...
My second question is: how should I properly implement task to have it endlessly running - the server, the updating function and some other which I want to implement (not related to the modbus server, just running along it and doing their things)? I want to add some tasks to the event loop and have them run endlessly, let's say - one should be executed every 1 second, another one should be triggered by some lock, etc.
I thought that the updating task() in the example was changing the values on the server once every second but after investigating I see that it doesn't - it is just executed once. How can it be modified to behave as mentioned - increment the server values every second?
I guess that's something obvious but lack of experience with asyncio and two days of brainstorming over the whole application made me too dumb to understand what am I missing... I hope you will be albo to guide me to right direction - TIA!
Answer: What you are missing is the await keyword.  An asyncio task without an await expression is almost always an error.
async def myFunction(args):
    # do some other stuff
    t = asyncio.create_task(run_updating_server(run_args))
    await t

There is a huge difference between this function and the one in your code.  Both functions create a task.  Your code is then finished.  It immediately exits and your program ends.  The function given here awaits completion of the newly created task.  It doesn't progress past the await expression until the task run_updating_server is complete.  The program will not exit until myFunction ends, so the program keeps running until the task finishes.  If the task is an infinite loop, the program will run forever.
You say you want to do other things in addition to running this server.  Probably each of those other things should be another task, created before the server.  You don't have to await on these tasks unless you want one (or more) of them to finish before the server starts.  I'm not sure of what else you want to do, but the point of my answer is that your main task has to await something to keep the program from exiting immediately.
Comment: Thank you, this answers one of my problems - I really had to be tired with this code if I didn't see the missing await...
And what about running tasks infinitely? What is the cleanest way to do this? I have the server up and running and now I would like to have the updating task executing every second, etc - how should I add this tasks to the loop to have them infinitely executing?
Comment: I thought that the `aiocron` module would solve my problem but I investigated further and I have a feeling that it's functionalities are a bit too limited for the case... So my problem still exists - how to add tasks to be executed every x seconds? And finally, how to stop all this stuff when closing the app? I've ended with asking a [new question](https://stackoverflow.com/questions/75309090/asyncio-run-tasks-cyclically-and-politely-stop-them-with-ctrlc) to clarify the problem...


Can you breed baby Dittos?

Question: I rather need an army of Dittos of different natures, but capturing them is annoying what with their high levels and rare appearances.
Can I stick 2 Dittos in the Day Care and make new ones?
Comment: You know, you don't have to breed with Dittos to get the nature.  Ever since HeartGold/SoulSilver if either parent is holding the everstone, their child inherits that Nature [citation](http://www.pokecommunity.com/showthread.php?p=5667076)
Comment: @tzenes I thought it was the Ditto or Female parent, but not Male non-Ditto parent.  Even so, however, an army of various-natured Dittos will come in handy for future breeding as well.
Comment: How I got my "ditto breeding army": bought Emerald version,spent 2days in the fossile maniacs cave on route 114, spent a week transfering them to Platinum->HG->Black
Answer: No, Dittos cannot breed with other Dittos.
Comment: @Raven Dittos are never created or destroyed, they only change form. Thus sayeth the Law of Conversation of Ditto.
Comment: *sigh* This game is really trying to make me waste a lot of my time.
Comment: @Strix If you have a 4th gen game, it may be faster to farm a bunch from there and then just transfer them over. To recollection, the ones in D/P are pretty easy to catch and chain.
Comment: @Raven Mitosis?
Comment: @Arkive They do look a little like amoebas...
Comment: If Dittos cannot breed with other Dittos... how the hell do they propagate?

Can you breed baby Dittos?


Numerical solution of heat equation on periodic domain

Question: Consider the steady heat equation $\nabla\cdot(k(x) \nabla u)=f$ in two dimensions on a periodic domain, say $[0,1]\times[0,1]$. My goal is to solve it numerically with standard central 5-points stencils. Due to the periodicity, the solutions are not unique and the corresponding linear system of equations, $AX=b$, is singular with rank-1 kernel (which contains constant grid functions). I know that the system is solvable since the data $f$ fulfills the solvability condition.
How should I find the solution of the system? In my previous work, I had constant $k$, so I could find the solution using discrete Fourier transform very efficiently, but it does not work here. I tried some iterative methods such as GMRES and Gauss-Seidel but they do not seem to work well.
Answer: Funny enough I just concluded a year-long project on a similar problem, for the unsteady case with the source term also specially varying. I used finite volume schemes in OpenFOAM to solve the problem, the frame-work in OpenFOAM is suitable for these sorts of computations, particularly if you want to play with the domain geometry as well.
In any case id say give finite volume methods a try.
Comment: Tnx. Reading your answer, it came to me that perhaps solving the unsteady case (which goes to the steady solution asymptotically)  de-singularize the matrix $A$. Or even I may be able to use explicit methods for that. What do you think?
Comment: That is correct. Explicit methods are certainly easier to handle from my experience. If you want to do it this way, you can include a time-stepping termination condition which stops the program when the temperature fields reach a steady solution.
Comment: I already did that and it works! Tnx a lot :)
Comment: Perfect! Out of curiosity what program are you using?


Can I access memory location and values ( pointers and reference ) for variables in a loop, in Python 3

Question: my_num_1 = 10
my_num_2 = 20

# I want to assign value 5 to above two variables like this:

for num in [my_num_1, my_num_2]:
    num = 5

That won't work. So is there a way to do something like this pseudo code:
for num in [(address_of)my_num_1, (address_of)my_num_2]:
    (value_at)num = 5

The code and application is terrible I know. But is there a way to play around with pointers and (de)referencing in Python like this?
Comment: Yes, there is, the `ctypes` module. You don't want to do that, you want to use a dictionary.
Comment: with [`id`](https://docs.python.org/3.9/library/functions.html#id) you get "This is the address of the object in memory"
Comment: TLDR: You're in the wrong language for that kind of stuff
Answer: Assuming you're a beginner to Python
What you want is a dictionary or a list. Use a dictionary if you need the variable names, but in this case a list is probably a better idea.
Dictionary sample implementation:
nums={
    "my_1": 10,
    "my_2": 20,
} #Create a dictionary of your nums

print(nums["my_1"]) #10
print(nums["my_2"]) #20

for num in nums: #Iterate through the keys of the dictionary
    nums[num] = 5 #and set the values paired with those keys to 5

print(nums["my_1"]) #5
print(nums["my_2"]) #5

List sample implementation:
nums = [10, 20] #Create a list and populate it with your numbers

print(nums[0]) #10
print(nums[1]) #20

for num in range(len(nums)): #Keys for your list
    nums[num] = 5 #Set the values within the list

print(nums[0]) #5
print(nums[1]) #5

Assuming you're a moderately advanced programmer
You can mutate the globals() dict.
my_num_1 = 10
my_num_2 = 20

print(my_num_1) #10
print(my_num_2) #20

for name in ("my_num_1", "my_num_2"): #Iterate through a tuple of your names
    globals()[name] = 5 #and mutate the globals dict

print(my_num_1) #5
print(my_num_2) #5


how do I RDP to Ubuntu 16.04 from windows

Question: how do I RDP to Ubuntu 16.04 from windows?
Answer: I believe this is a duplicate of a few other posts. You can use xRDP to rdp into your linux workstation. If you are looking to use rdp and log in to a Unity desktop, perform the following:

Install TigerVNC
Install xRDP
Configure preferred desktop to be used in xRDP

Full Instructions on how to perform this can be found at http://c-nergy.be/blog/?p=9962
Also see How to use xrdp with Unity on Ubuntu 16.04 LTS?


Grounding nightmare

Question: Please don't laugh (too much), but maybe someone can tell if this is safe or not? It looks at best a total bodge job to me, and at worst downright dangerous, but I don't know what I'm on about to be honest.
My wife and I live in a pretty old building, not especially well maintained, and have been feeling very mild electric shocks from our bathroom sink. We called in an electrician (friend of a friend, but still a pro... apparently) to check it out. He said the problem probably wasn't originating in our apartment, but he couldn't know for sure without ripping the walls down. He did this (see images), and said it's a safe temporary solution. His idea, as far as I understood, was to ground the sink to the back of the washing machine.
I guess I should call in an actual pro right? Any advice would be much appreciated.
Comment: Contact the building management and have them figure out why _their_ plumbing wants to kill you. In the meantime, don't touch the problem plumbing and label it so that no one else does. Aside: Note that unplugging the appliance (Washing machine?) removes the ground "connection".
Comment: It looks like the sink drain connection is a flexible hose that is unlikely to carry a current.  That would mean that either the supply lines are hot (and the current is carried by the stainless braid) or that the sink is mounted to a current source, e.g. someone ran a screw into a cable. I can't tell whether the sink is metal or ceramic, but my guess would be that the supply lines are making the faucet "hot".
Comment: ...continued from above.  As a brilliant young electrical engineer at about age 12 (LOL, kidding), I fixed it by connecting the supply to the metal (galvanized) drain line. Yeah, it was also a hack, but we had little money to hire an electrician. Eventually replaced the water heater and main panel when my dad's business became more successful.
Comment: The sink is ceramic. What would you suggest we do?
Comment: @HABO agreed, grounding the drain seems worthless, like you said, most likely the supply. In fact, grounding the drain could make things worse.   If the supply is really hot, (not just leakage current), and the OP had one hand in the sink and the other on the faucet, that would be a direct path to ground "better" than before... but far worse for the OP. The house I grew up in had an electric water heater which became defective and leaked current into the supply.  The house had an old fuse panel (Yes actual fuses), poor grounding and we'd get shocked at times at the kitchen sink. ...continued.
Comment: Thanks for the help and suggestions. I'm keeping the appliances disconnected for now, and will wait for a professional to come check it out.
Answer: No!  That's not safe at all.  Please disconnect power to the application at the panel and call for a qualified and licensed electrician to sort this out.
I'm especially concerned by the routing of the dubious ground wire along the edge of what looks like your shower.  If that gets "HOT" due to some fault and you drip some water, it may be lethal!
Comment: Yes it's our shower. I've disconnected the washing machine and all other electrical appliances in the bathroom, and will call an electrician now. Thanks.
Comment: Deleted previous version of this comment bc I was wrong. It is dangerous but not why jwh20 said. See my above comment on the OP. The dubious ground wire is at least insulated. But as I said above, grounding the sink drain could make it worse.  And jwh20, you are right, a real pro electrician will need to sort this out.

Grounding nightmare


Check if element has transition set in CSS using JavaScript

Question: I have a transition set:
element.one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
    scrollActive = false;
}).css({
    '-webkit-transform': '' + prop + '(' + value + 'px)',
    '-ms-transform': '' + prop + '(' + value + 'px)',
    'transform': '' + prop + '(' + value + 'px)'
});

and in CSS:
.element {
    transition: transform ease-in-out 0.3s;
}

If I don't have transition set in CSS, the transitionend event will never fire.
Is there a way to check if element has transition set?
Comment: `window.getComputedStyle(element);`
Comment: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
Answer: Try to use getComputedStyle().getPropertyValue() here. The default value of transition is all 0s ease 0s, if not applied in an element

var elem = document.querySelector(".element");
var style = window.getComputedStyle(elem, null).getPropertyValue("transition");
if (style === "all 0s ease 0s") {
  console.log("Not set");
} else {
  console.log("Set");
}
.element {
  transition: transform ease-in-out 0.3s;
}

Answer: Window.getComputedStyle()
 const styles = window.getComputedStyle(element);

 const hasTransition = styles.transition !== "all 0s ease 0s";

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

The Window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain.  Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.

WARNING: This function is very expensive to calculate.


Remove "\N"s when doing SELECT INTO OUTFILE

Question: I'm doing a SELECT INTO OUTFILE and it's showing a "\N" for every NULL value. Is there any way for me to make it just be blank instead?
I'm on MySQL.
Answer: You can use the COALESCE function something like this:
COALESCE(yourfield, '')

Comment: any alternative if i have to perform `SELECT * INTO OUTFILE`?
Answer: Good question, and as relevant today as it was in 2011. I use a stored procedure for this, wich takes the name of a table as argument. Subsequently, it converts all null-values to empty strings (''), using a prepaired statement and no cursors, for cursors are so non-SQL. I've tested it with a table with some 200 columns and a resulting prepaired statement that's about 15,000 characters long:
CREATE DEFINER=`root`@`localhost` PROCEDURE `ExportFixNull`(
   in tblname tinytext)
BEGIN

set @string=concat(
    "Update ",@tblname," set ",
    (
        select group_concat(column_name,"=ifnull(",column_name,",'')")
        from information_schema.columns
        where table_name=@tblname
    )
    ,";"
 );

prepare s1 from @string;
execute s1;
drop prepare s1;

In the main SQL-file, there is a statement
SET @@group_concat_max_len = 60000;

that might be crucial.
More details (in Dutch): http://wiki.devliegendebrigade.nl/SELECT_INTO_OUTFILE_%28MySQL%29
Regards,
Jeroen Strompf


Receptacle flush to the paneling

Question: Can the following receptacle be flushed evenly with the paneling or does it have to be extended outward (using an extension depth ring)?? This has been like this for forty years in a couple of locations of the house and if so do i need to change it to be extended beyond the paneling? And if so would a depth extension ring be okay for that purpose or what would you suggest? As it is now, is it  acceptable to NEC standards? Again this was passed when i bought the house. I want to do things right for my house thanks to you guys and gals? In short does the wall plate/receptacle need to be extended out beyond the paneling like this last picture?
Comment: There is nothing to prevent you from recessing it or making it flush.  The reason the cover is typically on the wall instead of in the wall is to hide the hole.  It is hard to make the hole look clean and finished.  The cover plate hides the opening and makes it look neat (and protects the edges of the hole).  Given the large existing hole, you could use an oversized cover to cover it, or molding to serve as a "frame" to neaten it up.
Comment: I have used two different types, a blue plastic Carlon from HomeDepot and and a softer white plastic type from an electrical supply.  I prefer the latter one for the case where the hole in the wall is too large (what you have), but both can be made to work.  Not exactly this but similiar https://www.amazon.com/Arlington-BE1-5-Electrical-Outlet-Extender/dp/B007EMA6CY?th=1
Comment: The video below says NEC compliant. If you look at youtube videos showing installation of extensions you do **not** have to unhook the wires from the receptacle, but of course you do have to turn off the power at the breaker, completely unscrew the upper and lower screws holding the receptacle in place, and pull the receptacle out . https://www.youtube.com/watch?v=SgWbrfalwjA
Comment: Before you do this you should have in hand the extra large cover plates and check to see that they will cover the extra large rectangle in the paneling and that they fit your receptacle shape. Then you should have a package of the plastic shims because if you use the Arlington extenders, the fins might not be large enough to bridge across the top and bottom gaps and you will need to use shims under the extender box fins to provide a firm physical connection. The top and bottom fins don't need shims if the wall around the box is close but if there is a large gap they need support of shims.
Comment: Here is an alternative to the shims. If the wall is non combustible, then this would be all that one needs. However if the wall material is combustible, then the box extender would be needed on top of this repair ring  as a barrier to prevent a fire in the box from spreading to the wall paneling.  https://www.youtube.com/watch?v=dOZZRykKdfM
Comment: Since the outlets look to be on there side is it possible that they are old work boxes? If they are old work boxes they can be adjusted and a oversized cover plate used.
Comment: If you use an oversize cover to cover the hole in the paneling, you will have to shim out the receptacle or it would be springy. If you do this, you "should" use a box extender so that the flammable paneling would be isolated from the contents of the box.
Comment: Any particular box extenders that you can name that would be easy to attached to a metal handy or gang box? I prefer to have it extended.
Comment: Arlington sounds good and is this NEC  ACCEPTABLE with metal outlet? Sorry for being hooked up on NEC-- it is just to ensure that Im in compliance. Again thank you Jin
Comment: I like all of the ideas especiallly the simplicitic one of the raco flush fit device leveling plate. Will try your suggestions. Thank you
Answer: Before you purchase the extenders you should have in hand the extra large cover plates and check to see that they will cover the extra large rectangle in the paneling and that they fit your receptacle shape.
These extra large extenders might be all you need.
But you should have a package of the plastic shims and/or the RACO sheet metal ring support because if you use the Arlington extenders, the fins might not be large enough to bridge across the top and bottom gaps and you might need to use shims under the extender box fins to provide a firm physical connection. The top and bottom fins don't need shims if the wall around the box is close but if there is a large gap they need support of shims or the RACO sheet metal flush fit device.
Arlington box extender
sheet metal ring support
Comment: Appreciate the support--will get both and see. Tha k you
Comment: Larry, @larry pinsky, the way you express agreement or thanks on this site is to "upvote" an answer or a comment. Put the mouse pointer on the up arrow on the left and click on it.

Receptacle flush to the paneling


Generators in ES6

Question: I have created a function to generate fibonacci series using es6 generators:
//WARNING CAUSES INFINITE LOOP
function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
      [current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

The above function doesn't swap the two numbers while if done normally in any other function swaps the two. On running this function I get an infinite loop.
Why doesn't the variable swap work?
Answer: You've got a syntax mistake: a missing semicolon makes the engine parse your statement as
yield (current [ current, next ] = [ next, current + next ])
//             ^        ^
// property access    comma operator

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `:
function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
    ;[current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

Comment: We should only allow people who understand ASI to omit semicolons :D
Answer: You have to first swap and then yield.
Yield will give control back to the caller, so the method kindad stops executing there..
This will work (tested in Firefox
function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    [current, next] = [next, current + next];
    yield current;

  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

Generators in ES6


Why does the limit for $\lim \limits_{x \to 0} x^{-2}(x-3)^3$ not exist?

Question: I have been told that the limit of $\lim \limits_{x \to 0} x^{-2}(x-3)^3$ does not exist.
However, it seems to me that after two applications of l'Hôpital, the limit should be $-9$
$$\lim \limits_{x \to 0} {{(x-3)^3}\over{x^2}}$$
$$\lim \limits_{x \to 0} {3{(x-3)^2}\over{2x}}$$
$$\lim \limits_{x \to 0} {6{(x-3)}\over{2}}=-9$$
What am I doing wrong?
Comment: https://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule You don't have $\lim_{x\to 0} (x-3)^3 = 0$, and thus don't satisfy the assumptions.
Comment: Using L'Hospital this way would give $\lim_{x\to0}\frac{x+1}x=1$ !?
Answer: You are applying L'Hopital's rule to a quotient which is not an indeterminate form, since $\lim_{x\to0}(x-3)^3=-27$.
As a simpler example, consider$$\lim_{x\to0}\frac{x-1}{x-2}.$$I suppose that you agree that this limit is $\frac12$. But if you apply L'Hopital's rule, then you will get $1$.
Comment: Well, it *is* $-\infty$. The limit doesn't exist in $\mathbb{R}$.
Comment: So why is is not simply $-\infty$ if the denominator approaches $0$?
Comment: @agblt I've added more details. I hope that this will make things clearer.
Answer: You cannot use L'Hôpital because $(x-3)^3$ doesn't go to 0 as $x\to0$.
In order to use L'Hôpital, you need that both the numerator and denominator go to $0$ or $\infty$ as $x\to0$.
This limit does not exist because the numerator goes to $-27$ and the denominator goes to $0$. Thus, the function is not bounded and the limit does not exist.
Answer: This is a proper rational function (i.e., a quotient of two polynomials with no common factors), and for these types of functions, finite limits fail to exist wherever they are undefined (i.e., whenever the denominator vanishes). This happens because for these types of rational functions, the numerator approaches a nonzero quantity while the denominator approaches zero at the point where they fail to exist, so that the quotient approaches $\pm\infty$ at such points, the appropriate sign of $\infty$ depending on other factors.
L'hopitals is useful only for calculating indeterminate limits; i.e., when both numerator and denominator approach $0,$ or both approach $\pm\infty,$ like the (improper) rational function $$\frac{x-1}{x-1}$$ near $1,$ for example, where both terms approach $0,$ but L'hopitals is not actually needed here since this is the function that is constantly $1$ everywhere except $1,$ where it is not defined. Thus, the limit at $1$ is obviously $1$. However, L'hopitals is used for cases where such observations are not so obvious; i.e., non-elementary indeterminate limits.