text:
Q: OpenOCD and Eclipse, wrong settings? As I migrated from the old Eclipse installation that comes with my Olimex STM32-E407 board I came across some difficulty with the OpenOCD installation.
The old Eclipse settings worked fine; a Zylin embedded debugger with the following init script:
target remote localhost:3333
monitor reset halt
monitor wait_halt
monitor sleep 100
monitor poll
monitor flash write_image erase main.bin 0x08000000
monitor sleep 200

And this run script:
monitor soft_reset_halt
monitor wait_halt
monitor poll
thbreak main
continue

Since I switched to the new Eclipse I could choose a different debugger as Zylin seems to be outdated (latest Google results were prior to ~2010). In Eclipse Neon, I opted for GDB OpenOCD Debug which will start from the same OpenOCD instance as the old Eclipse. It will not launch the executable from Eclipse itself.
The OpenOCD script looks like the following:
-f ../scripts/interface/ftdi/olimex-arm-usb-tiny-h.cfg
-f ../scripts/board/olimex_stm32_e407.cfg

At the Startup tab I copied the initalization and run commands per above, changed main.bin to Dev.elf and saved the settings.
Starting debug from Eclipse yields in the output below. Even when I use the original main.bin from the old eclipse - which worked previously! - I cannot seem to get around this issue.
Open On-Chip Debugger 0.10.0-rc1
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "jtag". To override use 'transport select <transport>'.
adapter speed: 2000 kHz
adapter_nsrst_delay: 100
jtag_ntrst_delay: 100
none separate
cortex_m reset_config sysresetreq
Info : clock speed 2000 kHz
Info : JTAG tap: stm32f4x.cpu tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4)
Info : JTAG tap: stm32f4x.bs tap/device found: 0x06413041 (mfg: 0x020 (STMicroelectronics), part: 0x6413, ver: 0x0)
Info : stm32f4x.cpu: hardware has 6 breakpoints, 4 watchpoints
Info : accepting 'gdb' connection on tcp/3333
Info : device id = 0x10076413
Info : flash size = 1024kbytes
undefined debug reason 7 - target needs reset
adapter speed: 2000 kHz
Info : JTAG tap: stm32f4x.cpu tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4)
Info : JTAG tap: stm32f4x.bs tap/device found: 0x06413041 (mfg: 0x020 (STMicroelectronics), part: 0x6413, ver: 0x0)
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080002b8 msp: 0x20020000
adapter speed: 8000 kHz
Info : dropped 'gdb' connection
Info : accepting 'gdb' connection on tcp/3333
adapter speed: 2000 kHz
Info : JTAG tap: stm32f4x.cpu tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4)
Info : JTAG tap: stm32f4x.bs tap/device found: 0x06413041 (mfg: 0x020 (STMicroelectronics), part: 0x6413, ver: 0x0)
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080002b8 msp: 0x20020000
background polling: on
TAP: stm32f4x.cpu (enabled)
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080002b8 msp: 0x20020000
auto erase enabled
Error: couldn't open Dev.elf

adapter speed: 2000 kHz
Info : JTAG tap: stm32f4x.cpu tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4)
Info : JTAG tap: stm32f4x.bs tap/device found: 0x06413041 (mfg: 0x020 (STMicroelectronics), part: 0x6413, ver: 0x0)
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080002b8 msp: 0x20020000
adapter speed: 8000 kHz
Info : Padding image section 0 with 1 bytes
adapter speed: 2000 kHz
Info : JTAG tap: stm32f4x.cpu tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4)
Info : JTAG tap: stm32f4x.bs tap/device found: 0x06413041 (mfg: 0x020 (STMicroelectronics), part: 0x6413, ver: 0x0)
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x080002b8 msp: 0x20020000
Info : dropped 'gdb' connection

What surprises me is how it keeps reconnecting GDB and the fact that the adapter speed is switching. What am I doing wrong?

A: I have found a solution for the time being.

*

*Add a debug option in GDB Hardware Debugging

*Use gdb command 'arm-none-eabi-gdb' - you require the executable in your PATH environment.

*Use remote target 'Generic TCP/IP' as JTAG device on localhost:3333

*Go to the Startup tab and select default settings. Initalization commands:
monitor reset halt
monitor flash write_image erase main.bin 0x08000000
monitor sleep 200

*The used run commands are:
monitor soft_reset_halt
monitor wait_halt
monitor poll
thbreak main
continue

This uses the 'old' main.bin from my initial Eclipse example project. If you use the .elf file you should use this instead:
monitor flash write_image erase main.elf

This is due to the fact that .elf contain all the required headers.


text:
Q: Clustering data in a file I have a file in the following format
--
752721  1
757734  1
757936  1
758144  1
758324  1
--
842825  1
843940  1
--
1301199 1
--
--
1302408 1
1302555 1
--
--
--
--
1306558 1
1307638 1
1308628 1

The '--' is a delimiter. I want to cluster these entries together like this:
752721 - 758324 5
842825 - 843940 2
1301199 1
1302408 - 1302555 2
1306558 - 1308628 3

where the range of a cluster is displayed and the count of the number of elements in it are appended next to the range.
I tried few options in awk and sed. Somehow they didn't work out. Any other suggestions are welcome.

A: $ awk 'function out(){if (count>0)printf "%s - %s %s\n",first,last,count;count=0}; /--/{out()} NF<2 {next} count==0{first=$1} {last=$1;count+=1} END{out()}' file2
752721 - 758324 5
842825 - 843940 2
1301199 - 1301199 1
1302408 - 1302555 2
1306558 - 1308628 3

How it works
This code uses three variables.  first and last denote the range and count is the number of lines found in that range.

*

*function out(){if (count>0)printf "%s - %s %s\n",first,last,count;count=0}
This defines a function out which, if there is a cluster to be printed, that is if count>0, prints the cluster.

*/--/{out()}
Every time we reach a delimiter, call function out to print out any cluster data.

*NF<2 {next}
If this is an empty line or a delimiter line, skip the rest of the commands and jump to the next line

*count==0{first=$1}
If this is the first line of a cluster, set first.

*{last=$1;count+=1}
Update last and count.

*END{out()}
At the end of the file, print the data for the last cluster.
Refinement
This version matches the desired output more closely.  It does not print "first - last" when first and last are the same:
$ awk 'function out(){if (count>0){printf "%s ",first; if(first!=last)printf"- %s ",last; print count;count=0}}; /--/{out()} NF<2 {next} count==0{first=$1} {last=$1;count+=1} END{out()}' file
752721 - 758324 5
842825 - 843940 2
1301199 1
1302408 - 1302555 2
1306558 - 1308628 3

This is accomplished by changing the logic in the out function to:
function out(){
    if (count>0){
        printf "%s ",first
        if(first!=last)
            printf"- %s ",last;
        print count;count=0;
    }
}

A: with open('/path/to/output') as infile:
    buffer = []
    for line in infile:
        line = line.split()[0]
        if line == '--':
            if buffer:
                print("{} - {} {}".format(buffer[0], buffer[-1], len(buffer)))
                buffer = []
        else:
            buffer.append(int(line))
    if buffer:
        print("{} - {} {}".format(buffer[0], buffer[-1], len(buffer)))

Output:
752721 - 758324 5
842825 - 843940 2
1301199 - 1301199 1
1302408 - 1302555 2
1306558 - 1308628 3

A: Code which reads from stdin (or a filename passed as the first command line argument):
import fileinput

def report(first,last,count):
  if first == last:
    print first, count
  else:
    print first, "-", last, count

first = None
last = None
count = 0
for line in fileinput.input():
  line = line.strip()
  if line == "--":
    if last:
      report(first, last, count)
    last = first = None
    count = 0
  else:
    words = line.split()
    i = words[0]
    n = int(words[1])
    if not first:
      first = i
      count = 0
    last = i
    count = count + n
if first:
  report(first, last, count)

redpajama_set_name: RedPajamaStackExchange


text:
Q: angularjs how to use service $scope variable in another function In my angularjs html file, i am reading a file data using a service and showing data in directive. It is working fine in displaying treeview. I have put a ng-click "ShowDetailsFunc()" for each item and want to get details from the variable ($scope.testdata). The problem is the data which i am getting from service is not accessible from ng-click function and shows as "undefined". i understand that $scope.testdata takes some time to get value as it comes from $http service but i am also trying to get once it is fully loaded. As far i understand once $scope variable is set, should be accessible in entire controller function and can be accessed anywhere.
I thought of using $watch but I think it is used for watching a normal variable. please help if my understand is not right or i am making some mistake somewhere.
My directive as below,
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '='},
        template: "
<member ng-repeat='member in collection' member='member'></member>
"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "
{{member.NodeName}}
";
    var linkerfunc = function(scope, element, attrs) {
                    var collectionSt = '<collection collection="member.children"></collection>';
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        element.append(cloned);
                     });
                    scope.ShowDetailsFunc = function() {
                        scope.ShowDetailsCtrlFunc(element,event);
                    }

    }
    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'TreeController',
        link: linkerfunc
    }
})

And my controller function,
mainApp.controller('TreeController', function ($scope,$http,getTestDataService,$timeout) {
    $scope.Intialfunc = function() {
        $scope.testdata = []
        var filename = 'D:\\myxmlfile.xml'
            getTestDataService.gettestdata(filename).then(function success(response){
                $(response.data.children).each(function(index,value){
                $scope.testdata.push(value);
                })
            console.log($scope.testdata) // showing data here.
            });
        }
    $scope.ShowDetailsCtrlFunc = function(element,event) {
            console.log("in function ShowDetailsCtrlFunc"); // coming to this fucntion on click.
            console.log($scope.testdata) // but this one is not showing . shows undefined.
            .....................................
            some other code using $scope.testdata
            .....................................

            event.stopImmediatePropagation();
      };
});

A: By default angular would not bind this of directive to the controller, to achieve this you should use bindToController property in return statement of directive. For more details check this


text:
Q: How to get Inner repeater Label Control in Outer Repeater's ItemDataBound I have Nested Repeater.
I binded inner repeater in outer repeater's ItemDataBound.
protected void rptrOuter_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
 Repeater rptrInner = (Repeater)e.Item.FindControl("rptrInner ");
  List<String> objList = new List<String>();
            objList = GetListofData().ToList();
 rptrInner .DataSource = objList ;
            rptrInner .DataBind();
   Label lblName = rptrInner .FindControl("lblName") as Label;
//Error Object reference not set to an instance of an object.

}

Even i tried  Label lblName = e.Item.FindControl("lblName") as Label;
in single repeater will get label like
Label lblId= e.Item.FindControl("lblId") as Label;

Like this how can i get nested repeater's Label inside outer repeater??
Please help me...

A: You seem to be trying to locate the inner repeater using the event arguments. If it's contained in the outer repeater and that's what's raising the event, it should be contained in the sender. I'm not 100% on how the syntax would look, but going off of what you wrote, try something like this:
Repeater rptrInner = ((Repeater)sender).FindControl("rptrInner");


text:
Q: XP - ping changes routing table? I have got a real strange behaviour with one of my XP-Sp3 machines.
Setup:
  A Server in the lan (192.168.5.0) proviedes access to all roadwarriors in 10.8.0.0
  The DCHP has a static route for all clients pronouncing 192.168.5.235 as gateway for 10.8.0.0
All Clients can ping & access the vpn-machines; everything works like a charm
But one Xp-Sp3 is not willing to connect to them. It gets all the same routes as any other sytem in the lan and I trippel-checked - there are no static routes on this machine
When I ping any 10.8.0.0 device from this machine, the first two packaged work like a charm; but the next two (and any package after them) fail and get lost.
When I look back into the routing table: There is a new route; a special one just for the device I pinged, which points to the right gateway - but which wasn't there earlier...
As Long as this route exists the machine can't ping anything on 10.8.0.0.
  But if I remove the route by hand: The next to ping packages work fine...
Has anybody got an idea about that? Anybody every seen such a behaviour? Any hint / help / tip is greatly appreachiated!
thx in advance
Corelgott
Ps: I attach an image of the cmd to clarify things - its in german, but reading a routing table shouldn't be that hard...
strage?! http://two-nerds.com/route.jpg

A: Is the netmask for the 10.8.0.0 route correct? From what I see here, I think you would want 255.255.0.0 instead of 255.255.255.255. What type of VPN are you using?
EDIT: What do the routing tables on the working machines show when you perform the same procedure?

A: That seems to be the result of ICMP REDIRECT packets (essentially, a router can elect to say "this is a better route AND it is local to your network" when its next hop is on the same network as the source).


text:
Q: htaccess rewrite using query string and set cookie I am trying to write a specific rewrite rule using a query string and also a saved cookie value.
The rewrite rule for query string works (on its own):
RewriteRule ^product/(.*)$ products.php?prodName=$1 [L]

which gives me:

www.mydomain.com/product/productName

However I would also like to add into the url the saved cookie value.
The cookie value is based on directory: /, /uk, /us, /tw
So the result I am after will be:

www.mydomain.com/uk/product/productName


text:
Q: Speed up an implementation of Boyer-Moore-Horspool string search I have a bit of trouble implementing the BMH algorithm in C++.
Here's the code:
#define Nm 2000005
int D[256];
char To[Nm],P[Nm],*T;
int Tl,Pl;
int cont;
void initialize_Lenght()
{
    Tl=strlen(To);
    Pl=strlen(P);
    T=To;
}
void compute_D()
{
    for(int i=0;i<256;i++)
        D[i]=Pl;
    for(int i=0;i<Pl;i++)
        D[P[i]]=Pl-i;
}
void Boyer_Moore()
{
    int i;

    while ( Tl>=Pl )
    {
        for(i=Pl-1;T[i]==P[i]&&i>=0;i--)
            if(i==0)
            {
                if(cont<1000)
                    v[cont]=(T-To); // I also have to store the first 1000 values
                cont++;
            }
            Tl -= D[T[i+1]];
            T += D[T[i+1]];
    }
}

It works for most examples but there are some examples that do not work (only ones which I found thus far are huge tests downloaded from different sources).
I would want to know where / what I am doing wrong (I do not really want code).
Edit: Due to comments
Do you have any idea how I could make this algorithm run faster without implementing a full Boyer-Moore version of it?

A: The order of tests in
for(i=Pl-1;T[i]==P[i]&&i>=0;i--)

is wrong. After a complete match, you compare T[-1] to P[-1] before checking whether the index is admissible.
If a mismatch occurs at the last pattern character,
Tl -= D[T[i+1]];
T += D[T[i+1]];

skips according to a character that need not exist (if the pattern end is aligned with the text end).


text:
Q: No variants found for `react-native-reanimated` I upgraded my React Native project to Gradle 7.0.2 and now when I open Android Studio it says No variants found for ':react-native-reanimated'. I'm using react-native-reanimated@1.13.3, and from the documentation for versions 1.x.x there's no real configuration, so I'm not sure how to approach this.
Has anyone run into anything similar? I'm using react-native@0.63.4, gradle 7.0.2, and Android Gradle Plugin 7.0.0.

A: You need to downgrade your Gradle version 7 to 6 because somehow Gradle 7 not work with react-native-reanimated 1.13.3. You can downgrade the version from gradle-wrapper.properties file like below:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-all.zip


text:
Q: Find expected value of continuous density distribution - integration problem
I need to find the expected value of a random variables Y with density $$p(y;\theta)=\theta(1-y)^{\theta-1},\ \theta > 0,\ y \in(0,1)$$

Based on the definition of expected value:
$$\mathbb{E}(Y) = \int^1_0y\theta(1-y)^{\theta-1}dy$$
I think I can solve it with integration by parts but I'm need a hint :-)
Edit with solution
$$\mathbb{E}(Y) = \int^1_0y\theta(1-y)^{\theta-1}dy=\theta\left[-\frac{(1-y)^{\theta}}{\theta}y\ \Bigg |_0^1-\int^1_0\left(-\frac{(1-y)^{\theta}}{\theta}\right)dy\right]=\frac{1}{1+\theta}$$
Alternative solution
The definition of beta function is $B(\alpha,\beta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}$. When $\alpha$ and $\beta$ are positive integer
$B(1,\theta)=\frac{\Gamma(1)\Gamma(\theta)}{\Gamma(1+\theta)}=\frac{(\theta-1)!}{\theta!}=\frac{1}{\theta}$.
In this case $p(y;\theta)=\theta(1-y)^{\theta-1}\sim Beta(1,\theta)$ so $\mathbb{E}(Y)=\frac{1}{1+\theta}$

A: If you don't want to use integration by parts, change variables $1-y=t$. You get
$$
\mathbb{E}(Y) = \int^1_0y\theta(1-y)^{\theta-1}dy=\theta\int_0^1 dt (1-t)t^{\theta-1}=\theta\left[\int_0^1 dt\ t^{\theta-1}-\int_0^1 dt\ t^{\theta}\right]\ ,
$$
and the two integrals are now elementary.


text:
Q: d3 force only display certain links and nodes on click I've got a force directed layout set up in d3, but I'm trying to make it so that only certain links and nodes display, in accordance with a horizontal group of buttons I have set up.
Essentially, the force layout would display links and nodes based on whatever buttons are toggled on. For example, if I click on academia, federal, and commonwealth, only the links and nodes under those groups would display in my visualization. Does anyone know how I can set this up?
Here is a link to my code: https://plnkr.co/edit/QZ8chcsOj64oYJnIqz1J?p=preview
Here are my buttons (lines 27-64 in index.html):

        <svg height="20" width="300">
            <circle cx="15" cy="12" r="4" stroke="black" stroke-width="1" fill="orange" fill-opacity="0.6" />
            <text x="25" y="16" font-family="serif" font-size="12px">Non-Governmental Organizations</text>
        </svg>

        <svg height="20" width="300">
            <circle cx="15" cy="12" r="4" stroke="black" stroke-width="1" fill="steelblue" fill-opacity="0.6" />
            <text x="25" y="16" font-family="serif" font-size="12px">Academia</text>
        </svg>

        <svg height="20" width="300">
            <circle cx="15" cy="12" r="4" stroke="black" stroke-width="1" fill="green" fill-opacity="0.6" />
            <text x="25" y="16" font-family="serif" font-size="12px">Commonwealth</text>
        </svg>

        <svg height="20" width="300">
            <circle cx="15" cy="12" r="4" stroke="black" stroke-width="1" fill="red" fill-opacity="0.6" />
            <text x="25" y="16" font-family="serif" font-size="12px">Federal</text>
        </svg>

        <svg height="20" width="300">
            <circle cx="15" cy="12" r="4" stroke="black" stroke-width="1" fill="purple" fill-opacity="0.6" />
            <text x="25" y="16" font-family="serif" font-size="12px">Military</text>
        </svg>

And I'm guessing the code I would need would go in here? (lines 207-209 in script.js):
$(".item").click(function () {
$(this).toggleClass("gray");

});

A: You can add extra information on these nodes and links by using data-[name] to distinguish different types of data, such as data-type.
 var node = svg.selectAll(".node")
        .data(json.nodes)
        .enter().append("g")
        .attr("data-type", function(d){
          return d.Sector; // add data attributes for later usage.
        })
        .attr("class","node") // better to give them class name

Then add filtering code like this in the dashboard toggle function:
$(".item").click(function () {
  $(this).toggleClass("gray");
  var text = $(this).find("text").text()
  if($(this).hasClass("gray")){
     d3.selectAll(".node")
       .filter(function(d,i){
         return d3.select(this).attr("data-type") == text;
       })
       // filter nodes with the same type, and make it invisible
      .style("opacity",0)
 }else {
    d3.selectAll(".node")
     .filter(function(d,i){
     return d3.select(this).attr("data-type") == text;
    })
   .style("opacity",1)
 }
});

The method is similar for links, I suppose you can add the type info into the data source. And keep the name of the 'type' consistent while filtering('Commonwealth' V.S 'Commonwealth of Virginia'). Example plunkr here, click on 'Academia', 'Federal', 'Military' to see how it works for node (the other two types aren't working because of the naming consistency issue).
Update for question in comments:
To achieve the effect of only show information tab while clicking on children nodes, you can check the name of the parent node and compare it with the dashboard items:
 // collect the items in the dashboard panel
 var items = [];
 $(".item").each(function(){
   items.push($(this).find("text").text())
 })

Then in the click event listener:
if($.inArray(d.name, items) !== -1){return}
// check if this node is the parent node describe in dashboard panel

Example plunkr here. Again, there is some data inconsistency just for the 'common wealth' type, should be 'common wealth of virgina'. (click on 'federal', 'academia', 'non-government organization' types to see how it turns out)


text: Q: Возможно ли создать один макет для всех товаров (для просмотра характеристик),или нужно создвать Activity под каждый товар? Пишу приложение для Android в котором основная цель-просмотр товара и его характеристики. У меня будет где-то 800-1000 товаров.Возник вопрос:нужно ли создавать Activity под каждый товар? Или можно как-то создать один макет для всех товаров , а потом заполнять?Или есть другие варианты? Подскажите пожалуйста,как можно это сделать ,и что для этого нужно?


text:
Q: Registration with Publication Server fail (RMI problem) I was setting up the EnterpriseDB replication server on a CentOS based Virtual Machine and I encountered the error ClassNotfound com.edb.remote.RemoteServer (no security manager: RMI class loader disabled) while registering the Publication Server with xDB Replication Console  on a Windows machine, even if I add the java.rmi.server.hostname=<IP address of the host machine '192.168.190.132' in my case> configuration while running publication server!

*

*The VM's Network Adapter is set to NAT mode.

*9051/tcp port is opened.

*The client (xDB console:Windows) and the server (Publication Server: Centos VM) are running on two separate machines and are connected via network.

Note that the same error is raised when trying to register a publication server with a xDB replication console, where both are running on Windows machines.
→ Here is the part of the enterprisedb documentation dealing with assigning an IP address for remote method invocation
xDB Replication Console


text:
Q: Rally Subversion Connector not robust at finding artifacts Some of our engineers are finding that the Rally-Subversion connector does not do a very good job of finding artifacts in the commit message, for example if they are followed by a colon (e.g. DE2222:)
I took a look at the connector 3.7 code, and found that they first split the message into words, but that splitting is done like this:
words = message.gsub(/(\.|,|;)/, ' ').split(' ')

Is there any reason this would not be done like this:
    words = message.split(/\W+/)

This seems like it will be much more robust and I'm having trouble thinking of a downside.
Any reason we should not make this change?
If not, could this update please also be made in the next release of the connector as well?

A: As the SCM connector source code is open, there's really no reason you shouldn't make a change to the commit message artifact "detection" regex, if you find it more efficient.
As a heads-up, Rally's new generation of SCM connectors (we're calling them "VCS" connectors for Version Control System connectors) will no longer utilize a post-commit hook, but instead will run at a scheduled interval and will collect commit events from the SVN log. These collected events will then be posted to Rally as Changesets.
The new VCS connectors will not parse the logs for commit messages to translate into artifact state changes - so ultimately implementing that type of functionality will end up needing a customer-extension to the connector code in the long run anyway.


text:
Q: neighborhood space metric Let $M$ be a metric space and $a \in M$. We say that $V \subseteq M$ is a
neighborhood of $a$ when $a \in \operatorname{Int}(V)$.
Show that if $(x_n)$ is a sequence in $M$, then the following are equivalent:

*

*$\lim x_n = a$;

*For every neighborhood $V$ of $a$ there is $n_{0} \in \mathbb{N}$ such that $x_n \in V$ when $n ≥ n_0$.

A: I assume that your definition of convergence is as follows:

If $M$ is a metric space with metric $d,$ and $a\in M$ and $(x_n)$ is a sequence in $M,$ then we say that $\lim x_n=a$ if for all real $\epsilon>0,$ there is some $n_0\in\Bbb N$ such that $d(x_n,a)<\epsilon$ whenever $n\ge n_0$.

Here's what I recommend, then. For each $a\in M$ and each real $\epsilon>0,$ define $$B_d(a;\epsilon):=\{x\in M\mid d(x,a)<\epsilon\}.$$ You should be able to $B_d(a;\epsilon)$ is a neighborhood of $a,$ so one part of the proof is then trivial. For the other direction, use the definition of interior point, together with the definition of convergence.


text:
Q: Spark Execution of TB file in memory Let us assume i have one Tb data file.
Each Node memory in ten node cluster is 3GB.
I want to process the file using spark.
But how does the One TeraByte fits in memory?
Will it throw out of memory exception?
How does it work?

A: As Thilo mentioned, Spark does not need to load everything in memory to be able to process it. This is because Spark will partition the data into smaller blocks and operate on these separately. The number of partitions, and this their size depends on several things:

*

*Where the file is stored. The most commonly used options with Spark already store the file in a bunch of blocks rather than as a single big piece of data. If it's stored in HDFS for instance, by default these blocks are 64MB and the blocks are distributed (and replicated) across your nodes. With files stored in S3 you will get blocks of 32MB. This is defined by the Hadoop FileSystem that is used to read the files and applies to files from other filesystems for which Spark uses Hadoop to reed them.

*Any repartitioning you do. You can call repartition(N) or coalesce(N) on an RDD or a DataFrame to change the number of partitions and thus their size. coalesce is preferred for reducing the number without shuffling data across your nodes, whereas repartition allows you to specify a new way to split up your data, i.e. have better control of which parts of the data is processed on the same node.

*Some more advanced transformations you may do. For instance, the configuration setting spark.sql.shuffle.partitions, by default set to 200, determines how many partitions a DataFrame resulting from joins and aggregations will have

Caching
The previous bit relates to just standard processing of data in Spark, but I feel you may be let to the wrong ideas because of Spark being advertised as 'in-memory', so I wanted to address that a bit. By default there is nothing in Spark that is more 'in-memory' than any other data processing tool: a simple example as sc.textFile(foo).map(mapFunc).saveTextFile(bar) reads a file (block by block and distributed over your nodes), does the mapping in memory (like any computer program) and then saves it to storage again. Spark's use of memory becomes more interesting in the following (in Scala as I'm more fammiliar with it, but the concept and method names are exactly the same in Python):
val rdd = sc.textFile(foo)
// Do some preprocessing, such as parsing lines
val preprocessed = rdd.map(preprocessFunc)
// Tell Spark to cache preprocessed data (by default in memory)
preprocessed.cache()
// Perform some mapping and save output
preprocessed.map(mapFunc1).saveTextFile(outFile1)
// Perform a different mapping and save somewhere else
preprocessed.map(mapFunc2).saveTextFile(outFile2)

The idea here is to use cache() so preprocessing doesn't have to be done twice (possibly); by default Spark doesn't save any intermediate results, but calculates the full chain for each separate action, where the 'actions' here are the saveTextFile calls.
I said 'possibly' because the ability to actually cache data is limited by the memory in your nodes. Spark reserves a certain amount of memory for cache storage, separate from work memory (see http://spark.apache.org/docs/latest/configuration.html#memory-management how the sizes of these parts of memory are managed), and can cache only up to as much as that amount can hold.
Depending on your partitioning it may be less though. Let's say you have 2GB of storage memory on each of your 3 nodes and the data in preprocessed is 6GB. If this data has 3 partitions, it will fit perfectly and all input data to mapFunc2 will be loaded from memory. But if you have say 4 partitions, each of 1.5Gb, only 1 partition can be cached on each node; the 4th partition won't fit in the 0.5GB that is still left on each machine, so this partition has to be recalculated for the second mapping and only 3/4 of your preprocessed data will be read from memory.
So in this sense it is better to have many small partitions, to make caching as efficient as possible, but this may have other downsides: more overhead, huge delays if you happen to use Mesos with fine grained mode, and tons of small output files (if you don't coalesce before saving) as Spark saves each partition as separate file.
As Durga mentioned there is also the possibility to have data that does not fit in memory spill to disk, you can follow his link for that :)

A: By default storage level is MEMORY_ONLY, which will try to fit the data in the memory. It will fail with out of memory issues if the data cannot be fit into memory.
It supports other storage levels such as MEMORY_AND_DISK, DISK_ONLY etc. You can go through Spark documentation to understand different storage levels. You can invoke persist function on RDD to use different storage level.


text:
Q: Fabric.js how to set opacity of lines Using the fabric.js library, I can set line width and color as follows:
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = "#f00";

Is there a way to set the opacity too? Couldn't find anything in the documentation, neither on the net anywhere.

A: Instead of using a hexadecimal color code, you can set color to use rgba, like below:
canvas.freeDrawingBrush.color = 'rgba(255, 0, 0, 0.1)';

Demo JSFiddle


text:
Q: plot geom_lines() by different time periods I have the following data:
structure(list(date_time = structure(c(1577836800, 1577840400,
1577844000, 1577847600, 1577851200, 1577854800, 1577858400, 1577862000,
1577865600, 1577869200, 1577872800, 1577876400, 1577880000, 1577883600,
1577887200, 1577890800, 1577894400, 1577898000, 1577901600, 1577905200,
1577908800, 1577912400, 1577916000, 1577919600, 1577923200, 1577926800,
1577930400, 1577934000, 1577937600, 1577941200, 1577944800, 1577948400,
1577952000, 1577955600, 1577959200, 1577962800, 1577966400, 1577970000,
1577973600, 1577977200, 1577980800, 1577984400, 1577988000, 1577991600,
1577995200, 1577998800, 1578002400, 1578006000, 1578009600, 1578013200,
1578016800, 1578020400, 1578024000, 1578027600, 1578031200, 1578034800,
1578038400, 1578042000, 1578045600, 1578049200, 1578052800, 1578056400,
1578060000, 1578063600, 1578067200, 1578070800, 1578074400, 1578078000,
1578081600, 1578085200, 1578088800, 1578092400, 1578096000, 1578099600,
1578103200, 1578106800, 1578110400, 1578114000, 1578117600, 1578121200,
1578124800, 1578128400, 1578132000, 1578135600, 1578139200, 1578142800,
1578146400, 1578150000, 1578153600, 1578157200, 1578160800, 1578164400,
1578168000, 1578171600, 1578175200, 1578178800, 1578182400, 1578186000,
1578189600, 1578193200), tzone = "UTC", class = c("POSIXct",
"POSIXt")), altura = c(80L, 67L, 69L, 86L, 110L, 137L, 161L,
178L, 182L, 174L, 153L, 126L, 102L, 86L, 84L, 94L, 113L, 137L,
161L, 180L, 189L, 183L, 164L, 136L, 107L, 86L, 77L, 81L, 95L,
115L, 137L, 157L, 171L, 175L, 167L, 149L, 127L, 107L, 94L, 91L,
99L, 114L, 134L, 156L, 173L, 181L, 177L, 160L, 136L, 112L, 94L,
85L, 87L, 98L, 114L, 133L, 152L, 166L, 172L, 167L, 152L, 133L,
113L, 99L, 93L, 97L, 109L, 128L, 150L, 168L, 178L, 175L, 161L,
140L, 117L, 99L, 88L, 87L, 94L, 109L, 129L, 151L, 168L, 176L,
173L, 159L, 138L, 116L, 98L, 88L, 89L, 102L, 123L, 147L, 168L,
180L, 180L, 166L, 145L, 120L)), row.names = c(NA, -100L), class = c("tbl_df",
"tbl", "data.frame"))

I produce this graph:

I wanna to produce the same graph with the lines in different colors considering the mean of different time periods. For example, 6 hours, 12 hours, or a day.
In another way. Plot lines with the mean of different time periods (6h, 12h, 24h)
Thank's all

A: You could do
library(tidyverse)

df %>%
  mutate(hour = lubridate::hour(date_time),
         date = as.Date(date_time)) %>%
  ggplot(aes(date_time, altura)) +
  geom_line() +
  geom_line(data = . %>%
              group_by(date, hour %/% 6) %>%
              summarise_all(mean), aes(color = "6 hour")) +
  geom_line(data = . %>%
              group_by(date, hour %/% 12) %>%
              summarise_all(mean), aes(color = "12 hour")) +
  geom_line(data = . %>%
              group_by(date) %>%
              summarise_all(mean), aes(color = "day"))


text:
Q: Formal arguments for why an asymmetric f-divergence might be favourable to a symmetric one in analyzing importance sampling I am reading Importance Sampling and Necessary Sample Size: an Information Theory Approach.
Below is a quote from paragraph 3, section 3 of the article.

While [total variation distance] and [Hellinger distance] can be shown to be distances in P(X), [Kullback-Leibler divergence] and [χ2 divergence] are not. In particular, these latter divergences fail to be symmetric, a feature that makes them appealing for the analysis of importance sampling. Indeed, the very formulation of the method is built on an asymmetric premise (the absolute continuity of P with respect to Q). Moreover, it is well acknowledged that it is desirable that the proposal has heavier tails than the target —again an asymmetric requirement.

I do not understand how this claim (bolded quote) is justified by the two sentences following it.
I understand that importance sampling is essentially an application of the Radon-Nikodym derivative of the target with respect to the proposal, hence absolute continuity is required for the existence of such a density. However, I do not understand how these "asymmetries" are a "feature" rather than a defect.
My question is as the title reads, are there formal arguments for why an asymmetric f-divergence might be favourable to a symmetric one in analyzing importance sampling?

A: I finished reading the paper and can convince myself temporarily, via an example the author provided, that an asymmetric divergence can be beneficial in analyzing importance sampling.
Before jumping into the example, it is worth noting the goal of the paper is, at a high level, to derive necessary sample sizes (NSSs) for importance sampling.
In Section 5 of Importance Sampling and Necessary Sample Size: an Information Theory Approach, the author demonstrates how the total variation (TV) and Hellinger (H) distance can fail to produce a meaningful NSS. In one example, he considered a N(0, 25) target distribution, and a proposal N(0, 1) distribution.
The tails of the target distribution is heavier than the proposal's.
Due to the symmetry of TV and H distances, these metrics are unable to distinguish the direction of tail discrepancies, resulting in the approximated NSS (under TV and H distances) to be less than 3 for both cases.
The benefit of asymmetric divergences can be further highlighted by reversing the setup, i.e., N(0,1) target and N(0,25) proposal. If we used TV and H distances, the approximated NSS will be the same for TV and H divergences. However, Kullback-Leibler and χ-square divergence will yield a lower NSS.
It would be interesting to see the effects of symmetry in divergences when considering sufficient sample sizes.


text:
Q: Adding attachment to Google Calendar with Google scripts I am trying to add a Google document from my Google drive to a calendar event in a calendar I own. The frustrating thing is that I had it and while playing with the code lost it! The code I have below will add a calendar event, but no attachment appears and no error arises when the code is run. If anyone has a simple example of attaching a file to a calendar event, it would be much appreciate.
   function createEvent() {
    var calendarId = 'primary';
    var start = getRelativeDate(1, 12);
    var end = getRelativeDate(1, 13);
    var event = {
        summary: 'Lunch Meeting',
        location: 'The Deli',
        description: 'To discuss our plans for the presentation next week.',
        start: {
            dateTime: start.toISOString()
        },
        end: {
            dateTime: end.toISOString()
        },
        attendees: [{
            email: 'alice@example.com'
        }, {
            email: 'bob@example.com'
        }],

        attachments: [{
                fileId: "1sGm4o0DVJFjJQun_oj1PWD9MuFCiikqamM7B0TkwH6w",
            },
        ],
        colorId: 9
    };

    event = Calendar.Events.insert(event, calendarId);
    Logger.log('Event ID: ' + event.getId());
}

function getRelativeDate(daysOffset, hour) {
    var date = new Date();
    date.setDate(date.getDate() + daysOffset);
    date.setHours(hour);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date;
}

A: For attaching Drive files in an Event, you can check out the Add Drive attachments to events.
Basically you'll first need to file.get() from Drive and use the alternateLink, title, and mimeType properties. The second step is to update the event by setting the supportsAttachments to true.
Once done, you can use events.insert or events.patch and setAttachments to the event. The final step would be to call execute to finalize the call.


text:
Q: Does WCF's netMsmqBinding requires any MSMQ package installation at the client side? I'd like to use WCF+MSMQ(netMsmqBinding) and I was wondering if I'd need to install anything MSMQ related at the client side, other than my client application and the .NET framework of-course.

A: Yes you need MSMQ installed on both the service and the consumer sides.
Edit: just to embellish the answer - the reason you need MSMQ installed is that when you send a message to a queue on another machine, what is really happening is that you are sending a message to the queue manager on the senders machine, which is sending a message to the queue manager on the receivers machine, which is sending a message to the queue.
Each "send" is a single logical action and is what gives MSMQ durability.


text:
Q: How to change default "sort by" to "type" in nautilus How to change the sort by for folders to type, because I want folders to be shown first and then files by name. When I sort by type, I get the result I want, but I need to change this for all my folders.
How can I change the default preference to sort by: type, so every folder will by default be sorted by type? I tried with dconf-editor, then org > gnome > nautilus > preferences and tried to choose type in default-sort-order, but I can only select modification_date, not by type.

A: Change the reverse sort order settings for files(nautilus)/nemo on Ubuntu 14.04:
gsettings list-recursively | grep reverse

...
gsettings set org.nemo.preferences default-sort-in-reverse-order true
gsettings set org.gnome.nautilus.preferences default-sort-in-reverse-order true

A: On Nemo (a recent fork of nautilus), I have the following in the menu :

*

*Edit > Preferences

*then on the Views tab

*

*I got a section called Default View

*with a line Arrange items, there is a select where I can choose the default sort order

Screenshot

A: Determine the current default value of Nautilus sort order using gsettings
gsettings get org.gnome.nautilus.preferences default-sort-order

Then change/set it to 'type'
gsettings set org.gnome.nautilus.preferences default-sort-order 'type'

The change happens instantly

A: update February 2017:
nautilus now has a configuration option to sort directories first (I think since 3.14 or so) so I recommend using that instead of changing the default sort order. It is literally the first item in GUI preferences.

initial post from May 2014
I see the same problems on Fedora 18 (using the same versions).
The first attempt using dconf directly via the command line does not work for me:
$ dconf write /org/gnome/nautilus/preferences/default-sort-order type
error: 0-4:unknown keyword

Now gsettings to the rescue:
$ gsettings set org.gnome.nautilus.preferences default-sort-order type

I'm not sure why dconf does not accept 'type' as a valid value even though dconf-editor explicitely lists it in the help text but gsettings works for me just fine.

A: In preferences -> Views -> Arrange Items
It has got 'By Type' in the drop down list.
If you can't see preferences in gnome-shell, click on the nautilus icon in the top panel


text:
Q: Reset counter in new \chapter before the first \section \newtheorem{lemma}{Lemma}[section]

\chapter{First chap}
\section{First sec}
\begin{lemma}
this one is correct.
\end{lemma}

\chapter{Second chap}
\begin{lemma}
This number is wrong.
\end{lemma}

\section{Second sec}
\begin{lemma}
this one is correct again.
\end{lemma}

Obviously I would like to have the lemma in the 2nd chapter before the Second sec to start at zero. But how?

A: LaTeX < 2015: The number of the lemma is only reset, when section is increased, not chapter. \@addtoreset helps to reset lemma, if chapter is increased:
\newtheorem{lemma}{Lemma}[section]

\makeatletter
\@addtoreset{lemma}{chapter}
\makeatother

In the recent LaTeX release 2015/01/01, this is no longer necessary, because the counter reset is implemented in a transitive way.
Number format
If the section number 0 should be suppressed, then the following redefinition of \thelemma helps:
\renewcommand*{\thelemma}{%
  \ifnum\value{section}=0 %
    \thechapter
  \else
    \thesection
  \fi
  .\arabic{lemma}%
}


text:
Q: When arrays go awry? I'm trying to learn C# by solving mathematical problems.  For example, I'm working on finding the sum of factors of 3 or 5 in the first 1000 positive numbers.  I have the basic shell of the code laid out, but it isn't behaving how I'm expecting it to.
Right now, instead of getting a single output of 23, I am instead getting 1,1,3,3,5,5,7,7,9,9.  I imagine I messed up the truncate function somehow.  Its a bloody mess, but its the only way I can think of checking for factors.  Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
using System;

namespace Problem1
{
    class Problem1
{
    public static void Main()
        {
            //create a 1000 number array
            int[] numberPool = new int[10];

            //use for loop to assign the first 1000 positive numbers to the array
            for (int i = 0; i < numberPool.Length; i++)
                {
                numberPool[i] = i + 1;
                }

            //check for factors of 3 or 5 using if/then statment
            foreach (int i in numberPool)
                if ((i / 3) == Math.Truncate((((decimal)(i / 3)))) || ((i / 5) == Math.Truncate(((decimal)(i / 5)))))
                    {
                    numberPool[i] = i;
                    }
                else
                    {
                    numberPool[i] = 0;
                    }

            //throw the 0s and factors together and get the sum!
            int sum = 0;

            for (int x = 0;x < numberPool.Length;x++)
            {
                sum = sum + numberPool[x];
            }

            Console.WriteLine(sum);

            Console.ReadLine();
            //uncomment above if running in vbs
        }
}
}

A: The foreach loop has a few errors.
If you want to modify the array you are looping through use a for loop. Also, use modulus when checking remainders.
    for (int i = 0; i < numberPool.Length; i++)
    {
            if (numberPool[i] % 3 == 0 || numberPool[i] % 5 == 0)
            {
                // Do nothing
            }
            else
            {
                numberPool[i] = 0;
            }
    }

Modulus (%) will give the remainder when dividing two integers.
Another useful shortcut, variable = variable + x can be replaced with variable += x
Please note that there are more concise ways of doing this but since you are learning the language I will leave that for you to find.

A: @kailanjian gave some great advice for you but here is another way your initial logic can be simplified for understanding:
//the sum of factors
int sum = 0;

//the maximum number we will test for
int maxNum = 1000;

//iterate from 1 to our max number
for (int i = 1; i <= maxNum; i++)
{
    //the number is a factor of 3 or 5
    if (i % 3 == 0 || i % 5 == 0)
    {
        sum += i;
    }
}

//output our sum
Console.WriteLine(sum);

You also stated:

Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.

Your program logic will execute in the order that you list it and won't move on to the next given command until it is complete with the last. So your sum output will only be printed once it has completed our for loop iteration.


text:
Q: ProgressBar issues : copying a folder to destination updates Below i have the code for the copying of a directory for the import function of the application, i want to update the progressbar and label accoridngly. Ive just been reading up about the background worker and that it would be suited to this particular case as well.
Heres the code:
private void importToolStripMenuItem_Click(object sender, EventArgs e)
    {
        lbProcessFiles.Visible = false;
        pbProcessFiles.Visible = false;

        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string sourcePath = folderBrowserDialog1.SelectedPath;
            string destinationPath = @"Logs\\";

            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
            {
                lbProcessFiles.Visible = true;
                lbProcessFiles.Text = "Copying Directories";
                pbProcessFiles.Value = 0;
                pbProcessFiles.Maximum = dirPath.Length;

                Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));

                pbProcessFiles.PerformStep();
            }

            lbProcessFiles.Text = "Now Copying Files";

            //Copy all the files
            foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
            {
                pbProcessFiles.Value = 0;
                pbProcessFiles.Maximum = newPath.Length;
                lbProcessFiles.Text = "Copying Files";

                File.Copy(newPath, newPath.Replace(sourcePath, destinationPath));

                pbProcessFiles.PerformStep();
            }
        }
        lbProcessFiles.Text = " Import Complete";
    }

A: You are setting the value of the progressbar to zero in each iteration of the foreach. Move pbProcessFiles.Value = 0; out of the foreach statement...


text:
Q: JSON AJAX connection handicap on 3G ( purgeIdleCellConnections: found one to purge conn ) I build an app that lists a few items, by requesting JSONP from my server with AJAX *once*, at startup on #site1 .
If you tap on the items(DIVs) it will direct you to #sitedetails .
On "sitedetails" the basic details and the description of the clicked item will be loaded with AJAX jsonp  (it's only text).
My jQuery-Mobile PhoneGap App works fine if I try it on my test-device with WIFI, as soon as I use 3G it kind of kills the connection. Sometimes "sitedetails" takes really long to make a request (2-5sec.) Usually it takes under 1sec since it is just a few kb. Because I set a timeout on the JSONP req. of 5sec it often shows the error message of my function.
When these kind of errors happen I navigate back to site1 and tap on an item again and it will work.
In XCode it shows this message while having that problem:
purgeIdleCellConnections: found one to purge conn = 0x1f078460
purgeIdleCellConnections: found one to purge conn = 0x1e591fd0
purgeIdleCellConnections: found one to purge conn = 0x1e591fd0

Although my 3G connection is fast and stable. It can't be the server either, on WIFI it responds immediately and displays the description on "sitedetails".
Now the weired thing: I found out that this only happens if I wait too long after I tapped on an Item. I need to navigate back to "site1" and tap on another item as fast as possible and again, and again, and again.... and there will be no connection problems. But since this is unrealistic for the user it won't help me.
Now the source code:
var itemid;

$(document).on('pageinit', '#site1', function(){
var output = $('#items');
$.ajax({
url: 'http://************.com/api/files/json/mydata.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){

var allitems =
"
"+
"
"+item.name+"
"+
"
"+item.date+"
"+
"
";

output.append(allitems);

});

},
error: function(){
output.text('ERROR - Could not load data.')
}
});
});

Tap event:
$(document).on('tap', '#con', function(event) {
itemid = $(this).attr('data-id');
$.mobile.changePage('#sitedetails');
});

The Problem zone:
$(document).on('pagebeforeshow', '#sitedetails', function(){
var output = $('#itemdetails');
$.ajax({
url: 'http://************.com/api/files/json/mydatadetails.php?itemid='+itemid,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 4000,
success: function(data, status){
$.each(data, function(i,item){
 var itemdetails =
"
"+item.name+"
"+
"
"+item.date+"
"+
"
"+item.details1+"
"+
"
"+item.details2+"
";

output.empty().append(itemdetails);
});
},
error: function(){
output.text('ERROR - Could not load data.')
}
});
});

That's basically it, except the 2 pages which just have a DIV
(site1:#items, sitedetails:#itemdetails).
I am using XCode 4.6, PhoneGap 2.9, JQuery 1.9, JQM 1.3.1 on iOS 6.1
EDIT: I forgot the mydatadetails.php on the server:
<?php
header('Content-type: application/json');

$server = "*******.com";
$user = "***********";
$pw = "***********";
$db = "***********";

$itemid = $_GET["itemid"];

$connection = mysql_connect($server, $user, $pw) or die ("Could not connect: " . mysql_error());
mysql_select_db($db, $connection);

$sql = "SELECT id, name, date, details1, details2 WHERE id='".$itemid."'";

$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
    $records[] = $row;
}

mysql_close($connection);

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

I am thankful for every answer.


text:
Q: Hibernate connects to Postgres db but it doesn't retrieve data I have a Java web application and I'm trying to retrieve a list of Clients from a Postgres database via class configured Hibernate. As far as I can tell, the application does get the connection because I checked the metadata from the connection and I see all my tables in there so it's alright. The problem is that I don't get any data from the table.
Here is my model for the Client:
@Entity
@Table(name="Client")
public class Client implements Serializable {

    @Id
    @Column(name="id", nullable= false)
    private Integer id;

    @Column(name="age", nullable = false)
    private Integer age;

    @Column(name="numberofrentals", nullable = false)
    private Integer numberofrentals;

    @Column(name="name", nullable = false)
    private String name;

    @Column(name="address", nullable = false)
    private String address;

    public Client() {
    }

    public Client(Integer id, Integer age, Integer numberofrentals, String name, String address) {

        this.id = id;
        this.age = age;
        this.numberofrentals = numberofrentals;
        this.name = name;
        this.address = address;
    }

    public Integer getId() {

        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Integer getnumberofrentals() {
        return numberofrentals;
    }

    public void setnumberofrentals(int numberofrentals) {
        this.numberofrentals = numberofrentals;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Client client = (Client) o;

        if (age != client.age) return false;
        if (numberofrentals != client.numberofrentals) return false;
        if (!id.equals(client.id)) return false;
        if (!name.equals(client.name)) return false;
        return address.equals(client.address);

    }

    @Override
    public int hashCode() {
        int result = id.hashCode();
        result = 31 * result + age;
        result = 31 * result + numberofrentals;
        result = 31 * result + name.hashCode();
        result = 31 * result + address.hashCode();
        return result;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Client{" +
                "id=" + id +
                ", age=" + age +
                ", numberofrentals=" + numberofrentals +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Here is the code for the JPAConfiguration
@Configuration
@EnableJpaRepositories("repository")
@EnableTransactionManagement
@EnableCaching
public class JPAConfig {

    //    @Value("${db.jdbcURL}")
    private String jdbcURL = "jdbc:postgresql://localhost:5432/Shop";

    //    @Value("${db.user}")
    private String user = "postgres";

    //    @Value("${db.password}")
    private String password = "*****";

    //    @Value("${db.generateDDL}")
    private Boolean generateDDL = true;

    @Bean
    public DataSource dataSource() {
        PGPoolingDataSource dataSource = new PGPoolingDataSource();
        try {
            dataSource.setUrl(jdbcURL);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setMaxConnections(4);

        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.POSTGRESQL);
        vendorAdapter.setGenerateDdl(generateDDL);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("model");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean
    PlatformTransactionManager transactionManager() {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(entityManagerFactory());
        return manager;
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }

    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager guavaCacheManager = new GuavaCacheManager();
        guavaCacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.HOURS));
        return guavaCacheManager;
    }
}

I get connected but no data from my Client table which has these exact same fields: id(PK), age, numberofrentals, name, address. Any ideas what's wrong? I'm using the findall() from the JpaRepository. I don't understand what could be the problem, everything seems to be right.
If there's more code necessary, I can post more.
Is there any way to debug this or find out what is wrong because so far I could only get the connection and the list of tables and the rest of information sounds alright?
Any ideas what could be wrong?

A: When hibernate creates a table, for some reason it creates it with all lower case letters and it will also read from those. I thought it accesses case-sensitive so I was adding data into the wrong table tables whereas the correct ones remained always empty.


text:
Q: Qualcomm AR Camera overlay view I am using NinevehGL framework and Qualcomm AR  in order to intract with 3D object , but I faced with a problem which is I can not overlay any view , button , text on the camera !!! or better to say add any view to subview !!
for example [self.view addSubView:myImage];
but when camera starts , nothing adds !
I would be grateful if you tell me how to do so ..

A: You need to make sure that your views are positioned correctly (center, bounds, and transform). It's a bit tricky because the AR camera is always displayed in landscape right orientation if you're using the default orientation.
You can display it in portrait orientation, but then you need to modify the values while configuring video background. I suggest to use the default landscape right orientation.


text:
Q: How do I define my model if I need an auto-incrementing ID but want to check for duplicates on another field? I have a class like this. My goal is to update the last_seen_date each time a duplicate link is encountered.
I've defined the id column, because this will be used as a foreign key into another table. This is auto-incrementing. The true duplicate is the url.
class Link(Base):
    __tablename__ = 'links'
    id = Column(BigInteger, primary_key=True, unique=True)
    url = Column(String(500), nullable=False, index=True, unique=True)
    last_seen_date = Column(DateTime, nullable=False, default=datetime.datetime.now())

I'd like to do an INSERT...ON DUPLICATE KEY UPDATE, but I don't know how to define the fields to accomplish this. The way I have it now, I can never duplicate because the combination primary key always has an auto-incrementing portion in the ID.
How do I need to change my definition to allow an ON DUPLICATE KEY UPDATE statement to work when the url is a duplicate, I can change the last_seen_date?

A: ALTER TABLE `tablename` ADD UNIQUE INDEX `ttt_url` (`url`);

ttt_xxx would be the name of the key which i do out of habit. It will allow for insert / on duplicate and you can update the date/timestamp and preserve your original pk


text:
Q: PnP PowerShell command "Add-PnPFieldToContentType" not working in any site collection I'm trying to use this PnP PowerShell command: Add-PnPFieldToContentType to assign some site columns to a specific content type. I've connected to the site collection using this command:
Connect-PnPOnline –Url $siteUrl –Credentials ($credential)

and other PnP commands are working just fine, but Add-PnPFieldToContentType throws me this error:
Add-PnPFieldToContentType : Field or property "ShowInDisplayForm" does not exist.
At line:1 char:1
+ Add-PnPFieldToContentType -Field "SPSNumber" -ContentType "East Asia  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Add-PnPFieldToContentType], ServerException
    + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.ContentTypes.AddFieldToContentType

Where "SPSNumber" is the internal name of the column and "East Asia Contact" is the content type name. Here is the command I'm using:
Add-PnPFieldToContentType -Field "SPSWorkFlowName" -ContentType "example content type"

I think I have studied every article on the internet about Add-PnPFieldToContentType and none of them are doing any good.
I appreciate any idea.

A: I've tested below, and it worked for me. Add-PnPFieldToContentType uses Internal column/field name as described here. You might try changing SPSWorkFlowName to internal name SPSNumber and try again.
Import-Module -Name SharePointPnPPowerShellOnline -Verbose

#Config Variables
$SiteURL = "https://tenant.sharepoint.com/sites/yourSite/"
$ContentTypeName = "TestDocCT"
$SiteColumnName = "WorkflowName" #Internal Name

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred

    #Add Field to Content type
    Add-PnPFieldToContentType -Field $SiteColumnName -ContentType $ContentTypeName
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

A: I figured out a way around using Sharepoint Management Shell commands like this (I'm using Windows PowerShell ISE):
#Get Web Object
$web = Get-SPWeb "site url here"

#Get Content Type
$ContentType = $web.ContentTypes["content type name"]

#Get The Field
$FieldToAdd=$web.Fields["site column name"]

#Add Field to Content type
$FieldLink = New-Object Microsoft.SharePoint.SPFieldLink($FieldToAdd)
$ContentType.FieldLinks.Add($FieldLink)
$ContentType.Update()


text:
Q: External JPanel classs does not show correctly in Main JFrame class basically I'm trying to understand Threads in Java.So I thought I'd create a main JFrame class containing two JPanels from external classes and then do something in one and control it with messages from the second panel.So far I have only created the first external panel and there the probleme starts! It does not show correctly although it appears to be "loaded".(see system.out lines)
So here is the Main Class
package com.maybee.gui;

import java.awt.*;
import javax.swing.*;
 import javax.swing.border.LineBorder;

public class Maybee extends JFrame implements Runnable
{
public JFrame  maynFrame = null;
public JPanel contentPanel = null;
public SimPanel simPanel = null;

public int screenWidth = 0;
public int screenHeight = 0;

public Maybee()
{

}

private void init()
{
    System.out.println("In Inint");
    maynFrame = new JFrame("Maybee");
    maynFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    screenWidth = gd.getDisplayMode().getWidth();
    screenHeight = gd.getDisplayMode().getHeight();
    maynFrame.setPreferredSize(new Dimension(screenWidth,screenHeight - 100));
    maynFrame.setContentPane(getContentPanel());
    maynFrame.setVisible(true);
    maynFrame.pack();
}

public JPanel getContentPanel()
{
    if (contentPanel == null)
    {
        contentPanel = new JPanel();
        contentPanel.setPreferredSize(new Dimension(screenWidth,screenHeight - 100));
        contentPanel.setBorder(new LineBorder(Color.BLUE));
        contentPanel.setBackground(Color.RED);
        contentPanel.setLayout(new BorderLayout());
        contentPanel.add(getSimPanel(),BorderLayout.CENTER);

    }

    return contentPanel;
}

public SimPanel getSimPanel()
{
    if(simPanel == null)
    {
        simPanel = new SimPanel(this);

    }
    return simPanel;
}

public static void main(String[] args)
{

    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            System.out.println("Start");
            Maybee maybee =  new Maybee();
            maybee.run();

        }

    });
}

public void run()
{
    init();

}

}
and now the first external JPanel class
package com.maybee.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

public class SimPanel extends JPanel
{
   public Maybee localMaybee = null;
   public JPanel simPanel = null;
   private JButton btn;

   public SimPanel(Maybee interMaybee)
  {
    localMaybee = interMaybee;
    init();
  }

  public void init()
  {
    simPanel = new JPanel();
    simPanel.setLayout(new BorderLayout());
    simPanel.setPreferredSize(new Dimension(localMaybee.screenWidth/4,localMaybee.screenHeight - 100));
    simPanel.setBackground(Color.GREEN);
    simPanel.add(getBtn(),BorderLayout.CENTER);
    simPanel.setVisible(true);

    System.out.println("IN SIM" + localMaybee.screenWidth);
}

public JButton getBtn()
{
    if(btn == null)
    {
        btn = new JButton("ENDE");
        btn.setSize(70, 20);
        btn.setForeground(Color.YELLOW);
        btn.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

    }
    return btn;
}
}

So what am I missing?
Many thanks!

A: The immediate issue is the second instance of JPanel created in SimPanel.init(). SimPanel is already a JPanel, there is no need to maintain public JPanel simPanel member.
The same problem is in the Maybee class which extends JFrame, but maintains public JFrame  maynFrame member.
Also, as already mentioned in comments above (thanks @Frakcool!) :

*

*Make sure to call pack() before setVisible();

*Don't call setPreferredSize(), do override getPreferredSize() intead;

*No need to extend JFrame;

*No need to call setVisible on JPanel;

*Don't call btn.setSize(), it is a job for a layout manager;

*No need for setContentPane(), JFrame by default has a JPanel as content pane with BorderLayout. Calling add() is enough in this case.
Here is a slightly modified version of the original code (simplified for clarity):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Maybee2 {
    static class SimPanel extends JPanel {
        public SimPanel() {
            setLayout(new BorderLayout());

            JButton btn = new JButton("ENDE");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    //TODO
                }
            });
            add(btn, BorderLayout.CENTER);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }
    }

    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Maybee");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SimPanel simPanel = new SimPanel();
        frame.add(simPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

EDIT:
The application may consist of many panels. The high level container such as JFrame  is not aware of all the underlying layout complexities and cannot enforce a certain size. The panel itself knows its internal layout and its content. So the panel reports its preferred size to the layout manager which eventually packs the content. See Laying Out Components Within a Container for more information.
setBackground has its effect although the button occupies the center of the BorderLayout which takes all the space of the panel. Change the layout of the panel and see the effect. Or move the button into another area, ie - add(btn, BorderLayout.NORTH); Read more in A Visual Guide to Layout Managers.


text:
Q: Azure az copy command complete event grid notification Is there a way for the Azure event grid to trigger when an AZ copy command completes?
We have clients which use az copy to transfer hundreds of files and sub folders into our Azure storage. The number of files is variable. And the az copy command is of a single root folder on their local containing those files and sub folders.
We want to raise an event grid notification when the az copy is complete and successful.
An alternative would be to have a second az copy command in a batch file that transfers a single flag file once the initial command is fully executed successfully. We would then monitor for this single file as the flag to proceed with further processing.
Perhaps if az copy cannot raise the event, then it can add a verification file signaling the end of the transfer?

A: You can have event grid notifications on an individual blob (or directory, when using ADLS). azcopy is essentially creating individual blobs, so you'd get individual notifications. Azure storage doesn't provide a transactional batch of uploads, so you can't get a single notifiction.
If you wanted a single notification, you'd have to manage this yourself. You mentioned a "flag" file, but you can also create custom topics, use an Azure Function, service bus message, etc. How you ultimately implement this is up to you (and your clients that are uploading content), but tl;dr no, you can't get a single completion event for a batch of uploads.

A: I have tried to reproduce in my environment get notification successfully
For event grid notification the endpoint which will receive notification in function app or logic apps...I created endpoint in function app
In your function app -> Function -> create ->select azure event grid trigger ->create

once created, in storage account create subscription as below

please make changes as below once you select endpoint by default it shows function in right side as below and confirm selection and create subscription

once azcopy is complete and files uploaded in container you will get a notification like below


text:
Q: C++ Image processing data blocks into array / pointer I have two grey scale images in txt files, one being a smaller block of the Main image. I have read the images into two different 2d vector matrices.
The Rows and the Columns of the images are:
Main: M = 768 N = 1024
SubImg: R = 49 C = 36
int R = 49; int C = 36;     //Sub Image Rows / Columns
int M = 768; int N = 1024;  //Main Image Rows / Columns
I have looped through the Main image by blocks of width: 49 and height: 36 and I want to put each block into an array, so I can compare the array with the Sub image (using Nearest Neighbor Search) to see which block has the closest result to the Sub image.
This is the code for loop of the Main image:
for (double bx = 0; bx < M; bx += R)
    for (double by = 0; by < N; by += C)
    {
        for (int x = 0; ((x < R) && ((bx + x) < M)); ++x)
        {
            for (int y = 0; ((y < C) && ((by + y) < N)); ++y)
            {
                if ((bx + x) >= M)
                {
                    std::cout << (bx + x) << (by + y) << " ";

                }
                cout << MainIMG_2DVector[bx + x][by + y] << " ";
            }
        }
        cout << "\n\n\n" << endl;
    }

This loop displays all the blocks in one go. The problem I'm having is that I don't know how to put each block into an array, so I can compare the data.
Also is it better to use a pointer instead of an array to do this?
Thanks

A: I'm not sure exactly how you want to compare the blocks, but as far as storing the blocks, you can make a simple Block object like this:
const double R = 49, C = 36;

// Block object (takes in your image 2D vector and x/y coordinates)
class Block {
public:
    Block(std::vector<std::vector<int>> *img_vector, int bx, int by);
    int compare(const Block &block) const;

private:
    std::vector<std::vector<int>> *img_vector;
    int bx, by;
};

Block::Block(std::vector<std::vector<int>> *img_vector, int bx, int by) {
    this->img_vector = img_vector;
    this->bx = bx;
    this->by = by;
}

// Compare any two blocks
int Block::compare(const Block &block) const {
    for (int x = bx; x < bx + R; x++) {
        for (int y = by; y < by + C; y++) {
            // Do some comparing
            std::cout << "Compare " << (*img_vector)[x][y]
                << " with " << (*block.img_vector)[x][y] << std::endl;
        }
    }
    return 0; // Return some value that indicates how they compare
}

And then add the image blocks to a vector:
// Add main image blocks to vector
std::vector<Block> main_img_blocks;
for (double bx = 0; bx < M; bx += R) {
    for (double by = 0; by < N; by += C)
        main_img_blocks.push_back(Block(&MainIMG_2DVector, bx, by));
}

// Do the same for sub image blocks...

// Invoke the compare function between 2 blocks at a time
int comp_value = main_img_blocks[0].compare(main_img_blocks[1]);

Hope that helps :)


text:
Q: Как разбить сложную строку на массив? Нужно распилить строку на массив.
Строка:
routes[0][1].action.controller[0].class

Массив:
array(
    [0]=> string(6) "routes",
    [1]=> string(3) "[0]",
    [2]=> string(3) "[1]",
    [3]=> string(6) "action",
    [4]=> string(10) "controller",
    [5]=> string(3) "[0]",
    [6]=> string(5) "class"
)

А еще лучше на:
array(
    [0]=> string(6) "routes",
    [1]=> int(0),
    [2]=> int(1),
    [3]=> string(6) "action",
    [4]=> string(10) "controller",
    [5]=> int(0),
    [6]=> string(5) "class"
)

Вот мой код
preg_match_all(
    '/([a-z0-9_]+)(\[\d+\])*(\.|$)/',
    'routes[0][0].action.controller[0].class',
    $matches
);

Но я получаю
array (
  0 =>
  array (
    0 => 'routes[0][1]',
    1 => 'action',
    2 => 'controller[0]',
    3 => 'class',
  ),
  1 =>
  array (
    0 => 'routes',
    1 => 'action',
    2 => 'controller',
    3 => 'class',
  ),
  2 =>
  array (
    0 => '[1]',
    1 => '',
    2 => '[0]',
    3 => '',
  ),
)

A: Ищем слово или цифры в квадратных скобках
\w+|\[\d+\]

демо на regex101
демо на eval.in
А чтобы получить цифры без скобок
\w+|(?<=\[)\d+(?=\])\]

демо на eval.in

A: $string = 'routes[0][0].action.controller[0].class';

preg_match_all('/[a-z0-9]+|\[\d\]/', $string, $matches);

пример


text:
Q: WPF WebBrowser- disable user interaction with content displayed in browser I am using the System.Windows.Controls.WebBrowser web browser to enable users to view PDF files from within my WPF application.
I now want to prevent the user from having any options for interaction with the content displayed in the browser (i.e. they should not be able to print/ save/ highlight text/ copy any of the content displayed in the browser).
How would I do this?
I have added the WebBrowser to the application with the line:
System.Windows.Controls.WebBrowser browser = new System.Windows.Controls.WebBrowser();

and am specifying the path of the file that they are viewing from within the code, but also giving them the options to select other files to view by using File -> Open and browsing to the location of the file that they want to open.
I couldn't find anything in the MSDN WebBrowser docs that indicated how I could disable the Save or Print buttons, 'right-click' functionality, or text highlighting... does anyone have any suggestions?

A: The problem is not the WebBrowser. You are opening a PDF file within it, so it's either a plugin or built-in viewer. Controlling that is outside of the WebBrowser properties and events.
You should consider using an actual PDF viewer control, such as ones suggested in this topic.


text:
Q: UPDATE Query issue I am porting my code that used MS Access to Sqlite.
I am getting problem for UPDATE query,
UPDATE Table1 T1, Table2 T2
SET T1.USE_MHE = T2.USE_MHE
WHERE T1.EQ_NAME= T2.EQ_NAME

Above query works fine for MS access ADO connection. But for SQLite it's looks like using table shortcut is not possible (Table1 T1) I have 100's of such query to update.
 Please let me know how table shortcut can be used in SQLite update query.
5:SqliteError
near "T1" Syntax error

A: The UPDATE docs suggest it simply isn't possible.
Maybe you'd be able to hack something up with virtual or temporary tables, but I think it's going to be way more complicated than just using the full table names.
Aside of that, you could simply use whatever alias, and your editor's replace tool.

A: update table1
set use_mhe=( select use_mhe
              from table2
              where eq_name=table1.eq_name )
where use_mhe= ( select use_mhe
        from table2
        where eq_name=table1.eq_name )

is not null;

A: try this:
UPDATE Table1
SET USE_MHE = (SELECT USE_MHE FROM Table2 WHERE Table1.EQ_NAME = Table2.EQ_NAME)


text:
Q: Add a blinking effect to single character of array I am trying to achieve blinking effect to a single character of an array.
For example, if "text" get load inside paragraph
 tag or container then first character of text should blink and when user types the blinking character in input area blinking effect must move to blink on next character.
I need assistance in solving this problem. Any instructions or help will be so grateful.
Here what I've tried so far:

let displayElem = document.getElementById("me");
const inputElem = document.getElementById("input");
const text = "Hey It's bad day, not a bad life,you'll be okay...!"

text.split('').forEach(char => {
  const chrspan = document.createElement('span')
  chrspan.innerText = char;
  displayElem.appendChild(chrspan);
});

inputElem.addEventListener('input', () => {
  var vl = document.getElementById("input").value;
  const arrayq = displayElem.querySelectorAll('span')
  const arrayv = inputElem.value
  let correct = true;

  arrayq.forEach((chSpan, index) => {
    const char = arrayv[index];

    if (char == null) {
      correct = false;
    } else if (char === chSpan.innerText) {
      chSpan.classList.add('blink-bg')
    } else {
      chSpan.classList.remove('blink-bg')
      correct = false
    }
  })
})
.blink-bg {
  text-align: center;
  color: #fff;
  display: inline-block;
  border-radius: 3px;
  animation: blinkingBackground 1s infinite;
}

@keyframes blinkingBackground {
  from { background-color: #f1ebeb; }
  to { background-color: #080808; }
}

<input id="input" type="input" />

let displayElem = document.getElementById("me");
const inputElem = document.getElementById("input");
const text = "Hey It's bad day, not a bad life,you'll be okay...!"

text.split('').forEach(char => {
  const chrspan = document.createElement('span')
  chrspan.innerText = char;
  displayElem.appendChild(chrspan);
});

inputElem.addEventListener('input', () => {
  var vl = document.getElementById("input").value;
  const arrayq = displayElem.querySelectorAll('span')
  const arrayv = inputElem.value
  let correct = true;

  arrayq.forEach((chSpan, index) => {
    const char = arrayv[index];

    if (char == null) {
      correct = false;
    } else if (char === chSpan.innerText) {
      chSpan.classList.add('blink-bg')
      // document.getElementById("p_id").innerHTML = chSpan.innerText;
    } else {
      chSpan.classList.remove('blink-bg')
      correct = false
    }
  })
})

A: This might be a good starting point for you. I changed a couple things,
I made a helper function $ to grab items from the dom as a personal prefrence.
I created an array of all the spans on the document, making it easier to keep track of which element has the blinking class. I created a helper function to grab what the activeText is from the txtArr instead of checking the text content. This way I can avoid using the rendered screen as a storage area for information, and instead have the screen mirror what is happening in my js.
On input I check the last character entered, and if it is the character that is blinking, I increment increment which span is blinking.
This is meant to be a simple demo of how to accomplish this task, you may want to have different functionality, but hopefully this helps as a starting point!

const $ = str => [...document.querySelectorAll(str)];
let displayElem = $("#me")[0];
const inputElem = $("#input")[0];
const text = "Hey! It's a bad day, not a bad life, you'll be okay...!"
const txtArr = [...text];
const txtSpans = txtArr.map(char => {
  const span = document.createElement("span");
  span.innerText = char;
  return span;
});
let activeIndex = -1;
const activeText = () => txtArr[activeIndex];

function renderSpans() {
  displayElem.innerHtml = "";
  txtSpans.forEach(span => displayElem.appendChild(span));
};

function updateActive() {
  const firstRun = activeIndex == -1;
  if (!firstRun)
    txtSpans[activeIndex].classList.remove("blink-bg");
  activeIndex++;
  if (activeIndex == txtSpans.length) return;
  txtSpans[activeIndex].classList.add("blink-bg");
}
updateActive();
renderSpans();

inputElem.addEventListener('input', e => {
  const val = e.target.value;
  if (val == "") return;
  const lastChar = val[val.length - 1];
  if (lastChar == activeText()) updateActive();
})
.blink-bg {
  text-align: center;
  color: #fff;
  display: inline-block;
  border-radius: 3px;
  animation: blinkingBackground 1s infinite;
}

@keyframes blinkingBackground {
  from { background-color: #f1ebeb; }
  to { background-color: #080808; }
}

<input id="input" type="input" />


text:
Q: Цвет вершины у ломанной Есть ли возможность изменить цвет/форму вершины у Polyline ломаной линии?

A: Вершина ломаной не является отдельной составной частью геометрии, поэтому настраивать её нельзя. Но в режиме рисования/редактирования линии у неё появляются отдельные вершины и промежуточные точки, которые можно кастомизировать, в частности задать им layout:
vertexLayout: 'default#image',
vertexIconImageHref: 'images/button3.png',
vertexIconImageSize: [16, 16],
vertexIconImageOffset: [-8, -8],

Вот пример в песочнице


text:
Q: Using System.Random over multiple data types - the Haskell way? I'm trying to learn Haskell in the most "Haskell way" possible, so I'm trying to avoid things like dos and lets that sort of obscure what's actually going on.
So I have a data type called Org that in is defined as so:
data Org = Org
    { pos :: Pos2D
    , color :: Color
    } deriving (Show)

where Color and Pos2D are defined as so:
-- Not actually defined like this, it's Graphics.Gloss.Data.Color
data Color = Color Float Float Float Float
data Pos2D = Pos2D Float Float

Now I've implemented UniformRange for Pos2D and Uniform for Color as so:
instance UniformRange Pos2D
  where
    uniformRM (Pos2D x1 y1, Pos2D x2 y2) g = Pos2D
        <$> uniformRM (x1, x2) g
        <*> uniformRM (y1, y2) g

instance Uniform Color
  where
    uniformM g = G.makeColor
        <$> uniformRM (0.0, 1.0) g
        <*> uniformRM (0.0, 1.0) g
        <*> uniformRM (0.0, 1.0) g
        <*> return 1.0

Given a tuple of Pos2D (representing the corners of the bounds), it will return a random Pos2D distributed uniformly between those. And for Color, it will return a random color with uniform R, G, and B values, but with a fixed alpha = 255 (1.0).
The question is now, how do I make an org?
randomOrg :: RandomGen g => g -> Org
randomOrg = -- ...
  where
    gen = mkStdGen 1337

The issue I'm having is that uniformR and uniformM take a g and return a tuple of (a, g). So I'm not sure what the cleanest, most "Haskelly" way would be to actually chain these calls together to create the Org.
Any thoughts? Thanks,
Edit:
I know that I can do this:
randomOrg :: RandomGen g => g -> Org
randomOrg g = Org pos color
  where
    (pos, g1) = uniformR (Pos2D 0 0, Pos2D 720 480) g
    (color, g2) = uniform g1

But I'm not a fan of that for obvious reasons.
Edit 2:
Ok so after some thinking, I think the function I need might need to look something like this?
pUniform
    :: (Uniform a, RandomGen g)
    => (a -> b, g) -> (g -> (a, g)) -> (b, g)

But I'm not sure.
Edit 3:
Now I'm thinking a functor might be relvant:
(<$>) :: (Functor f) => (a -> b) -> f a -> f b

So if we take some function (a->b) (which could be for example the Org constructor), and we have some a wrapped in the context f, which would be like (a, g) then we can produce a b wrapped in the context, which would be (b, g). Seems right to me, but I'm not sure how to translate that into actual code.

A: As outlined here, the best way of doing this is by using the new monadic interface:
randomOrg :: StatefulGen g m => g -> m Org
randomOrg g = Org <$> uniformR (Pos2D 0 0, Pos2D 720 480) g <*> uniform g

Which you can then specialise to a pure stateful function:
randomOrg' :: RandomGen g => g -> (Org, g)
randomOrg' g = runStateGen g randomOrg

Though this approach is more general, so you can also run it e.g. in IO using mutable state:
randomOrg'' :: RandomGen g => IOGenM g -> IO Org
randomOrg'' = randomOrg

(Warning: these should work, but I haven't double-checked it myself; please tell me if you find any lurking errors!)


text:
Q: How to query DynamoDB with for multiple ids eg: student_id in [1,2,3] #rails I have a table in DynamoDB.
student_id, name, age, address  partition_key: student_id, table_name: students

lets say student ids are 1,2,3 etc...
I wanted to query students based on Ids.
eg sql select * from students where id in (1,2,3)
How to do the same in DynamoDB
Please help me with the query params.
I tried
params = {
:table_name=>"students",
:key_condition_expression=>"student_id IN :student_id",
:expression_attribute_values=>{":student_id"=> [1,2,3]}
}

A: DynamoDB does not allow you to apply conditionals around the partition key (e.g. PK in [1,2,3]), you need to specify it explicitly.  However, you can perform various condition operations around sort keys (<,>, begins_with, etc).

A: If you can identify the primary key, which I'm assuming is your student_id and you want students with id 1, 2, and 3, then you can use the client batch_get_item().


text:
Q: python3 pexpect how to flush buffer after expect() I am trying to telnet (console using console server) to a Cisco router, run a few show commands, and store the output of them in a variable.
Below simple script works -
Already logged into the router before running script (Not very useful in real world use cases)
import telnetlib
import datetime
import getpass
import sys
import re
import time
import pexpect

host1_ip = "192.168.6.131"
host1_port = "32772"
user ="cisco"
password = "cisco123"

tn=pexpect.spawn("telnet " + host1_ip + " " + host1_port, maxread=16384)
tn.sendline("show ip interface brief")
time.sleep(5)
tn.expect("CE1#")
data1=tn.before
print(data1.decode('utf-8'))

Output is (data1's contents) :
show ip interface brief
Interface                  IP-Address      OK? Method Status                Protocol
Ethernet0/0                unassigned      YES NVRAM  administratively down down
Ethernet0/1                unassigned      YES NVRAM  administratively down down
Ethernet0/2                unassigned      YES NVRAM  administratively down down
Ethernet0/3                unassigned      YES NVRAM  administratively down down
Serial1/0                  unassigned      YES NVRAM  administratively down down
Serial1/1                  unassigned      YES NVRAM  administratively down down
Serial1/2                  unassigned      YES NVRAM  administratively down down
Serial1/3                  unassigned      YES NVRAM  administratively down down

expect with "CE1#" works, as this is the first occurrence of "CE1#"
However, when I use a more useful script that logs in to the router, configures it, and then gets/stores the output of show commands, it doesnot work.
import telnetlib
import datetime
import getpass
import sys
import re
import time
import pexpect

host1_ip = "192.168.6.131"
host1_port = "32772"
user ="cisco"
password = "cisco123"

tn=pexpect.spawn("telnet " + host1_ip + " " + host1_port, maxread=16384)
tn.send("\r")
tn.expect("Username: ")
tn.sendline(user)
tn.expect("Password: ")
tn.sendline(password)

tn.sendline("terminal length 0")
tn.sendline("terminal width 0")
time.sleep(5)
tn.expect("CE1#")
tn.sendeof
tn.sendline("show ip interface brief")
time.sleep(5)
tn.expect("CE1#")
data1=tn.before
print(data1.decode('utf-8'))
tn.sendline("exit")

Output is :
terminal length 0

Expect with "CE1#" after the "show ip interface brief" doesnot work, as "CE1#" is encountered much before.
When I log into the router, "CE1#" is seen.
When I configure "terminal length 0", "terminal width 0", CE1# is seen
Username: cisco
Password:
CE1#terminal length 0
CE1#terminal width 0

How do I flush out the buffer so that previous encounters of "CE1#" are removed ?
Tried (1) adding 'expect "CE1#" statements before (as ideally child.before should only read output after that last expect'
(2) sending eof (3) sending flush using child.flush etc.
None of them have helped.

A: No so sure if after 3 years this is usefully but here it goes:
In your case you need to do .sendline('something') .expect('something') in sequence in order to follow properly the buffer.
In your code, maybe the print you expect is in the buffer or in the .after
Anyhow, if you want to force buffer clear, use this:
 if my_child.before:

       my_child.expect(r'.+')


text:
Q: On Postback, the DataTable data source for a Repeater is empty? Background
I have a User Control (an .ascx file) which is being dynamically inserting into an asp:PlaceHolder control on a page. That User Control contains an asp:Repeater, which I'm binding to a DataTable.
Theoretically, on the User Control's first load the DataTable is initialized and 3 empty rows are added. A button on the User Control adds additional empty rows to the Repeater, one at a time.
Problem
The issue is that after any PostBack event on the page (namely the button in this example being clicked), the DataTable for the Repeater is empty.
User Control (.ascx)
(simplified)
<asp:TextBox ID="controlOutsideRepeater" runat="server" />
<asp:Repeater ID="myRepeater" runat="server">
  <ItemTemplate>

<asp:Textbox ID="firstControlInRepeater" runat="server" text='<%# DataBinder.Eval(Container.DataItem, "A") %>' />

<asp:Textbox ID="secondControlInRepeater" runat="server" text='<%# DataBinder.Eval(Container.DataItem, "B") %>' />

  </ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="addItemButton" runat="server" Text="Add Item" onclick="addNewItem" />

Code Behind (.ascx.cs)
(also simplified)
public DataTable items {
  get {
    object i = ViewState["items"];
    if (i == null) {
      DataTable t = new DataTable();
      t.Columns.Add("A");
      t.Columns.Add("B");
      // add 3 blank items/rows:
      t.Rows.Add(t.NewRow());
      t.Rows.Add(t.NewRow());
      t.Rows.Add(t.NewRow());
      ViewState["items"] = t;
      return t;
    } else {
      return (DataTable)i;
    }
  set { ViewState["items"] = value; }
}

protected void Page_Init(object sender, EventArgs e) {
  myRepeater.DataSource = this.items;
  myRepeater.DataBind();
}

public void addNewItem(object sender, EventArgs e) {
  DataRow r = this.items.NewRow();
  this.items.Rows.Add(r);
  myRepeater.DataBind();
}

Behavior
The first time the UserControl is loaded, the Repeater contains 3 empty items: good! However, after entering some text in the textboxes both inside and outside the repeater and clicking the "Add Item" LinkButton, the page does a refresh/postback and shows 4 empty items, however the textbox -outside- the Repeater retains it's text. Clicking the "Add Item" LinkButton again also performs a postback and still shows 4 empty items, yet the TextBox outside the Repeater again retains it's text.
My Crazy Guess
I've tried wrapping the Repeater databinding in a (!Page.IsPostBack), but this prevented the Repeater from -ever- being bound, as the UserControl is only programmatically added to the page after a PostBack (a button on the Page adds the UserControl on a click, and then the Page checks each PostBack to see if there should be a user control present and re-adds it to the Page if needed). So I'm guessing there's a problem with the Page re-creating the User Control on every PostBack, but can't explain why the TextBox outside the Repeater would retain it's value, and why the ViewState doesn't seem to remember my item (on each postback ViewState["items"] is null and gets re-built within the getter).
HELP!

A: The problem is you are data binding every single request when really you only want to data bind on the first request. Since you don't data bind on the first page load, you will have to check if you are data bound in a way other than !Page.IsPostBack. You could add a property to your user control to handle this and then check against that every page load / page init.
Update: With more details from comments
I see your AddItem() now. I've had problems using viewstate this way though I'm not entirely sure why. I've had to do it more like the following:
public void addNewItem(object sender, EventArgs e) {
  DataTable theItems = this.items;
  DataRow r = theItems.NewRow()
  theItems.Rows.Add(r);
  this.items = theItems
  myRepeater.DataBind(); //I'm not sure if this belongs here because of the reasons said before
}


text:
Q: React Native - "Roulette" effect on Array shifting Summary:
I'm trying to achieve a "roulette" effect on my array.
Assuming I have an array of 5 strings with a function that shifts the value of N index to N + 1 with the last index going back to 0.
These strings are presented in a stacked manner with first string on top and last string at the bottom.

Expected:
Clicking the Test button Animate the stacked string in a roulette effect
What have I tried:
Below is the Test button function that I created which randomizes the number of shift times before shifting the value of strings to the next index.
test = async () => {

    const shiftTimes = Math.floor((Math.random() * 50) + 1);

    for (let i = 0; i < shiftTimes; i ++ ) {
        setTimeout(() => {
            const myList = this.state.myList;

            const temp = myList[myList.length - 1];
            for (let j = myList.length - 1; j > 0; j --) {
                myList[j] = myList[j-1];
            }
            myList[0] = temp

            this.setState({
                myList: myList
            });
        }, 100);
    }
}

Current effect:
While the function does the job of what a roulette should, it lacks the animation even with the setTimeout. It does "animate" on the browser although laggy but on native devices, it doesn't.


text:
Q: dnsmasq without altering /etc/hosts file manually I've trying to get dnsmasq working as a combined dns and dhcp server. It's infuriating so far... In short, the DNS works fine for anything added to /etc/hosts, and the dhcp works fine, but the dhcp is not updating the dns with hostname information from clients.
The outcome of this is that i can only ping a node by hostname if i know it's address, which means setting a static dhcp allocation and putting the hostname into /etc/hosts manually, which is very annoying and kind of defeats the poit of dhcp. There must be a way to get dnsmasq to update the hosts file, surely
The clients aren't using fqdn's if that matters, and i think i've tried every combinination of "expand-hosts" and "domain="
following is the dnsmasq config file contents:

domain-needed
bogus-priv
except-interface=tun0

dhcp-range=192.168.1.10,192.168.1.80,255.255.255.0,12h
dhcp-leasefile=/var/lib/misc/dnsmasq.leases
dhcp-authoritative

log-queries
log-dhcp

A: The DHCP client needs to send a name to have the name made available in the DNS. Otherwise dnsmasq can supply the name, but you have to configure that in /etc/dnsmasq.conf or /etc/hosts first.
Since dnsmasq is a DNS server, you need to have a domain name. The domain-needed part enforces that. Set a domain name in your configuration also.
So here's basically what I have:
bogus-priv
dhcp-authoritative
dhcp-host=00:0c:29:1b:62:c6,host1,192.168.1.86,infinite
dhcp-host=00:0c:29:f7:e6:7d,host2,192.168.1.89,infinite
dhcp-host=00:1e:58:94:d2:5b,192.168.1.10,infinite
dhcp-option=19,0           # option ip-forwarding off
dhcp-option=27,1
dhcp-option=42,0.0.0.0
dhcp-option=44,192.168.1.10     # set netbios-over-TCP/IP nameserver(s) aka WINS server(s)
dhcp-option=45,0.0.0.0     # netbios datagram distribution server
dhcp-option=46,8           # netbios node type
dhcp-option=6,0.0.0.0
dhcp-option-force=210,/
dhcp-option-force=211,30i
dhcp-option=option:domain-search,example.com
dhcp-option=option:router,192.168.1.1
dhcp-range=192.168.1.50,192.168.1.150,255.255.255.0,30d
domain=example.com
domain-needed
enable-tftp
expand-hosts
interface=eth0
local=/dartworks.biz/
local=/localnet/
no-poll
no-resolv
server=<ISP DNS 1>
server=<ISP DNS 2>

A: Try setting a domain with domain example.org.
dnsmasq also has a hook to call a script dhcp-script=foo.sh.  The arguments sent to the script are "add" or "del", then the MAC address, the IP address and finally the hostname.
It should be relatively easy to quickly create a script that updates the hosts file.