text:
Q: Drag and Drop for Semantic-UI-React component with Packery (masonary) layout I am working on a card-based UI with brick layout. I am using semantic-ui-react for the card components and react-packery-component for the masonary layout.
My react component is this.
import React from 'react';
import DisplayHomePageCardStructure from
 './DisplayHomePageCardStructure.jsx';
import {Grid} from 'semantic-ui-react';
const Packery = require('react-packery-component')(React);

let packeryOptions = {
 // transitionDuration: 0,
    gutter: 20
};

class DisplayHomePageCard extends React.Component {
constructor() {
    super();
}

render() {
    /* Getting the values from Mongo db*/
    let Data = this.props.display.map(function(item) {
        return (
            <Grid.Column>
              <DisplayHomePageCardStructure id={item.id} displayImage=
                {item.displayImage}
              heading={item.heading} question={item.question} postedBy=
                {item.postedBy}
              addedOn={item.addedOn} category={item.category} upVotes=
                 {item.upVotes}
              downVotes={item.downVotes} answerCounts={item.answerCounts}  '
                  views={item.views}
              profileImage={item.profileImage}
            />
          </Grid.Column>

        );
    });
    return (
      <Packery
        elementType={'div'} options={packeryOptions} className = 'packery'>
          {Data}
        </Packery>
    );
  }
}
DisplayHomePageCard .propTypes = {
   display: React.PropTypes.func
 };
module.exports = DisplayHomePageCard;

As explained in https://github.com/eiriklv/react-packery-component, I'm getting the masonary layout as expected, similar to http://www.hearsay.me/.
I now want to implement drag-and-drop of my cards, somrthing functionally similiar to http://packery.metafizzy.co/draggable.html#jquery-ui-draggable
I need advice on how to achieve this. Can it be done via React only (without JQuery)? If I need to use JQuery, how should I do it?

A: You can implement it via react only relatively simply using react-dnd library.


text:
Q: Proper file transclusion for classic JScript I want to have something like C's #include directive or Python's import() function. I would appreciate it if you consider that this is not a Javascript, VBScript, nor a JScript.Net question. I want the functionality in the JScript .js files run by cscript.exe/wscript.exe. Not the JScript/JavaScript in HTA's run by mshta.exe. The closest thing I could find so far is from here:
function Include(jsFile) {
    var fso, f, s;
    fso = new ActiveXObject("Scripting.FileSystemObject");
    f = fso.OpenTextFile(jsFile);
    s = f.ReadAll();
    f.Close();
    return(s);
}

that requires the user to invoke eval(Include("File.js")) which is not desirable for me. I prefer a solution where I can have a clean include() function. Here are what I have found so far:

*

*If JScript had a function similar to VBScript's ExecuteGlobal, then the problem would be easily solved. Sadly JScript only has the eval() function that executes the input string in the local scope. I tried return eval(<commands>) in the above function to no avail.

*If it was possible to include XSLT in WSH's .wsf/.wsc files, then one could potentially define the include() function on XML level something like (sorry, I don't know XML/XSLT, and this is just pseudocode)

<xsl:function name="JS:include">
    <xsl:param name="fileName"/>

</job>
</package>

Next a sample XML, with an Epoch @dt in each row.
<xml>
    <row id='123' dt='1605666152744'/>
    <row id='234' dt='1605766152744'/>
    <row id='345' dt='1605866152744'/>
</xml>

Then the XSL that calls the javascript extension object "dt".  Note that you have to declare the namespace at the top of the XSL.
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:dt="urn:dt" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:param name='testparam'/>
<xsl:variable name='list' select='//row'/>

<xsl:template match='/'>

Test XSL with Date Extension - <xsl:value-of select='$testparam'/>

                Name
                Date

            <xsl:for-each select='$list'>

                    <xsl:value-of select='@id'/>
                    <xsl:value-of select='dt:DateParse(  @dt )'/>

            </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

Finally the result, note the formatted dates, from the Epoch Dates.

Test XSL with Date Extension -

                                Name
                                Date

                                123
                                11/17 21:22

                                234
                                11/19 1:9

                                345
                                11/20 4:55

redpajama_set_name: RedPajamaStackExchange


text:
Q: enable ethernet on ubee router I am trying to enable ethernet on my ubee Time Warner router.enter image description here
I can connect via wireless and everything works fine, when I use wired I get not DHCP address and the lights on the back don't light up when connected.
If I reset the router, the ethernet lights on the back (and the connected devices) light up briefly.
Tried two devices and two cables.


text:
Q: Is $\overline{T(\overline{B_X})} = \overline{T(B_X)}$? Let $T$ be a continuous linear functional from Banach space $X$ to Banach space $Y$. Is it true that  $\overline{T(\overline{B_X})} = \overline{T(B_X)}$? Here $B_X$ denotes the open unit ball of $X$, and the overline denote the closure operation (in respective strong topologies).
It seems obviously true by a diagonal argument, but I need a rigorous proof.

A: Yes.  If $x_n \in \overline{B_X}$, $y_n = (1 - 1/n) x_n \in B_X$, and $\|T(x_n) - T(y_n)\| \to 0$, so if $z = \lim_{n \to \infty} T(x_n)$ then $z = \lim_{n \to \infty} T(y_n)$.

A: This is true in a general context. Let $X,Y$ be two topological spaces and $f:X\to Y$ be a function. Then, $f$ is continuous if and only if $$\forall A\subseteq X  \hspace{15mm}  f(\overline{A})\subseteq \overline{f(A)}$$ Thus, if $f$ is continuous, then for any $A\subseteq X$ we have $\overline{f(\overline{A})}\subseteq \overline{f(A)}$. Also, by the properties of images and closures: $$f(A)\subseteq f(\overline{A}) \Rightarrow \overline{f(A)} \subseteq\overline{f(\overline{A})}.$$ We get $\overline{f(A)}=\overline{f(\overline{A})}$ for all $A\subseteq X $.


text:
Q: How many numbers between 1-10000 cannot be divided by 2 or 3?
*

*I know that $5000$ are divisible by $2$ and $3333$ are divisible by $3$, but this will include repeats.

*I figured out that for numbers divisible by $3$, $1/3$ of them are divisible by $2$, so for the numbers divisible by $3$ that aren't divisible by $2$ will be $2222$.

$5000$ + $2222$ = $7222$ are divisible by $2$ or $3$, giving a final answer of $2778$.
What do you guys think $?$.

A: Let $M_d = \{\text{integers } n \text{ divisible by } d \text{ such that } 0 < n \leq 10\,000 \}$. Then you're looking for the size of the complement of the set $M_2 \cup M_3$. But, as you've observed, these sets overlap. In fact,
$$
| M_2 \cup M_3 | = | M_2 | + | M_3 | - | M_2 \cap M_3 |.
$$
What about that last term? You want numbers divisible by $2$ and by $3$, namely those divisible by $6$. (In general, a number is divisible by integers $a$ and $b$ if and only if it's divisible by $\operatorname{lcm}(a, b)$.)
So, $M_2 \cap M_3 = M_6$, and
$$
| M_2 \cup M_3 | = | M_2 | + | M_3 | - | M_6 |.
$$
How big are these sets of multiples? As you've implicitly indicated in your question,
$$
| M_d | = \biggl\lfloor \frac{10\,000}{d} \biggr\rfloor,
$$
where $\lfloor x \rfloor$ is the floor function that rounds numbers down to the greatest integer $m$ satisfying $m \leq x$. Can you put this all together? Try it yourself before revealing the spoiler:

\begin{align} | (M_2 \cup M_3)^{\mathrm{c}} | &= 10\,000 - | M_2 \cup M_3 | \\ &= 10\,000 - \bigl( | M_2 | + | M_3 | - | M_6 | \bigr) \\ &= 10\,000 - \biggl\lfloor \frac{10\,000}{2} \biggr\rfloor - \biggl\lfloor \frac{10\,000}{3} \biggr\rfloor + \biggl\lfloor \frac{10\,000}{6} \biggr\rfloor \\ &= 10\,000 - 5000 - 3333 + 1666 \\ &= 3333\end{align}

A: How do you figure that "for numbers divisible by $3$, $1/3$ of them are divisible by $2$"? I get $1/2$.
You didn't say but I'm guessing that your "between" is inclusive, so that the number $1$ is included in the count. You could use the in-and-out formula $|A\cup B|=|A|+|B|-|A\cap B|$ but you don't have to.
Observe that, of any six consecutive integers, exactly two of them are divisible neither by $2$ nor by $3$. Now $10000=1666\cdot6+4$, i.e., $1666$ groups of six consecutive integers, plus four at the end. To make things easy look at the four numbers at the little end: $1$, $2$, $3$, $4$. Only one of them (namely $1$) is good, so the final answer is $1666\cdot2+1=\boxed{3333}$. If you're a Big-Endian, of the four numbers at the big end, $9997$, $9998$, $9999$, $10000$, only one of them (namely $9997$) is divisible by neither $2$ nor $3$, so you get the same answer.


text:
Q: Purpose of Includes directory in Magento, Shell Directory, Api.php and get.php i'm new in Magento, please let me know what is basic purpose on Include directory in Magento and how it's work? and also i want to know about Shell directory, Api php file in root directory of magento and get php file also in root directory. Can anyone explain it's confusing me.
Thanks

A: *

*includes directory is used for storing compiled code and config of Magento Compiler (see System > Configuration > Tools > Magento Compiler)

*shell directory is used for CLI tools to perform maintenance tasks from command line, script names located there are self-explanatory

*api.php is used for API requests from various integrations (i.e. ERP system or POS terminals)

*get.php is used when you store media files in database instead of filesystem. It can be useful if you have multiply backends or host a huge shared Magento install like "Magento Go"


text:
Q: How do I convert date time string with milliseconds to datetime in Ruby? I try to parse a date time string with milliseconds to datetime
DateTime.strptime('20190221095838258727','%Y%m%d%H%M%S%6N')

If I run the example above in the ruby console (Ruby 2.5.1) I get following error
2.5.1 :021 > DateTime.strptime('20190221095838258727','%Y%m%d%H%M%S%6N')
Traceback (most recent call last):
        2: from (irb):21
        1: from (irb):21:in `strptime'

According to the strptime documentation I am not able to find the allowed format specification so I use the format specification of the strftime function as you can see above.
If I leave %6N format out the datetime will created successfully
2.5.1 :022 > DateTime.strptime('20190221095838258727','%Y%m%d%H%M%S')
 => Thu, 21 Feb 2019 09:58:38 +0000


text:
Q: Unable to install typescript on windows 10 i am try to install typescript through CMD in Windows. But i am getting these errors:
npm ERR! pna.nextTick is not a function
npm ERR! asyncWrite is not a function

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\deepu\AppData\Roaming\npm-cache\_logs\2018-10-10T11_17_39_169Z-debug.log

A: This worked for me
rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/bin/node
rm -rf /usr/local/bin/npm
n 10.9.0
node -v
npm -v


text:
Q: Elements floating over each other even though they're blocks? So front-end design isn't really my forte...
I'm attempting to have every post/my main header/logo take up 100% by 100% which works. But I'm also trying to have certain elements positioned within the parent element, also which I have done, but when the site gets resized down the elements tend to just float over on top of one another.
Is there a way I can go about making it so each element acts as a block to prevent the float?

 body {
  font-family: 'Raleway', sans-serif;
 }

 /* Article/Content */
 div.article {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
 }
 div.article p {
  font-size: 100%;
  font-family: 'Open Sans', sans-serif;
 }
 div.article div.datetime {
  font-family: 'Open Sans', sans-serif;
  position: absolute;
  top: 20px;
  left: 20px;
  display: inline-block;
 }
 .hookers {
  vertical-align: middle;
     font-size: 700%;
     color:#CFD8DC;
     letter-spacing: -2px;
     font-weight: bold;
     text-shadow: 1px 1px #78909C,2px 2px #78909C,3px 3px #78909C,4px 4px #78909C,5px 5px #78909C,6px 6px #78909C,7px 7px #78909C,8px 8px #78909C,9px 9px #78909C,10px 10px #78909C;
 }

 /* Misc */
 .noselect {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
 }
<link href='https://fonts.googleapis.com/css?family=Raleway:800' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

 WELCOME

Posted on <?= date('Y-m-d'); ?> at <?= time(); ?>

The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.

A: On div.article, set it to position: absolute;
Then set the child blocks to position:relative;.
Finally, position the block inside the div using top, bottom, left and right. The blocks will position relative to the absolutely positioned parent container.
CSS:
body {
    font-family: 'Raleway', sans-serif;
}

/* Article/Content */
div.article {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    position: absolute;
}
div.article p {
    font-size: 100%;
    font-family: 'Open Sans', sans-serif;
}
div.article, div.datetime {
    font-family: 'Open Sans', sans-serif;
    position: relative;

    display: inline-block;
}
.hookers {
    vertical-align: top;
    height: 100%;
    width: 100%;
    display:block;
    text-align: center;
    font-size: 700%;
    color:#CFD8DC;
    letter-spacing: -2px;
    font-weight: bold;
    text-shadow: 1px 1px #78909C,2px 2px #78909C,3px 3px #78909C,4px 4px #78909C,5px 5px #78909C,6px 6px #78909C,7px 7px #78909C,8px 8px #78909C,9px 9px #78909C,10px 10px #78909C;
}

/* Misc */
.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

HTML
<link href='https://fonts.googleapis.com/css?family=Raleway:800' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

    WELCOME

Posted on <?= date('Y-m-d'); ?> at <?= time(); ?>

The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.

Fiddle


text:
Q: IBM Worklight 6.1 - Direct Update on iOS fails with Update Failed - Failed processing application update file For iOS devices, the Direct Update flow is triggered but fails when unpacking the update archive.
Note that for Android devices, the process works correctly and updates are pushed to the client apps successfully.
The Direct Update prompt is triggered correctly when checksums between the content of initial installed .ipa build is different than new uploaded .wlappp to AppCenter.
Both AppCenter server and WL client logs show the connections is ok and package download successful.
The process failes when unzipping the updated resource package with logged error : "Fatal error updating application. Can't open downloaded zip file." (below and attached).
We have tried both alternatives with same outcome.

*

*Enabling the flag in initOptions.js

connectOnStartup : true,
onConnectionFailure: function (){alert("Worklight server connection failed. Direct Update is not possible.");wlCommonInit();},

*

*Triggering connect in wlCommonInit()

WL.Client.connect({
    onSuccess: function(){WL.Logger.error("OK");},
    onFailure: function(){WL.Logger.error("FAIL");}
});

iOS Logs:

2014-08-09 10:25:28.974 SMC[1500:60b] [INFO] [wl.client] WL.Client.connect onConnectSuccess ENTERING
2014-08-09 10:25:28.981 SMC[1500:60b] [DEBUG] [NONE] wlclient connect success
2014-08-09 10:25:29.096 SMC[1500:60b] THREAD WARNING: ['Notification'] took '107.535889' ms. Plugin should use a background thread.
2014-08-09 10:26:19.976 SMC[1500:60b] [ERROR] [NONE] Update checksum is 3782542690
2014-08-09 10:26:19.988 SMC[1500:60b] THREAD WARNING: ['NetworkDetector'] took '13.082031' ms. Plugin should use a background thread.
2014-08-09 10:26:19.990 SMC[1500:60b] [ERROR] [NONE] In Progress checksum is 3782542690
2014-08-09 10:26:20.002 SMC[1500:60b] THREAD WARNING: ['NetworkDetector'] took '11.927979' ms. Plugin should use a background thread.
2014-08-09 10:26:20.004 SMC[1500:60b] [DEBUG] [NONE] Request [https://{appceneter_hostname}:443/worklight/apps/services/api/SMC/iphone/setup]
2014-08-09 10:26:20.014 SMC[1500:60b] THREAD WARNING: ['NetworkDetector'] took '10.286133' ms. Plugin should use a background thread.
2014-08-09 10:26:20.041 SMC[1500:60b] Requesting bytes starting from 0
2014-08-09 10:26:20.042 SMC[1500:60b] THREAD WARNING: ['WebResourcesDownloader'] took '25.979004' ms. Plugin should use a background thread.
2014-08-09 10:26:20.106 SMC[1500:60b] Start downloading update file.
2014-08-09 10:26:20.110 SMC[1500:60b] Temp update file is /var/mobile/Applications/2DEEED98-E567-4ABB-AD41-BE74EF28A014/Library/tempUpdateFile
2014-08-09 10:26:20.116 SMC[1500:60b] Length of updateFileBase64String before appending 0
2014-08-09 10:26:20.118 SMC[1500:60b] Length of updateFileBase64String after appending 0
2014-08-09 10:26:20.247 SMC[1500:60b] Temp update file is /var/mobile/Applications/2DEEED98-E567-4ABB-AD41-BE74EF28A014/Library/tempUpdateFile
2014-08-09 10:26:20.279 SMC[1500:60b] Length of updateFileBase64String before appending 0
2014-08-09 10:26:20.281 SMC[1500:60b] Length of updateFileBase64String after appending 0
2014-08-09 10:26:20.316 SMC[1500:60b] [DEBUG] [NONE] response [https://{appcenter_hostname}:443/worklight/apps/services/api/SMC/iphone/setup] success:
2014-08-09 10:26:20.326 SMC[1500:60b] THREAD WARNING: ['NetworkDetector'] took '10.586914' ms. Plugin should use a background thread.
2014-08-09 10:26:20.328 SMC[1500:60b] [DEBUG] [NONE] defaultOptions:onSuccess
2014-08-09 10:26:20.339 SMC[1500:60b] THREAD WARNING: ['NetworkDetector'] took '11.760010' ms. Plugin should use a background thread.
2014-08-09 10:26:20.386 SMC[1500:60b] Temp update file is /var/mobile/Applications/2DEEED98-E567-4ABB-AD41-BE74EF28A014/Library/tempUpdateFile
2014-08-09 10:26:20.391 SMC[1500:60b] Length of updateFileBase64String before appending 0
2014-08-09 10:26:20.392 SMC[1500:60b] Length of updateFileBase64String after appending 0
2014-08-09 10:26:20.496 SMC[1500:60b] Temp update file is /var/mobile/Applications/2DEEED98-E567-4ABB-AD41-BE74EF28A014/Library/tempUpdateFile
2014-08-09 10:26:20.501 SMC[1500:60b] Length of updateFileBase64String before appending 0
2014-08-09 10:26:20.502 SMC[1500:60b] Length of updateFileBase64String after appending 0
2014-08-09 10:26:20.544 SMC[1500:60b] Finished downloading.
2014-08-09 10:26:20.545 SMC[1500:60b] Deleting file
2014-08-09 10:26:20.547 SMC[1500:60b] File deleted
2014-08-09 10:26:20.548 SMC[1500:60b] webViewDidFinishLoad: Length of updateFileBase64String before appending 0
2014-08-09 10:26:20.550 SMC[1500:60b] webViewDidFinishLoad: Length of updateFileBase64String after appending 0
2014-08-09 10:26:20.551 SMC[1500:60b] Setting progress
2014-08-09 10:26:20.553 SMC[1500:60b] Starting to unpack
2014-08-09 10:26:20.556 SMC[1500:60b] Decoding base 64
2014-08-09 10:26:20.558 SMC[1500:60b] Unzipping
2014-08-09 10:26:20.562 SMC[1500:60b] Zip file created
2014-08-09 10:26:20.570 SMC[1500:60b] Fatal error updating application. Can't open downloaded zip file.
2014-08-09 10:26:20.572 SMC[1500:60b] Warning: Attempt to dismiss from view controller <CDVMainViewController: 0x15630070> while a presentation or dismiss is in progress!
2014-08-09 10:26:20.586 SMC[1500:60b] Releasing downloadUpdateFileUiWebView
2014-08-09 10:26:20.631 SMC[1500:60b] THREAD WARNING: ['Notification'] took '39.161133' ms. Plugin should use a background thread.
2014-08-09 10:26:20.636 SMC[1500:60b] Temp update file is /var/mobile/Applications/2DEEED98-E567-4ABB-AD41-BE74EF28A014/Library/tempUpdateFile
2014-08-09 10:26:21.236 SMC[1500:60b] Unbalanced calls to begin/end appearance transitions for <CDVMainViewController: 0x15630070>.

A: Make sure you have updated your Server and Studio installations to the very latest 6.1.0.02 iFix release, as related Direct Update fixes were made. The iFix can be obtained from IBM Fix Central.
If it does not work for you, still, update the question with updated logs.

A: I have faced this issue when I build the iOS hybrid file using windows machine.
And problem solved when I build using Mac machine.
Try to rebuild the .wlapp file for iOS and redeploy it to WL console and test the direct update again.
Hope this help.


text:
Q: Timer intervals, Making 1 timer stop another timer - Hey guys im trying to get a simple button masher up, What i want timer1 to do is mash keys in richtextbox1 for 30 seconds over and over, after 30 seconds Activate timer2, which will disable timer 1 and press keys in richtextbox 2 once, then wait 10 seconds and activate timer 1 again.
Im extremley new to c# but ive tried using timer 3 to stop timer 2 and start timer 1 again and it just messes it self up. The code ive tried is below. Any help apreciated...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            SendKeys.Send(richTextBox1.Text);
            SendKeys.Send("{ENTER}");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer2.Enabled = true;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            SendKeys.Send(richTextBox2.Text);
            SendKeys.Send("{ENTER}");
            timer1.Enabled = false;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer2.Enabled = false;
        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

A: If timer3 is running continuously, won't it start timer1 and stop timer2 at unpredictable times, without warning?
IOW, what starts and stops timer3?
As JustLoren pointed out, there might be a cleaner way to do this.  Perhaps a single timer event and some controlling logic and flags, rather than trying to juggle three timers.

A: I suggest to use just one timer, increment a state counter every second, and perform an action base on the current state.
public Form1()
{
    this.InitializeComponent();

    // Just to illustrate - can be done in the designer.
    this.timer.Interval = 1000; // One second.
    this.timer.Enable = true;
}

private Int32 state = 0;

private void timer_Tick(Object sender, EventArgs e)
{
    if ((0 <= this.state) && (this.state < 30)) // Hit text box 1 30 times.
    {
        SendKeys.Send(this.richTextBox1.Text);
        SendKeys.Send("{ENTER}");
    }
    else if (this.state == 30) // Hit text box 2 once.
    {
        SendKeys.Send(this.richTextBox2.Text);
        SendKeys.Send("{ENTER}");
    }
    else if ((31 <= this.state) && (this.state < 40)) // Do nothing 9 times.
    {
        // Do nothing.
    }
    else
    {
        throw new InvalidOperationException(); // Unexpected state.
    }

    // Update state.
    this.state = (this.state + 1) % 40;
}

The variant with two numeric up down controls.
public Form1()
{
    this.InitializeComponent();

    // Just to illustrate - can be done in the designer.
    this.timer.Interval = 1000; // One second.
    this.timer.Enable = true;
}

private Int32 state = 0;

private void timer_Tick(Object sender, EventArgs e)
{
    Decimal n1 = this.numericUpDown1.Value;
    Decimal n2 = this.numericUpDown2.Value;

    if ((0 <= this.state) && (this.state < n1))
    {
        SendKeys.Send(this.richTextBox1.Text);
        SendKeys.Send("{ENTER}");
    }
    else if (this.state == n1)
    {
        SendKeys.Send(this.richTextBox2.Text);
        SendKeys.Send("{ENTER}");
    }
    else if ((n1 <= this.state) && (this.state < n1 + n2))
    {
        // Do nothing.
    }
    else
    {
        // Reset state to resolve race conditions.
        this.state = 0;
    }

    // Update state.
    this.state = (this.state + 1) % (n1 + n2);
}


text:
Q: Let $G$ be a graph which does not have 2 disjoint odd cycles. Prove that the Chromatic number is at most 5. Hint: Suppose that the chromatic number is at least 6 and consider graphs induced by 3 colour classes.
Any hints would be appreciated. I do not understand what a graph induced by 3 colour classes are. They have not been defined in my lectures.
Thanks

A: Here is what the hint suggests:
Assume by contradiction that the chromatic number is at least 6. Pick one optimal coloring.
Define subgraphs $G_1, G_2$ the following way:
$G_1$ contains all the vertices colored with the first three colors and all the edges between these vertices. $G_2$ contains all the vertices colored with the other colors and all the edges between these vertices.
Now, one of $G_1, G_2$ doesn't contain an odd cycle, thus is 2 colorable. Recolor it with two colors, and prove that this gives a better coloring of $G$.


text:
Q: Magnetic path length and permeability relation In a transformer, does increasing the magnetic path length reduce flux and permeability and increase thr reluctance of the core?
If yes, why does the equation of relative permeability of a gapped core show that permeability is increased as you increase the MPL?

A: In a transformer, increasing the magnetic path length reduces flux and permeability and increases reluctance of the core?
True.
The magnetic path length (MPL) is analogous to the length of a conductor for electrical current - increasing the MPL will increase its reluctance (magnetic 'resistance'). For a given magneto-motive force (MMF) in ampere-turns the flux produced will depend upon the value of reluctance in ampere-turns per Weber and so an increase in reluctance will produce a decrease in flux. (See Hopkinson's Law)
Permeability is analogous to 'conductivity' and depends upon the material as well as the path length and cross-sectional area. Increasing reluctance will decrease permeability.
[In electrical terms if the resistance is increased the conductance is decreased]
Why does the equation of relative permeability of a gapped core show that permeability is increased as you increase the MPL?
False
The reason an 'air gap' is used is to prevent the core from saturating. {n.b. the term 'air gap' also refers to other materials such as nylon that is used to fill the gap.} In other words you are increasing the reluctance of the circuit and as we have already seen this decreases the permeability.
As you don't show the equation you're referring to I'll just go through the basic theory.
The gap reluctance, Rg, is given by:
                        Rg = Lg / (μ0 * Ae)

where Lg is gap length, μ0 is the permeability of a vacuum (very similar to value for air) and Ae is the cross sectional area.
The core reluctance, Rc, is
                        Rc = Lc / (μ0 * μr * Ac)

Where Lc is the magnetic core length,  μr is the relative permittivity of the core material (>>μ0) and Ac is the area of the core.
The total reluctance of the magnetic circuit, Rt, is
                Rt =  Lc / (μ0 * μr * Ac)  +  Lg / ( μ0 * Ae)

Generally Ae = Ac = A (maintains cross sectional area across gap) so this becomes
                 Rt = (1 / ( μ0 * A)) * ( (Lc /  μr) + Lg)

If  μr is very large (as in most cases of magnetic core material) it is the length of the airgap, Lg, that dominates the Reluctance value. Reluctance INCREASES with air gap length (and MPL) and if you increase Reluctance you DECREASE the effective Permeability.

A: You asked:

"In a transformer, increasing the magnetic path length reduces flux
  and permeability and increases reluctance of the core?"

This is not quite right.  The permeability of a material is a property of that material.  Permeability really only makes sense for a uniform material.  It tells you for a given magnetic field, H, what your magnetic flux density, B, is.  In other words, \$B = \mu H\$. So if you had a transformer with a core with no air gap and N turns of wire with current I in that wire and length l, your magnetic field will be \$H = \frac{N I}{l}\$.  So if you keep all those things constant but increase l, then your magnetic field, H, will decrease.  Because \$\mu\$ is a property of your material, it will remain constant.  So if H decreases and \$\mu\$ stays the same, it means your flux density, B, will also decrease.  So, keeping all other things the same, if you just increase the magnetic path length, then that will change your flux density.  Assuming uniform cross sectional area, this also means your flux will decrease.
Reluctance is defined as \$R = \frac{N I}{\phi} = \frac{H l}{B a} = \frac{l}{\mu a} \$, where \$\phi\$ is the magnetic flux and a is the cross-sectional area.  Again, if all other things remain the same, than an increase in path length results in an increase in reluctance.
So, to restate: An increase in path length of a core of a transformer without an air gap will result in a decreased magnetic field, H, decreased flux density, B, decreased flux, \$\phi\$, and increased reluctance.  However, permeability of the material stays the same.
Effective permeability is a shortcut that is sometimes used to make calculations easier.  Essentially it takes a core with a gap in it and says "What would be the equivalent value of \$\mu\$ if this core had no gap?"  This allows a person (by using the equations above) to quickly find the magnetic flux through the core by just knowing length, cross-sectional area, number of turns and current.  It's a slight shortcut that lets you skip calculating the core reluctance, the air gap reluctance, adding them together, and then calculating flux.
Notice that if you know the reluctance of the core and the air gap individually, you can add them together to get an effective reluctance and from that, if you multiply by cross-sectional area and divide by total length, you will get the effective permeability.  Here are the equations:
$$
R_{core} = \frac{l_{core}}{\mu_{core} a}
$$
$$
R_{gap} = \frac{l_{gap}}{\mu_{gap} a}
$$
$$
R_{eq} = R_{core} + R_{gap} = \frac{1}{a} (\frac{l_{core}}{\mu_{core}} + \frac{l_{gap}}{\mu_{gap}})
$$
$$
\mu_{eq} = \frac{l_{eq}}{R_{eq} a} = \frac{l_{core} + l_{gap}}{R_{eq} a}
$$
And if you work out the math, that last equation comes out to:
$$
\mu_{eq} = \frac{\mu_{core} \mu_{gap} l_{core}}{l_{core} \mu_{gap} + l_{gap} \mu_{core}}
$$
Now, based on that last equation, you can see that if you increase the length of the core, the effective permeability is going to increase.  However, if you increase the air gap, the effective permeability will decrease.

A:
Why does the equation of relative permeability of a gapped core show
  that permeability is increased as you increase the MPL?

The permeability of the raw material used in ferrite is called initial permeability, \$\mu_i\$.
When ferrite is "molded" into a shape and gaps introduced, the permeability is then called effective permeability, \$\mu_e\$.
The formula you have is \$\mu_e = \frac{\mu_r}{1+(\mu_r\frac{l_g}{l_e})}\$ where \$\mu_r\$ is relative permeability which can be taken to mean the same as \$\mu_i\$.
Quite simply, effective permeability increases if the gap remains constant but the length of the magnetic path increases. Why? Because the gap becomes smaller relative to the magnetic path length. Use the formula, do the math.
It's nothing to do with the physics (\$\mu_r\$ or \$\mu_i\$) but to do with the effective permeability.

In a transformer, increasing the magnetic path length reduces flux and
  permeability and increases reluctance of the core?

YES because magnetic flux is the by-product of magnetic field strength, H and H is purely determined by number of turns, current in the turns and magnetic path length.


text:
Q: Why does the $\mathbb{1}$ in $S = \mathbb{1} + i \mathcal{M}$ correspond to no scattering? I am a beginner in quantum field theory and I am learning from the lecture notes by David Tong. On Page 58, he gives an example of two nucleons scattering and says that we are only interested in $\langle f|S-1|i\rangle$ since this is the only relevant quantum amplitude for scattering events. I do not understand how subtracting $\langle f|i \rangle$ from $\langle f|S|i \rangle$ will exclude the non-scattering events and give us what we are looking for.

A: The decomposition $S=1+i\mathcal M$ is just a convenient way to separate out the "trivial" part of the $S$-matrix.
Recall that two quantum states are orthogonal if and only if there exists, at least in principle, a measurement which can distinguish beetween the two. Therefore the $1$ in $S=1+i\mathcal M$ is zero if "something happens":$$\langle \alpha \vert 1 \vert \beta \rangle =0 \iff \vert \alpha \rangle \perp \vert \beta \rangle.$$
Note that $\mathcal M$ satisfies the identities: $$\mathcal M^\dagger \mathcal M+i (\mathcal M-\mathcal M^\dagger)=0\\\mathcal M \mathcal M^\dagger +i (\mathcal M^\dagger-\mathcal M)=0$$which are equivalent to the unitarity of the $S$-matrix and ultimately lead to the optical theorem, see for example Weinberg S., "The quantum theory of fields, Vol.1".

Side note. As pointed out, there are several notations for the so called "transfer matrix" $S-1$. The one I encounter more frequently is $S=1+iT$.


text:
Q: Fluent NHibernate Mapping Left Join I know that this code has a bit of smell but it suits this project in this specific implementation.
public class InvestmentAdvisorMap: ClassMap<InvestmentAdvisor>
{
    public InvestmentAdvisorMap()
    {
        Id(x => x.EmployeeID).GeneratedBy.Assigned()
            .Access.CamelCaseField(Prefix.Underscore);

        Not.LazyLoad();
        Table("Employee");
        //need mapping to tierName here???? that links to join table
    }
}

public class InvestmentAdvisor
{
    private readonly Guid _employeeID;
    private string _tierName;

    public Tier Tier
    {
        get
        {
            switch (_tierName)
            {
                case "<$100K":
                    return Tier.LessThan100K;
                case "$100K+":
                    return Tier.MoreThan100K;
                case "$240K+":
                    return Tier.MoreThan240K;
                case "$400K+":
                    return Tier.MoreThan400K;
                case "$600K+":
                    return Tier.MoreThan600K;
                case "$1M+":
                    return Tier.MoreThan1M;
                default:
                    return Tier.LessThan100K;
            }
        }
    }

    public string TierName
    {
        get {
            return _tierName;
        }
    }

    public Guid EmployeeID
    {
        get { return _employeeID; }
    }
}

}
I have a join table where there is a one to one relationship on tier where which has employeeID and TierName, I cant for the life of me figuire out how to do the Mapping class, basically a composite entity but not finding great examples

A: How about inheritancehirarchy?
public abstract class Tier
{
    public abstract void DoSomething();
}

class TierMap : ClassMap<Tier>
{
    public TierMap()
    {
        DiscriminateSubClassesOnColumn("TierName");
    }
}

public class LessThan100K : Tier
{
    public override void DoSomething()
    {
        // Do something useful
    }
}

class LessThan100KMap : SubclassMap<LessThan100K>
{
    public LessThan100KMap()
    {
        DiscriminatorValue("<$100K");
    }
}

and so on.


text:
Q: python updating single value in csv file I have this script, where I intend to update a value in a CSV
I understand that I will write it back to the file to actually effect the changes, but I was expecting to be able to change the value in the row list like below.
However, before and after the change, the row remains the same,
Why would that be?
with open(tasks) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        row[1] == 'ddd'
        print(row)

A: You surely meant:
row[1] = 'ddd'
#     ^^^

Your former expression was a boolean test (==) not an assignment and you did nothing with it (no return value whatsoever).

A: I think that you should do like below:
row[1] = 'ddd'


text:
Q: Simplification question regarding a quotient If I have an expression such as $\frac{(1-a)}{a(a-1)}$ am I allowed to distribute a negative sign only to the denominator, and if so why. How does the negative sign distribute over both factors that is $(a)(a-1)$? Is that not allowed?

A: Both ways are correct since they lead to the same result:
$$\require{cancel}
\dfrac{(1-a)}{a(a-1)}=\dfrac{-\cancel{(a-1)}}{a\cancel{(a-1)}}=-\dfrac1a \\ \color{grey}{\text{or }}\dfrac{(1-a)}{a(a-1)}=\dfrac{\cancel{(1-a)}}{-a\cancel{(1-a)}}=\dfrac1{-a}=-\dfrac1a.
$$
I hope this helps.
Best wishes, $\mathcal H$akim.


text:
Q: GSON : Parsing JSON when keys are a part of response Here's the response I am trying to parse.
{"table":"PypersonResponsibleCrewMembersWklyView","numberOfRemainingRecords":0,"rowDefinition":{"attrNames":["EmpOraseq","{PEmpNo","PEmpName","Code","Name","EmpNo","EmpTrdCode","EmpTrdName","EmpFirstName","EmpLastName","NhHrsTot","OtHrsTot","DotHrsTot","NhHrs1","OtHrs1","DotHrs1","NhHrs2","OtHrs2","DotHrs2","NhHrs3","OtHrs3","DotHrs3","NhHrs4","OtHrs4","DotHrs4","NhHrs5","OtHrs5","DotHrs5","NhHrs6","OtHrs6","DotHrs6","NhHrs7","OtHrs7","DotHrs7"]},"rows":[{"attrValues":[211448,"1016","Mr. Demo","REL","aman","1004","PRES","President","Gord","Rawlins",0.5,0.5,0,0.5,0.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},{"attrValues":[211448,"1016","Mr. Demo","REL","aman","ESS001","PROE","Project Engineer","Nadal","Rafael",0.5,0.5,0.5,0.5,0.5,0.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},{"attrValues":[211448,"1016","Mr. Demo","REL","aman","CL1001","SS01","System Specialist","Ronald","Bromell",0.5,0.5,0.5,0.5,0.5,0.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}]}

In this response 'attrNames' contains the keys and 'attrValues' contains the values. Is it possible to parse this using GSON?


text:
Q: Does $\sum q^\sqrt n$ converge?
Does $\sum q^\sqrt n$ converge? ($q>0$)

It is clear that if $q\ge1$ series diverges, but what about $q\in(0; 1)$?

A: For $q\in(0,1)$:
$$\sum_{n=1}^\infty q^{\sqrt n}<\sum_{n=1}^\infty q^{\lfloor\sqrt n\rfloor}\stackrel*=\sum_{k=1}^\infty (2k+1)q^k<\infty$$
$(*)$ Note that for each $k\in\Bbb N$ there are exactly $2k+1$ natural numbers $n$ such that $\lfloor\sqrt n\rfloor=k$.
EDIT (motivated by Clement's comment):
Let $r\in(0,1)$. Take some natural $s>1/r$. For each natural $k$, there are
$$p(k)=(k+1)^s-k^s$$
natural numbers $n$ such that $\lfloor\sqrt[s]n\rfloor=k$. Then
$$\sum_{n=1}^\infty q^{n^r}<\sum_{k=1}^\infty p(k)q^k<\infty$$

A: Yes, it does converge (and quite fast, but that's besides the point). We can prove it by comparison with, for instance, the series $\sum_{n=1}^\infty \frac{1}{n^2}$.
Let $q\in(0,1)$ be any number.
$$\frac{q^{\sqrt{n}}}{\frac{1}{n^2}} = n^2 e^{-\sqrt{n} \ln\frac{1}{q}}
= e^{-\sqrt{n} \ln\frac{1}{q}+2\ln n}
= e^{-\ln\frac{1}{q}\left( \sqrt{n} - \frac{2}{\ln\frac{1}{q}}\ln n\right)}$$
Now, you can use the fact$^{(\dagger)}$ that for any real number $a\in\mathbb{R}$,
$$
\sqrt{n}-a\ln n \xrightarrow[n\to\infty]{} \infty
$$
to conclude that $\frac{q^{\sqrt{n}}}{\frac{1}{n^2}}\xrightarrow[n\to\infty]{} 0$.

If $(\dagger)$ is not obvious or known to you:
$$
\sqrt{n}-a\ln n = \sqrt{n}\left(1-a\frac{\ln n}{\sqrt{n}}\right)
= \sqrt{n}\left(1-2a\frac{\ln \sqrt{n}}{\sqrt{n}}\right) $$
so it is sufficient to know or prove that $\frac{\ln x}{x} \xrightarrow[x\to\infty]{} 0$.

A: Let $f:\mathbb{Z}_{\geq 0}\to\mathbb{R}_{\geq 0}$ be a function such that, as a function of $m\in\mathbb{Z}_{\geq 0}$, the cardinality of the preimage $T_m:=f^{-1}\big([m,m+1)\big)$ is polynomially bounded, namely, for some polynomial $p(X)\in\mathbb{R}[X]$, $\big|T_m\big|\leq p(m)$ for every $m$.  (In fact, we only need that $T_m$ is finite for all $m$ and $\limsup\limits_{m\to\infty}\,\sqrt[m]{\left|T_m\right|}\leq1$.)  Then, for $q>0$, the infinite sum $\displaystyle\sum_{n=0}^\infty\,q^{f(n)}$ converges if and only if $q<1$.
It is trivial that $q<1$ is necessary for the sum to converge.  We shall show that the sum indeed converges when $q<1$.  Observe that
$$\sum_{n=0}^\infty\,q^{f(n)}=\sum_{m=0}^\infty\,q^{m}\,\sum_{j\in T_m}\,q^{f(j)-m}\leq\sum_{m=0}^\infty\,q^m\,\left|T_m\right|\,.$$
Since $\left|T_m\right|$ is polynomially bounded, we conclude that $\sum\limits_{m=0}^\infty\,q^m\,\left|T_m\right|<\infty$ for $q\in(0,1)$.
In particular, if $f(n)=\sqrt{n}$, then $\big|T_m\big|=(m+1)^2-m^2=2m+1$ is linear, whence polynomially bounded.  Hence, for $q>0$, the sum $\sum\limits_{n=0}^\infty\,q^{\sqrt{n}}$ is convergent iff $q<1$.

A: *

*Write $q=\frac{1}{1+y}$

*Note that $(1+y)^k > {k \choose 3}y^3$

*Deduce that $q^k < \frac{y^{-3}3!}{k(k-1)(k-2)}$

*Take $k=\sqrt{n}$ to see$$q^{\sqrt{n}}=O(n^{-3/2})$$

*Remark that $n^{-3/2 }$ has a convergent sum

*Deduce that the sum is convergent

A: We can use the estimate $\sqrt n\geq\ln n$ to get
$$
\sum_{n=1}^\infty q^{\sqrt n}\leq\sum_{n=1}^\infty q^{\ln n}=\sum_{n=1}^\infty n^{\ln q}<\infty,\ \ \text{ if }\ln q<-1,$$
which happens for $0<q<\frac{1}{e}\approx0.367878$. We have thus obtained only a partial solution, but this argument can be modified  in order to get the desired result:
Let's fix $k\geq1$. As $\frac{\sqrt n}{k\ln n}\to\infty$ when $n\to\infty$ we know that there is some $N(k)\in\mathbb{N}$ such that $$\sqrt{n}\geq k\ln n,\ \ \text{for }n\geq N.$$ Performing the above estimations again we arrive at
$$
\sum_{n=N}^\infty q^{\sqrt n}\leq\sum_{N}^\infty n^{k\ln q}<\infty,
\ \ \text{ if }k\ln q<-1,$$ which happens for $0<q<e^{-\frac{1}{k}}$. As $e^{-\frac{1}{k}}\nearrow1$ when $k\to\infty$ this yields the desired convergence for $0<q<1$.


text:
Q: Where do you place POSIX semaphores when using POSIX shared memory? I'm trying to build a client server application using POSIX shared memory and POSIX semaphores. Do I have to place the semaphores inside the shared memory segment or can the semaphores just be global variables? I wish to adhere to POSIX convention.

A: No, the semaphores are system resources; you don't have to worry about locating them.
Update: Let me "extend and revise my remarks".  Named semaphores are system resources.  Unnamed semaphores must be in a shared memory segment.  See the intro man page for semaphores.


text:
Q: Unicode text to Arabic Text in Excel I have asked here to how put %u after every four digit to convert my long string into a proper unicode text. I got a very nice reply with the UDF and it work great.. now from this string
002006390632064A0632064A00200627064406390645064A0644003A0020062A0645002006270644

I am able to convert it into
%u0020%u0639%u0632%u064A%u0632%u064A%u0020%u0627%u0644%u0639%u0645%u064A%u0644%u003A%u0020%u062A%u0645%u0020%u0627%u0644

Well the string is to long i just showed you the result... Now what I am looking is there any excel function which can convert this into Arabic text. Actually its a uncode and want to see how it look in Arabic.
Currently I am using a website

http://unicode.online-toolz.com/tools/text-unicode-entities-convertor.php

to convert it manually. Is there any excel function which can do that locally.

A: You could create a byte array from the code and assigning this byte array to a String. This String can then be assigned to a Cell.
Example:
Sub test()

 Dim sCode As String

 sCode = "002006390632064A0632064A00200627064406390645064A0644003A0020062A0645002006270644"

 Dim b() As Byte
 Dim j As Long
 j = 0

 For i = 1 To Len(sCode) Step 4

  ReDim Preserve b(j + 1)
  b(j) = Val("&H" & Mid(sCode, i + 2, 2))
  b(j + 1) = Val("&H" & Mid(sCode, i, 2))
  j = j + 2

 Next

 Dim s As String
 s = b

 Range("A1").Value = s

End Sub


text:
Q: Math contest proof equation problem Could someone help me with this?
If $m$ and $n$ are positive integers, then show that $$\frac{m}{
\sqrt n}+ \frac{m}{\sqrt[4]{n}} \neq 1$$.

A: $$\frac{m}{\sqrt n}+ \frac{m}{\sqrt[4]{n}} = 1 \implies \frac{m}{\sqrt n}\left(1+\sqrt[4]{n}\right) = 1 $$
Or $m(1+\sqrt[4]{n}) = \sqrt{n}$.  Squaring, $m^2(1+\sqrt[4]{n})^2 = n$.

Suppose $n$ is not a perfect fourth power, so $r = \sqrt[4] n$ is irrational.  Then we have $(1+r)^2 = N$, for some factor of $n$.  So $r = \sqrt N -1$ and $N$ is not a perfect square.
However $r^4 = N^2+6N+1-4(1+N)\sqrt N= n$ makes $\sqrt N$ rational.  Hence this case leads to contradiction.

So we need $n$ to be a perfect fourth power, say $n = k^4$.  So $m^2(1+k)^2 = k^4$.
So $m(1+k) = k^2 \implies$ for all primes $p|(1+k)$, we must have $p | k$.  This is not possible, hence we cannot have a solution.


text:
Q: What's the meaning of "knocking in my knees" in this sentence? and one more
*

*"I tug on my skirt, willing it to be longer, wanting it to cover the knocking in my knees."  -from the Hunger Games

What is the difference between "to cover my knees" and the sentence above?
All I know about "knocking" is a kind of "knocking the door" or "hit sth".

*"My whole body's shaking. Hopefully, it will be put down to excitement." -from the Hunger Games

Does it mean 'I wish everybody would think the excitement cause shaking of my body'?
Thank you.

A: "Cover" in this context means "conceal".  "Knocking in my knees" is just an illiterate trying to say "knocking of my knees".
One's knees knocking (that is, shaking severely enough they are actually banging together) is a sign of stress, typically either anticipation or fear.
It is a weak metaphor because a skirt can literally cover the knees themselves, without necessarily concealing the fact that they are shaking.


text:
Q: A fixed point theorem Let $\emptyset \not = X\subseteq \Bbb{R}^n$ be convex and compact and let $\cal{A}$ be a family of affine maps from $\Bbb{R}^n$ into $\Bbb{R}^n$ such that $X$ is invariant under each element of $\cal A$ and $f\circ g = g\circ f$ for any $f, g \in \cal A$. I am trying to show that elements of $\cal A$ have  a common fixed point which is in $X$.
Any idea or references would be helpful.


text:
Q: HashSet performance (compared to ObservableCollection)? I am currently working on a project where I have to manage large sets of unique elements. Each element has ~20 Properties, and every element has a public property DateTime.
The property DateTime is not unique, so I cannot use a generic dictionary to store my data.
Currently I put those elements into an ObservableCollection, but the perfomance of removing elements from the collection is incredibly slow, I end up waiting ~20 seconds to remove ~7000 elements from a collection of ~25.000 elements.
(The search operation seems to be quite efficient, it takes only ~30 ms to find 80 randomly selected elements from an unsorted collection of 300.000 elements).
Each element implements the GetHashCode() method by simply returning the DateTime.GetHashCode().
I thought that using a HashSet rather than an ObservableCollection would increase my performance quite a bit, but it doesn't seem to have an effect at all...
And using a generic dictionary is even worse...
Isn't the HashSet more powerful than an ObservableCollection if the elements have "good" hash functions (there are very few elements that have the same hash code)??

A: You have to override the Equals method of your objects.
Because the HashSet uses an internal IEqualityComparer instance that usually first checks for (null) and then compares a "non-null" item with another item by using the overridden Equals method:
class MyObject
{
    public Guid Id { get; set; }

    public override bool Equals(object other)
    {
        if (other is MyObject)
        {
            // use the 'Id' property as identifier

            MyObject myObj = (MyObject)obj;
            return myObj.Id == this.Id;
        }

        // is not a 'MyObject' based object
        return base.Equals(other);
    }
}

You can also use strings or any other kind of objects that are comparable with your objects.
EDIT:
So you can use the HashSet instead of OberservableCollection. The last collection type is normally slower because on each collection change (add, remove, clear, insert, etc.) the PropertyChanged and the CollectionChanged events are fired.

A: You can optimize the performance of the ObservableCollection by reducing the change notifications. I've written a custom collection class, the ItemCollection, with an update mechanism (BeginUpdate/EndUpdate):
  ItemCollection<Customer> customers = new ItemCollection<Customer>
  customers.BeginUpdate();
  customers.Add( new Customer( "Joe", "Smith" ) );
  customers.Add( new Customer( "Mary", "Jones" ) );
  customers.Add( new Customer( "Lisa", "Black" ) );
  customers.Add( new Customer( "Peter", "Brown" ) );
  customers.EndUpdate();

Article with source code: Presentation Patterns for XAML based Applications.

A: Well Marcel answer is correct, but if performance really matters you can slightly improve his equals method:
class MyObject
{
    public Guid Id { get; set; }

    public override bool Equals(object other)
    {
        MyObject myObj = obj as MyObject;

        if (myObj != null)
        {
            // use the 'Id' property as identifier
            return myObj.Id == this.Id;
        }

        // is not a 'MyObject' based object
        return base.Equals(other);
    }
}

With this approach you avoid the costly function to check if a object is of a specifc type two times by calling it only once and doing a fast null check. For more informations about it, you could take a look into this article from Eric.


text:
Q: How can I connect to wifi Internet using IP rather than ESSID? How can I connect to wifi Internet using IP rather than ESSID?
Hello,
I have a machine running a Linux OS and I want to connect to Internet over wifi. However, I do not want to use the ESSID in the configuration settings. Instead, I want to connect to the IP address using password only.
I. e. I know the IP of the access point and I want to put only the IP and the password into e. g. WPA_supplicant.conf or similar Internet settings file. I will only use the Terminal for this so please don't reply with any GUI instructions.
Is it possible and if so, how?
Vesa


text:
Q: How to share wifi under Gentoo? My system is Gentoo 64bit, with KDE. I want to share my wifi connection with other devices. I am able to do this with Windows 7, so I think my device is able to setup an AP. And I find out that in KDE, the NetworkManager can set up a shared wifi connection.
But my problem is, after I setup this shared wifi connection profile, I cannot activate it. I can not see it from the network connection drop down list, neither can I find it with my phone.

A: You can check the configuration file in /etc/NetworkManager/system-connections directly. System wide connections don't have permissions= line in the [connection] section. Also, NetworkManager is monitoring available connections via wpa_supplicant which triggers network scanning. You normally only connect to networks that are public, i.e. not hidden. If your network uses hidden SSID, the best way is to turn of this feature, as it doesn't provide security anyway. If you cannot do that, you'd have to ask KDE developers or use nmcli or nm-applet to connect to the network.
See also:

*

*https://developer.gnome.org/NetworkManager/0.9/ref-settings.html


text:
Q: Jquery UI Tabs - Multiple tabs (vertical) issue I have two tabs. Essentially, tabs within tabs. Here is an example: image: http://i45.tinypic.com/35k0uhg.png
Tabs is red
Sub-Tabs is blue
Tabs is supposed to be vertical (working properly) whereas the Sub-Tabs is horizontal. However as you can see above, the Sub-Tabs is also vertical. For some odd reasons, I cannot figure out how to make the Sub-Tabs horizontal while the Tabs stays vertical.
The Sub-Tabs is supposed to look like this:
Image: http://i47.tinypic.com/k9c01d.png
Code for Tabs
#tabs {
    position: relative;
    padding-left: 14.5em; /* content */
    margin-right: 5px;
    padding-top: 20px;
    background: transparent;
    border: none;
    /*  height: 30em; */
}

#tabs .nav {
    position: absolute;
    left: 0.25em;
    top: 1.5em;
    bottom: 0.25em;
    width: 16em; /* tabs width */
    padding: 0.2em 0 0.2em 0.2em;
    background: transparent;
    border: none;
}

#tabs .nav li {
    right: 1px;
    width: 100%;
    border: none;
    overflow: hidden;
}

#tabs .nav li a {
    float: left;
    width: 100%;
    margin-bottom: 3px;
    height: 24px;
    padding-top: 14px;
    padding-left: 15px;
    font-weight: bold;
    color: #2e2e2e;
    background: #fff;
}

#tabs .nav li a:hover {
    cursor: pointer;
    background: #206fbf;
    color: #fff;
}

#tabs  .nav li.ui-tabs-selected a {
    cursor: pointer;
    color: #fff;
    background: #206fbf;
}

Codes for Sub-Tabs
#Sub-Tabs {
    background: transparent;
    border: none;
    position: none;
    list-style: none;
}
#Sub-Tabs .ui-widget-header {
    background: transparent;
    border: none;
    border-bottom: 1px solid #c0c0c0;
    -moz-border-radius: 0px;
    -webkit-border-radius: 0px;
    border-radius: 0px;
    position: none;
}
#Sub-Tabs .ui-state-default {
    background: transparent;
    border: none;
}
#Sub-Tabs .ui-state-active {
    background: transparent url(img/uiTabsArrow.png) no-repeat bottom center;
    border: none;
}
#Sub-Tabs .ui-state-default a {
    color: #c0c0c0;
}
#Sub-Tabs .ui-state-active a {
    color: #459E00;
}

HTML Portion:

Testing Area

Upgrade Requirements

Hello World

Main

Hellow rold!

afsa

afsa

Your help is appreciated!

A: Seeing your HTML would help a little but the real problem is your CSS. #tabs .nav li is going to grab every li under every element with class .nav within element #tabs. In other words, you have extreme overlapping CSS here.
Try using some children selectors like:
#tabs .nav > li {}
/* Where ">" says 'Hey, grab only the li elements immediately within .nav!' */

Also, for more info on how jQueryUI does it, see here
Here is jsFiddle for you to work with and try out.


text:
Q: Why is this node's X position not the center of the screen? I have a container node, simply initialized with no arguments. When added to the scene it appeared centered, as all children nodes are placed approriately.
Then in touchesMoved I'm trying to use the following code to allow movement of the container node up to 1/3 of the screen width in either X direction:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first as UITouch?
    let width = self.frame.size.width
    let startX = touch!.previousLocation(in: self).x
    let currentX = touch!.location(in: self).x

    if container.position.x < width * CGFloat(5.0/6.0) && container.position.x > width * CGFloat(1.0/6.0) {
        container.run(SKAction.moveBy(x: (currentX - startX), y: 0.0, duration: 0.0))
    }

}

Removing the if statement conditionals, but keeping the code inside the if, allows for the container to be moved indefintely without bounds, but with the if statement it will not move at all.  It seems to me that the x position of the container should start at the center (width * 3/6) and  these conditions should allow it to move in either direction to the bounds by allowing movement between (width * 1/6) and (width * 5/6).  Is this the wrong way to go about this, or is my logic flawed?


text:
Q: jquery selecting a element child then an attribute of that child <object id="foo">
  <param value="bar1" name="foo1"></param>
  <param value="foo2" name="bar2"></param>
</object>

To get a value should the jquery be this?
$("#foo > param[name='bar2']").attr("value")

Doesnt seem to work for me.
http://api.jquery.com/child-selector/
http://api.jquery.com/attribute-equals-selector/

A: $("#foo").find('[name="bar2"]').attr("value")

Or if the child element is an immediate child , you can use
$("#foo").children('[name="bar2"]').attr("value")

A: When I tried the code you provided, it worked fine; perhaps it is the version of jQuery you're using. Put
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

onto the page, and see if that makes the code you've written work.


text:
Q: sql - How to have multiple select/from statements in one query I'm trying to pull a report where each column is selecting from a specific table set. However, one of the columns needs to pull from a completely different table set and still be included in the same report. Of course, this doesn't work:
select u.first_name, ticket_work.time_spent
FROM tickets LEFT OUTER JOIN ticket_work ON ticket_work.ticket_id = tickets.id JOIN users u
(select count(tickets.id) FROM tickets JOIN users u)

where tickets.assigned_to = u.id

...
So just the part (select count(tickets.id) FROM tickets JOIN users u) needs to be selecting from the different table set but still be included in the report.

A: I'm a little confused by your question.  Are you wanting to return the user, the count of tickets for that user, and the amount of time spent overall?  If so, something like this should work:
select u.id, u.first_name,
    SUM(tw.time_spent) summed_time_spent,
    COUNT(DISTINCT t.id) count_tickets
FROM users u
    LEFT JOIN tickets t
        ON u.id = t.assigned_to
    LEFT JOIN ticket_work tw
        ON tw.ticket_id = t.id
GROUP BY u.id, u.first_name

A: Your questions is unclear, but just generally, it sounds like you're trying to join to a derived table (i.e., a query).  In that case, do this:
SELECT...
FROM...
table_A A LEFT JOIN
   (SELECT keyfield, valuefield FROM table_b WHERE ...) B
   ON A.keyfield = B.keyfield

Does that make sense?  To make a derived table, you put a query inside of parenthesis, give it an alias ('B' in this case), and then join it to your other tables as though it were a regular table.

A: Don't know about your table structure but you may use a sub query for such requirement
select u.first_name, ticket_work.time_spent,(select count(tickets.id) FROM tickets where ticket.id=ticket_work.ticket_id) as myCount
FROM tickets LEFT OUTER JOIN ticket_work ON ticket_work.ticket_id = tickets.id JOIN users u
where tickets.assigned_to = u.id


text:
Q: nginx "server_tokens" configuration ignored nginx.conf:
server_tokens off;

Why could this get ignored, the header is still sent:
Server: nginx

No, other included config files do not contain server_tokens configuration.
Yes, I did restart all services.

A: To cite the docs on the server_tokens directive:

Enables or disables emitting nginx version in error messages and in the "Server" response header field.

According to the docs, it thus doesn't prevent the generation of the Server header but only prevents the addition of the exact version. If you want to completely remove the servers header, you could use the ngx_headers_more module.

A: "The setting works as documented"
The above is kinda insane... (Sorry Hulgar Just, but if you don't understand the rant you should probably not answer.)
Nginx doesn't need to broadcast out its version and the server OS, basically ever, outside of debug situations, shouldn't actually be a question. nor should people wanting to stop that insane behavior be a problem to anyone who knows anything about infosec.
As it stands site failures even with the "feature' enabled, results in disclosure of information that is unnecessary for visitors. The absolute best you can do is disable it in all your site configs, but when they die you still have a problem. Patching is the only way at the moment sadly...


text:
Q: Firefox override NetError.xhtml page I am using Ubuntu 12.04, and my firefox version is 47.0. I want to override the netError.xhtml file. I have tried googling a lot, but unable to fix this problem
This is what I've done so far

from my home directory

unzip /usr/lib/firefox/omni.ja -d omni

edited the function retryThis(buttonEl) infile
  /home/suman/omni/chrome/toolkit/content/global/netError.xhtml

  function retryThis(buttonEl)
  {
    // Note: The application may wish to handle switching off "offline mode"
    // before this event handler runs, but using a capturing event handler.

    // Session history has the URL of the page that failed
    // to load, not the one of the error page. So, just call
    // reload(), which will also repost POST data correctly.
    try {
      location.replace('http://www.google.com');
    } catch (e) {
      // We probably tried to reload a URI that caused an exception to
      // occur;  e.g. a nonexistent file.
    }

    buttonEl.disabled = true;
  }

Repacked the omni folder and replace it into the actual location
zip -qr9XD omni.ja *
mv home/suman/omni/omni.ja /usr/lib/firefox/

Restarted the browser and generated the page as show in image description below
But I cannot redirect it to google site when Try Again is clicked
Any help would be very much appreciated
Below is the screenshot
image description here

A: I have similiar problem in firefox 59 in windows 10.
TLDR: check chrome.manifest in the folder mozilla firefox/browser/omni.ja/chrome and you can delete the line that override netError.xhtml with aboutNetError.xhtml or you can simply edit aboutNetError.xhtml.
I get the idea[1] that there's a rule that override neterror.dpd in chrome.manifest because the neterror.dpd in omni.ja from Mozilla Firefox folder is different from the error message I found when an error occured when I'm browsing.
So I look into all the chrome.manifest that i can find but I didn' find any that override the rule. So I searched for the possibility of another omni.ja and therw i found it in Mozilla Firefox/browser
So what I do is:

*

*Copy omni.ja to Desktop or any of your preferred folder and rename it to omni.zip

*Extract the archive to a folder (I named it omni too)

*Get into the folder omni/browser/chrome/browser/content

*There I found aboutNetError
xhtml and this is the file that you want to edit

[1]https://mike.kaply.com/2012/06/14/customizing-firefox-hiding-private-browsing-continued/


text:
Q: Can I get reviews or stars for hotels or restaurants in HERE Geocoding & Search API? I can't seem to find anything in the documentation (link), but the previous version of the Places API (link) said:

Certain types of categories, such as restaurants or hotels, are ranked via a "recommendations-style" algorithm where measures of popularity or quality, such as number of stars or reviews, are taken into account.

Does that mean that I would be able to retrieve info on number of starts for a hotel or ratings for restaurants?

A: Rating is Rich content. Rich content is not covered within the base or extended content and is generally provided by third-party data
suppliers.
See more on references from Geocoding and Search API 7 Discover API here https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-discover-brief.html


text:
Q: How to add multiple select statement one bcp command in SQL Server I have a bcp command to create a file with columns and headers. I need to add timestamp at the top of the file and Ctrl C at the end. How do I achieve this?
This works fine with queries having union all.
DECLARE @Query VARCHAR(5000) ='select ''Col1'', ''Col2'', ''Col3'' union all select col1, col2, col3 from TestTable '
DECLARE @cmd1 VARCHAR(5000)='bcp "' + @Query +'" queryout "' +  @File + '" -c -T'

I tried to put them in multiple queries and concatenate them to one query
This is what I tried
DECLARE @Query1 VARCHAR(5000)='Select Getdate();'
DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
DECLARE @Query2 VARCHAR(5000) ='select ''Col1'', ''Col2'', ''Col3'' union all select col1, col2, col3 from TestTable '
DECLARE @Query VARCHAR(5000)=@Query1 + @NewLineChar + @Query2
DECLARE @cmd1 VARCHAR(5000)='bcp "' + @Query +'" queryout "' +  @File + '" -c -T'

The output file should be like this
12/14/18 17:10

Col1 Col2 Col3
1      2   3
4      5   6
^C

A: Simple way will be create a view with header and data (unionall) and query the view in your BCP


text:
Q: GCS GoogleCredential My application has requirement to download file from GCS bucket.I am able to download files from GCS using StorageClient  DownloadObjects method. But performace is really slow. for 50MB file size it is taking 3-4 minutes and this time varies by hugh time difference. Please find sample code and let me know how can I improve downloading performance?
class Program
{
        public static void Main(string[] args)
    {
    GoogleCredentials gcpCreds = new GoogleCredentials()
    {

        private_key = "-----BEGIN PRIVATE KEY-----PrivateKey-----END PRIVATE KEY-----\n",
        client_email = "client_email",
        type = "service_account"
    };
    var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(gcpCreds));

    // var credentials= GoogleCredential.GetApplicationDefault();
    var storage = StorageClient.CreateAsync(credentials).Result;

    string localPath, directoryPath, localFileName, objectName, bucketName;
    directoryPath = "localpathstring";
    objectName = "SourceFileName";
    localFileName = objectName;
    localPath = directoryPath + "\\" + localFileName;
   bucketName="bucketName";

   FileStream fs = new FileStream(localPath, FileMode.OpenOrCreate);

    //Code to download with progress bar
    DownloadObjectOptions option = new DownloadObjectOptions();

    using (fs)
    {
        var progress = new Progress<IDownloadProgress>(
             p => Console.WriteLine($"bytes: {p.BytesDownloaded}, status: {p.Status},"));
        storage.DownloadObject(bucketName, objectName, fs, option, progress);

        }
 }

A: The latency issue you are experiencing can come from either the application, the network (your own or Google's), or the Cloud Storage service. To identify the root cause, here are some steps to follow:

*

*Run mtr to the Cloud Storage endpoint 2 times to determine if/where latency is observed on the network. Command example: mtr -4 -n -r -c 10 www.googleapis.com

*Download the file directly with gsutil to identify if the issue is on the application side.

*Run a performance diagnostic with the "perfdiag" gsutil command to determine any issue on Cloud Storage's side. Command example: gsutil perfdiag -o output.json gs://your-bucket
If results are showing healthy metrics, then it would be worth trying to download the file asynchronously. Finally, here are some tips for optimizing Cloud Storage performance.


text:
Q: custom AuthorizeAttribute should be failing but API runs I have created a custom authorize attribute class for my application, to test if a user is allowed to access the API route. The user I am testing with has had all permissions that this class will test for removed, however the api is still running. What am I doing wrong?
UserActionsDictionary has tenant IDs as the keys and a list of strings for actions.
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Application {
    public class HasActionAttribute : AuthorizeAttribute {

        public string Actions { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            UserCache userCache = HELPERS.GetCurrentUserCache();
            return userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect(Actions.Split(',').ToList()).Any();
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
            filterContext.Result = new HttpUnauthorizedResult("Action not allowed for the current user");
        }
    }
}

And in the controller. I am testing what should be causing the authorize to fail within the route, it should never even make it in, but with breakpoints I am seeing that test is coming out to false.
[Authorize]
public class TestController : ApiController {

    [Route("api/Test/TestRoute")]
    [HttpGet]
    [HasAction(Actions="Test Action")]
    public dynamic Test(){
        UserCache userCache = HELPERS.GetCurrentUserCache();
        bool test = userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect("Test Action".Split(',').ToList()).Any();
        return test;
    }
}

I see a lot of questions here on SO about similar topics, but none seem to address the issue I have here.

A: haim770 answered my issue mostly in the question comments, so I'll put the full answer here for others with similar issues.
I was inheriting the wrong AuthorizeAttribute. I needed to inherit from System.Web.Http not System.Web.MVC. The final code for the attribute is below.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Application {
    public class HasActionAttribute : AuthorizeAttribute {

        public string Actions { get; set; }
        public override void OnAuthorization(HttpActionContext actionContext) {
            UserCache userCache = HELPERS.GetCurrentUserCache();
            List<string> actionsList = Actions.Split(',').Select(a=>a.Trim(' ')).ToList();
            if (!userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect(actionsList).Any()) {
                HandleUnauthorizedRequest(actionContext);
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext) {
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("Action not allowed for the current user") };
        }
    }
}

A: I think that you'd forgotten to put the:
GlobalFilters.Filters.Add(new HasActionAttribute());

in ~/App_Start/FilterConfig.cs.
The FilterConfig is used to manage global filters.
UPDATE:
And change you method to check for null parameter:
protected override bool AuthorizeCore(HttpContextBase httpContext) {
    if(string.IsNullOrWhiteSpace(Actions))
    {
        return true;
    }
    UserCache userCache = HELPERS.GetCurrentUserCache();
    return userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect(Actions.Split(',').ToList()).Any();
}


text:
Q: Intuition behind differentiability I've just started studying multi-variable calculus and I found myself mumbling a lot over the definition of differentiability. Here's the one I'm using. A function if differentiable if
$$\lim_{\vec x \to \vec x_0} \frac{f(\vec x) - f(\vec x_0) - \nabla f\cdot(\vec x - \vec x_0)}{\|\vec x - \vec x_0\|}=0$$
Now, I recall that the gradient gives the direction of maximum increase of the function, and I understand that the term with the gradient gives, in fact, the component of the gradient in the direction of the vector $\vec x - \vec x_0$. What I do not understand is why, rearranging the limit, the limit for $\vec x \to \vec x_0$ of $$\lim_{\vec x \to \vec x_0} \frac{f(\vec x) - f(\vec x_0)}{\|\vec x - \vec x_0\|}$$ has to be precisely
$$\frac{\nabla f\cdot(\vec x - \vec x_0)}{\|\vec x - \vec x_0\|}$$Thank you in advance for your time.

A: Umm. If you require that there be directional derivatives in every direction, but do not place your strong condition on the exact value of the directional derivatives, you can get things such as this:
$$  f(x,y) = \frac{x^2 y}{x^4 + y^2}, \; \; f=0 \; \mbox{along axes}  $$
Along the line $y=mx$ for nonzero $m,$ we have
$$ f(x,mx) = \frac{mx}{m^2 + x^2},  $$
so there is a directional derivative corresponding to that line, with value $1/m.$
The bad news is that the function is not even continuous at the origin:
$$ f(x,x^2) = \frac{1}{2},  $$
$$ f(x,-x^2) = \frac{-1}{2}.  $$


text:
Q: TypeScript: ES2015 string property 'repeat' not recognized Condition: I'm working on Win10, TypeScript 1.8, and Visual Studio Code 1.0.0. I have code like
///<reference path = "./typings/lib.es6.d.ts" />

and, later
let z = "0".repeat(4 - str.length)

This is the let z line.
VS Code put red underlines under "repeat" and reported
[ts] Property 'repeat' does not exist on type 'string'.

I compiled at the command line with
tsc <filename>.ts

Pointing at the start of repeat in the let z line, the compiler reported
error TS2339: Property 'repeat' does not exist on type 'string'.

Beggin' to differ, TypeScript, but that was added with ES2015 (ES6).
Question: How can I get a clean compile?
EDITS: Shortened.

A: In my case, I only changed this line on tsconfig.json file:
Before:
"compilerOptions": {
    "target": "es5"
}

After:
"compilerOptions": {
    "target": "es6"
}

A: What ended up working for me was:
(1) Remove all references to d.ts files and compile. It seemed some of my problems came from overlapping definitions in various d.ts files. With all of those files gone, the compile told me what problems were "real". One of them was this one.
(2) In my project directory, I created a typings directory. I'll make a habit of putting almost all d.ts files there. Modules get a directory there. (For instance, I have a typings\node that holds node.d.ts.)
(3) In typings, I have a file I'm slowly building; some call it globals.d.ts and lots of people seem to prefer index.d.ts. In it, I put all the solutions I've needed. This was one of them; string.substr was a second. The relevant part of that file:
interface String {
    repeat(count: number): string
    substr(from: number, length?: number): string
}

And where'd I get that? Anywhere with something that works! I found these two lines in a copy of lib.es6.d.ts.
(4) Cite that file in your source code via /// <reference path="./typings/index.d.ts" /> (subject to whatever you call the file). Compile. Repeat (3) as needed. When all the errors go away, my d.ts is complete enough. Someday, I'm bound to add more source code that'll need more here, but that's a later problem.
Is everything sweetness and light? Certainly not.
I'm past this error, but there's another that is particularly perplexing.
I've read some development tickets the TypeScript team shares with the public. They definitely understand the whole problem. It's not easy to fix. They're chipping away at it. When they're done, I think they hope this will no longer be a problem.
Sometimes, even with the amazing resource of typings on npm, the most recent version of a d.ts file I can find seems likely to be out of date. (The most recent version of node.d.ts is labeled for v4.x; I'm using v5.11 and v6.0 is out. Of course, v4.4 is the long-term-support version most suitable for production use. Sure. Still, I'm not fully confident I'll always be able to find a solution.)
If the lines in those files make my errors go away, they're good enough for me. Sometimes, they don't.
If I can figure out the typings on my own, that's best case. I'm developing toward full ability to do that. (So ... sometimes, I can't! Sigh.)
I'll be glad to understand everything related to these issues!

A: In my special case (perhaps very special!) "files" entry in tsconfig.json had pointed to an incorrect file.
{
    "compilerOptions": {
        ...
    },
    "exclude": [
        ...
    ],
    "files": [
        "src/wrong.ts"  // <= CHECK THIS
    ]
}


text:
Q: Tracking how long a viewer has viewed a certain video I am trying to track how long a viewer has viewed a certain video and I'm a bit confused as to what some of the media events do in React JS.

*

*When a video is skipped to a later part of the video and stops for a bit does it call onPause without actually needing to press the pause button?

*Also I am confused as to what onTimeUpdate does.

A: Please take a look at the HTML Audio/Video Event Listeners reference here:
https://www.w3schools.com/tags/ref_av_dom.asp
You'll probably need the 'readystate' property :

Represents the ready state of the audio/video element:
0 = HAVE_NOTHING - no information whether or not the audio/video is
ready
1 = HAVE_METADATA - metadata for the audio/video is ready
2 = HAVE_CURRENT_DATA - data for the current playback position is
available, but not enough data to play next frame/millisecond
3 = HAVE_FUTURE_DATA - data for the current and at least the next
frame is available
4 = HAVE_ENOUGH_DATA - enough data available to start playing

So, I would imagine you use a counter on a setTimeout to count how long the video has been played for:
var counter = 0;
var timer = setTimeout(function() {
    var vid = document.getElementById("myVideo");
    var state = vid.readystate;
    if( state != 0 ) counter++;
    console.log( counter + " seconds its been played" );
} , 1000 );


text:
Q: Cómo usar un array y subir archivos usando ajax y PHP? Hola buenas tardes a todos tengo un problemita cuando intento enviar imagen o archivo por ajax, lo que pasa estoy usando una librería typeahead y tagmanager para agregar tags con consulta a BD y lo almaceno en un array para luego procesarlas en donde lo hice bien pero cuando agrego new FormData(this); para subir archivos en el post no me envía nada.
Eso usando en mis otros formularios sin eso de tags funciona bien pero el array que esta almacenado en js no funciona con subir archivos al mismo tiempo array y subir archivo.
Cuando lo hago sin file normal me proceso pero con el file me da problema espero su ayuda.
Imagen 1 cuando no tiene el file normal se envía al post.

Imagen 2 cuando agrego el file en el JS

JS

PHP
$data = json_decode($_REQUEST['arraypasar']);

/* $archivo = $_FILES["archivo_add"]['name']; */

parse_str($_REQUEST['datos'], $valores);

/* echo $archivo; */

echo "
";
echo $valores['area2'];

echo "

";
echo "
";
print_r($data);
echo "
";

A: Hola bueno lo resolví de la manera siguiente tuve que separar el array de tags del submit llamando dentro del post.php a la función para que procese el array creado. No quería separarlo pero esa idea se me ocurrió pensaba hacerlo en uno solo.
Bueno ahí les dejo mi código como lo resolví para quienes usan tags.
Saludos.
//AQUI AGREGA LOS TAGS Y LO ALMACENO EN UN ARRAY
    var miArray = [];
        v = 0;

        function quitararea(v) {
            valor = v - 1;
            miArray.splice(valor, 1);
            console.log(miArray);
        }
        $(document).ready(function() {
            var tags = $(".tm-input").tagsManager();
            jQuery(".typeahead").typeahead({
                source: function(query, process) {
                    return $.get('consulta_sql.php', {
                        query: query
                    }, function(data) {
                        data = $.parseJSON(data);
                        return process(data);
                    });
                },
                afterSelect: function(item) {
                    var divisiones = item.split(" - ");
                    agregar = [divisiones[0], divisiones[1]];

                    for (var i = 0; i < miArray.length; i++) {
                        if (miArray[i][0] == divisiones[0]) {
                            alert("Ya se encuentra agregada la área!");
                            $('#area').val('');
                            return miArray;
                            break;
                        }
                    }
                    tags.tagsManager("pushTag", divisiones[1]);
                    $('#area').val('');
                    miArray.push(agregar);
                    console.log(miArray);
                    return miArray;
                }
            });
        });

//SUBMIT DEL FOMULARIO
        $("#enviar").submit(function(event) {
            var parametros = $(this).serialize();
            var data = new FormData(this);

            $.ajax({
                type: "POST",
                cache: false,
                url: "post.php",
                data: parametros,
                data: data,
                processData: false,
                contentType: false,
                success: function(datos) {
                    $("#resultado").html(datos);

                }
            });
            event.preventDefault();
        });

//FUNCION QUE HACE RECOGER EL ARRAY CREADO
        function copia(codigo) {
            arraypasar = JSON.stringify(miArray);
            var doc = $("#area2").val();
            var folios = $("#area3").val();
            var arrayparametros = {
                arraypasar: arraypasar,
                codigo: codigo,
                doc: doc,
                folios: folios
            };
            $.ajax({
                type: "POST",
                cache: false,
                url: "post2.php",
                data: arrayparametros,
                success: function(data) {
                    $("#resultado2").html(data);

                }
            });
        };


text:
Q: Why does the simpler oc statement take a longer time?
I am using Xcode Instruments Time Profiler to analyse some Objective-C code, and the statement self.tbNavigationItem.tbNavibarRightItem = nil; took a longer time than self.tbNavigationItem.tbNavibarRightItem = [[TBBarButtonItem alloc] initWithCustomView:settingBtn];, anyone can explain?


text:
Q: ee_extract after normalizing image (zero mean and unit variance) I have working code for normalizing an image. Is there a more efficient way to achieve the same result and cut down on the steps involved?
Asking because after finalizing this workflow on a per-Image basis, will want to adapt to a per-ImageCollection workflow (not sure how to do that yet) to extract time series.
Using rgee with Google Earth Engine.
Thank you!
# Load libraries
library(rgee)

# Initialize gee
ee_Initialize()

# Define ImageCollection
viirs <- ee$ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG")$
    filterDate("2020-01-01", "2020-01-31")$
    select('avg_rad')$
    first()

# Define AOI
tls <- ee$Feature(ee$FeatureCollection("FAO/GAUL/2015/level0")$
    filter(ee$Filter$eq('ADM0_NAME', 'Republic of Korea'))$
    first())$
    geometry()

# Clip
ntl_tls <- viirs$clip(tls)

# Calculate mean and SD
mu  <- ntl_tls$reduceRegion(reducer=ee$Reducer$mean())
std <- ntl_tls$reduceRegion(reducer=ee$Reducer$stdDev())

# Cast these to native ee Numbers using the ee.Number constructor
mu <- ee$Number(mu$get('avg_rad'))
std <- ee$Number(std$get('avg_rad'))

# By pixel: Subtract mean and divide by SD to normalize
ntl_tls_clean <- ntl_tls$subtract(mu)$divide(std)

# Extract computation
NTL <- ee_extract(
    x = ntl_tls_clean,
    y = tls,
    scale = 20,
    fun = ee$Reducer$sum(),
    sf = FALSE
)

# Show result (one data point)
print(NTL)

For sanity check, can plot map for the two images (original vs normalized):
# Plot raw map for sanity check
Map$centerObject(ntl_tls, zoom=7)
map_raw <- Map$addLayer(
    eeObject = ntl_tls,
    visParams = list(
    #min=0,
    #max=0.0002,
    palette=c('000000','700000','808080','FFFF00','ffffff','ffffff','ffffff')
    ))
map_raw

# Plot cleaned map for sanity check
Map$centerObject(ntl_tls_clean, zoom=7)
map_clean <- Map$addLayer(
    eeObject = ntl_tls_clean,
    visParams = list(
        #min=0,
        #max=0.0002,
        palette=c('000000','700000','808080','FFFF00','ffffff','ffffff','ffffff')
    ))
map_clean

Raw image from band
Normalized image


text:
Q: Does SageMaker Feature Store use Athena queries (data virtualization) to make its queries performant? SageMaker boasts rapid performance for reading data from batch and online. I am wondering what is happening behind the scenes. Are these Athena queries behind the scenes that the feature stores uses? Is it accessing materialized views, or are these queries running against partitioned data in S3 directly (and thus faster due to partitioning rather than materialized views)?

A: The video goes into the high-level details of FeatureStore and this E2E sample shows how to query against the offline data store.


text:
Q: Using scanf to read in certain amount of characters in C? I am having trouble accepting input from a text file. My program is supposed to read in a string specified by the user and the length of that string is determined at runtime. It works fine when the user is running the program (manually inputting the values) but when I run my teacher's text file, it runs into an infinite loop.
For this example, it fails when I am taking in 4 characters and his input in his file is "ABCDy". "ABCD" is what I am supposed to be reading in and 'y' is supposed to be used later to know that I should restart the game. Instead when I used scanf to read in "ABCD", it also reads in the 'y'. Is there a way to get around this using scanf, assuming I won't know how long the string should be until runtime?

A: Normally, you'd use something like "%4c" or "%4s" to read a maximum of 4 characters (the difference is that "%4c" reads the next 4 characters, regardless, while "%4s" skips leading whitespace and stops at a whitespace if there is one).
To specify the length at run-time, however, you have to get a bit trickier since you can't use a string literal with "4" embedded in it. One alternative is to use sprintf to create the string you'll pass to scanf:
char buffer[128];

sprintf(buffer, "%%%dc", max_length);
scanf(buffer, your_string);

I should probably add: with printf you can specify the width or precision of a field dynamically by putting an asterisk (*) in the format string, and passing a variable in the appropriate position to specify the width/precision:
int width = 10;
int precision = 7;
double value = 12.345678910;

printf("%*.*f", width, precision, value);

Given that printf and scanf format strings are quite similar, one might think the same would work with scanf. Unfortunately, this is not the case--with scanf an asterisk in the conversion specification indicates a value that should be scanned, but not converted. That is to say, something that must be present in the input, but its value won't be placed in any variable.

A: Try
scanf("%4s", str)

A: You can also use fread, where you can set a read limit:
char string[5]={0};
if( fread(string,(sizeof string)-1,1,stdin) )
  printf("\nfull readed: %s",string);
else
  puts("error");

A: You might consider simply looping over calls to getc().


text:
Q: Swap adjacent element of an array in JAVA q1:write a program to print following output from given input=
input: aaa bbb ccc ddd eee fff ggg hhh iii jjj
output: bbb aaa ddd ccc fff eee hhh ggg jjj iii
SOLUTION:
package practice;

import java.io.*;
import java.util.*;

public class happy {
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        String t;
        String arr[]=new String[n];
        for(int i=0;i<n;i++)
        {
            arr[i]=in.nextLine();
            t=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=t;
        }
        System.out.println(arr);
    }
}

where did i went wrong can anybody please provide solution in java?

A: Take the input string a split it using using the Java split() method and store the output into a String array. From there it becomes easy.
 Scanner scanner = new Scanner(System.in);
 String [] inputArr = scanner.nextLine().split(" ");
 for(int i = 0; i < inputArr.length; i++)
 {
    if( ( i+1 ) % 2 == 0 )
    {
        String temp = inputArr[i-1];
        inputArr[i-1] = inputArr[i];
        inputArr[i] = temp;
    }
 }

You're working in pairs of two's. The pairs can be easily checked by using the modulus of the current element (adding 1 to it because of the way indexing works). When the if-statement triggers (when there is no remainder), it simply swaps the two elements.
You could also probably use a built-in method, so check the Java Documentation at https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html if you'd like a more cleaner and perhaps more efficient way of doing this.


text:
Q: How to make a react global state re-render component? I have tried using two different libraries to handle this issue and both time I get the same behavior.
Libraries tried: OvermindJS, Hookstate
When I click the button I can see the state change is beeing logged in the console but the component will only re-render on the second click
If I change page:

*

*click Home

*click Page1

*click No Funds

Then it will show 1$
If I click straightway the No Funds button without changing page (first action on page) then the button will not re-render until it is clicked twice.
App.tsx
import * as React from "react"
import {
  ChakraProvider,
  Box,
  Text,
  Grid,
  theme,
} from "@chakra-ui/react"
import { Switch, Route } from "wouter"
import { Appbar } from "./common/AppBar"

export const App = () => (
  <ChakraProvider theme={theme}>
    <Appbar />
    <Box textAlign="center" fontSize="xl">
      <Grid minH="100vh" p={3}>
        <Switch>
          <Route path="/">
            <Text mt={100}>Home</Text>
          </Route>
          <Route path="/home">
            <Text mt={100}>Home</Text>
          </Route>
          <Route path="/page1">
            <Text mt={100}>Page 1</Text>
          </Route>
        </Switch>
      </Grid>
    </Box>
  </ChakraProvider>
)

AppBar.tsx
import React, { ReactNode } from "react";

import {
    Box,
    Flex,
    HStack,
    Link,
    IconButton,
    Button,
    Icon,
    useDisclosure,
    useColorModeValue,
    Stack,
} from '@chakra-ui/react';
import { HamburgerIcon, CloseIcon } from '@chakra-ui/icons';
import { MdAccountBalanceWallet } from 'react-icons/md'
import { useLocation } from 'wouter';
import { actionIncrementFunds, globalState } from "../hookState/state";
import { useState } from "@hookstate/core";
const Links = ['Home', 'Page1'];

const NavLink: React.FC<any> = ({ children, handleClick }: { children: ReactNode, handleClick: any }) => (
    <Link
        px={2}
        py={1}
        rounded={'md'}
        _hover={{
            textDecoration: 'none',
            bg: useColorModeValue('red.200', 'red.300'),
        }}
        onClick={() => handleClick(children)}>
        {children}
    </Link>
);

export const Appbar: React.FC = () => {
    const state = useState(globalState);

    const { isOpen, onOpen, onClose } = useDisclosure();
    const [location, setLocation] = useLocation();
    const handleClick = (path: string) => {
        setLocation(`/${path.toLowerCase()}`)
    }

    const hasFunds = () => {
        return state.currentFunds.get() > 0
    }

    const handleConnectWallet = () => {
        actionIncrementFunds()
    }
    return (
        <>
            <Box zIndex={900} position={"fixed"} top={0} left={0} width="100%" bg={useColorModeValue('gray.100', 'gray.900')} px={4}>
                <Flex h={16} alignItems={'center'} justifyContent={'space-between'}>
                    <IconButton
                        size={'md'}
                        icon={isOpen ? <CloseIcon /> : <HamburgerIcon />}
                        aria-label={'Open Menu'}
                        display={{ md: 'none' }}
                        onClick={isOpen ? onClose : onOpen}
                    />
                    <HStack height={"100%"} spacing={8} alignItems={'center'}>
                        <HStack
                            as={'nav'}
                            spacing={4}
                            display={{ base: 'none', md: 'flex' }}>
                            {Links.map((link) => (
                                <NavLink handleClick={handleClick} key={link}>{link}</NavLink>
                            ))}
                        </HStack>
                    </HStack>
                    <Flex alignItems={'center'}>
                        {hasFunds()
                            ? <Button
                                variant={'solid'}
                                colorScheme={'red'}
                                size={'md'}
                                onClick={handleConnectWallet}
                                mr={4}>
                                {state.currentFunds.get()} $
                            </Button>
                            : <Button
                                variant={'solid'}
                                colorScheme={'red'}
                                size={'md'}
                                mr={4}
                                onClick={handleConnectWallet}
                                leftIcon={<Icon as={MdAccountBalanceWallet} />}>
                                No Funds
                            </Button>
                        }
                    </Flex>
                </Flex>

                {
                    isOpen ? (
                        <Box pb={4} display={{ md: 'none' }}>
                            <Stack as={'nav'} spacing={4}>
                                {Links.map((link) => (
                                    <NavLink handleClick={handleClick} key={link}>{link}</NavLink>
                                ))}
                            </Stack>
                        </Box>
                    ) : null
                }
            </Box >
        </>
    );
}

Behavior example:

Repo with example for Hookstate:
https://github.com/crimson-med/state-issue
Repo with example for OvermindJS:
https://github.com/crimson-med/state-issue/tree/overmind
How can I get the button on change on the first click?


text:
Q: Алгоритм присвоения победы в Delphi Я создаю игру крестики-нолики. Мне надо ввести проверку на победную комбинацию. При компиляции кода, победной комбинацией является только последний if, а первый пропускается, а это я только считываю победу крестиков без учета комбинаций по диагонали.
procedure TForm1.win;
var
  i: integer;
begin
  for i:=1 to 3 do
    if gg[i,1] and gg[i,2] and gg[i,3]=1 then
    begin
      final:=true
    end
    else
    begin
      if gg[1,i] and gg[2,i] and gg[3,i]=1 then
      begin
        final:=true;

A: Попрактикую телепатию.
for i:=1 to 3 do
   if (gg[i,1]=1) and (gg[i,2]=1) and (gg[i,3]=1) then
      final:=true
   else
     if (gg[1,i]=1) and (gg[2,i]=1) and (gg[3,i]=1) then
       final:=true;

Наверное, лучше будет так:
for i:=1 to 3 do
   if (gg[i,1]=1) and (gg[i,2]=1) and (gg[i,3]=1) or
      (gg[1,i]=1) and (gg[2,i]=1) and (gg[3,i]=1) then begin
       final:=true;
       break;
   end;