Q: Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users? I have some css menus on my site that expand with :hover (without js)
This works in a semi-broken way on iDevices, for example a tap will activate the :hover rule and expand the menu, but then tapping elsewhere doesn't remove the :hover. Also if there is a link inside the element that is :hover'ed, you have to tap twice to activate the link (first tap triggers :hover, second tap triggers link).
I've been able to make things work nicely on iphone by binding the touchstart event.
The problem is that sometimes mobile safari still chooses to trigger the :hover rule from the css instead of my touchstart events!
I know this is the problem because when I disable all the :hover rules manually in the css, mobile safari works great (but regular browsers obviously don't anymore).
Is there a way to dynamically "cancel" :hover rules for certain elements when the user is on mobile safari?
See and compare iOS behavior here: http://jsfiddle.net/74s35/3/
Note: that only some css properties trigger the two-click behavior, e.g. display:none; but not background: red; or text-decoration: underline;

A: I found that ":hover" is unpredictable in iPhone/iPad Safari. Sometimes tap on element make that element ":hover", while sometimes it drifts to other elements.
For the time being, I just have a "no-touch" class at body.
<body class="yui3-skin-sam no-touch">
   ...
</body>

And have all CSS rules with ":hover" below ".no-touch":
.no-touch my:hover{
   color: red;
}

Somewhere in the page, I have javascript to remove no-touch class from body.
if ('ontouchstart' in document) {
    Y.one('body').removeClass('no-touch');
}

This doesn't look perfect, but it works anyway.

A: :hover isn't the issue here.  Safari for iOS follows a very odd rule.  It fires mouseover and mousemove first; if anything is changed during these events, 'click' and related events don't get fired:

mouseenter and mouseleave appear to be included, though they're not specified in the chart.
If you modify anything as a result of these events, click events won't get fired.  That includes something higher up in the DOM tree.  For example, this will prevent single clicks from working on your website with jQuery:
$(window).on('mousemove', function() {
    $('body').attr('rel', Math.random());
});

Edit: For clarification, jQuery's hover event includes mouseenter and mouseleave.  These will both prevent click if content is changed.

A: There are basically three scenarios:

*

*User only has a mouse/pointer device and can activate :hover

*User only has a touchscreen, and can not activate :hover elements

*User has both a touchscreen and a pointer device

The originally accepted answer works great if only the first two scenarios are possible, where a user has either pointer or touchscreen. This was common when the OP asked the question 4 years ago. Several users have pointed out that Windows 8 and Surface devices are making the third scenario more likely.
The iOS solution to the problem of not being able to hover on touchscreen devices (as detailed by @Zenexer) is clever, but can cause straightforward code to misbehave (as noted by the OP). Disabling hover only for touchscreen devices means that you will still need to code a touchscreen friendly alternative. Detecting when a user has both pointer and touchscreen further muddies the waters (as explained by @Simon_Weaver).
At this point, the safest solution is to avoid using :hover as the only way a user can interact with your website. Hover effects are a good way of indicating that a link or button is actionable, but a user should not be required to hover an element to perform an action on your website.
Re-thinking “hover” functionality with touchscreens in mind has a good discussion about alternative UX approaches. The solutions provided by the answer there include:

*

*Replacing hover menus with direct actions (always visible links)

*Replacing on-hover menus with on-tap menus

*Moving large amounts of on-hover content into a separate page

Moving forward, this will probably be the best solution for all new projects. The accepted answer is probably the second best solution, but be sure to account for devices that also have pointer devices. Be careful not to eliminate functionality when a device has a touchscreen just to work around iOS's :hover hack.

A: A better solution, without any JS, css class and viewport check: you can use Interaction Media Features (Media Queries Level 4)
Like this:
@media (hover) {
  // properties
  my:hover {
    color: red;
  }
}

iOS Safari supports it
More about:
https://www.jonathanfielding.com/an-introduction-to-interaction-media-features/

A: The browser feature detection library Modernizer includes a check for touch events.
It’s default behavior is to apply classes to your html element for each feature being detected. You can then use these classes to style your document.
If touch events are not enabled Modernizr can add a class of no-touch:
<html class="no-touch">

And then scope your hover styles with this class:
.no-touch a:hover { /* hover styles here */ }

You can download a custom Modernizr build to include as few or as many feature detections as you need.
Here's an example of some classes that may be applied:
<html class="js no-touch postmessage history multiplebgs
             boxshadow opacity cssanimations csscolumns cssgradients
             csstransforms csstransitions fontface localstorage sessionstorage
             svg inlinesvg no-blobbuilder blob bloburls download formdata">

A: Some devices (as others have said) have both touch and mouse events. The Microsoft Surface for example has a touch screen, a trackpad AND a stylus which actually raises hover events when it is  hovered above the screen.
Any solution that disables :hover based on the presence of 'touch' events will also affect Surface users (and many other similar devices). Many new laptops are touch and will respond to touch events - so disabling hovering is a really bad practice.
This is a bug in Safari, there's absolutely no justification for this terrible behavior. I refuse to sabotage non iOS browsers because of a bug in iOS Safari which has apparently been there for years. I really hope they fix this for iOS8 next week but in  the meantime....
My solution:
Some have suggested using Modernizr already, well Modernizr allows you to create your own tests. What I'm basically doing here is 'abstracting' the idea of a browser that supports :hover into a Modernizr test that I can use throughout my code without hardcoding if (iOS) throughout.
 Modernizr.addTest('workinghover', function ()
 {
      // Safari doesn't 'announce' to the world that it behaves badly with :hover
      // so we have to check the userAgent
      return navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? false : true;
 });

Then the css becomes something like this
html.workinghover .rollover:hover
{
    // rollover css
}

Only on iOS will this test fail and disable rollover.
The best part of such abstraction is that if I find it breaks on a certain android or if it's fixed in iOS9 then I can just modify the test.

A: Adding the FastClick library to your page will cause all taps on a mobile device to be turned into click events (regardless of where the user clicks), so it should also fix the hover issue on mobile devices.  I edited your fiddle as an example: http://jsfiddle.net/FvACN/8/.
Just include the fastclick.min.js lib on your page, and activate via:
FastClick.attach(document.body);

As a side benefit, it will also remove the annoying 300ms onClick delay that mobile devices suffer from.

There are a couple of minor consequences to using FastClick that may or may not matter for your site:

*

*If you tap somewhere on the page, scroll up, scroll back down, and then release your finger on the exact same position that you initially placed it, FastClick will interpret that as a "click", even though it's obviously not. At least that's how it works in the version of FastClick that I'm currently using (1.0.0). Someone may have fixed the issue since that version.

*FastClick removes the ability for someone to "double click".

A: The JQuery version
in your .css use
  .no-touch .my-element:hover
for all your hover rules
include JQuery and the following script
function removeHoverState(){
    $("body").removeClass("no-touch");
}

Then in body tag add
 class="no-touch" ontouchstart="removeHoverState()"
as soon as the ontouchstart fires the class for all hover states is removed

A: I agree disabling hover for touch is the way to go.
However, to save yourself the trouble of re-writing your css, just wrap any :hover items in  @supports not (-webkit-overflow-scrolling: touch) {}

.hover, .hover-iOS {
  display:inline-block;
  font-family:arial;
  background:red;
  color:white;
  padding:5px;
}
.hover:hover {
  cursor:pointer;
  background:green;
}

.hover-iOS {
  background:grey;
}

@supports not (-webkit-overflow-scrolling: touch) {
  .hover-iOS:hover {
    cursor:pointer;
    background:blue;
  }

}
<input type="text" class="hover" placeholder="Hover over me" />

<input type="text" class="hover-iOS" placeholder="Hover over me (iOS)" />

A: Instead of only having hover effects when touch is not available I created a system for handling touch events and that has solved the problem for me. First, I defined an object for testing for "tap" (equivalent to "click") events.
touchTester =
{
    touchStarted: false
   ,moveLimit:    5
   ,moveCount:    null
   ,isSupported:  'ontouchend' in document

   ,isTap: function(event)
   {
      if (!this.isSupported) {
         return true;
      }

      switch (event.originalEvent.type) {
         case 'touchstart':
            this.touchStarted = true;
            this.moveCount    = 0;
            return false;
         case 'touchmove':
            this.moveCount++;
            this.touchStarted = (this.moveCount <= this.moveLimit);
            return false;
         case 'touchend':
            var isTap         = this.touchStarted;
            this.touchStarted = false;
            return isTap;
         default:
            return true;
      }
   }
};

Then, in my event handler I do something like the following:
$('#nav').on('click touchstart touchmove touchend', 'ul > li > a'
            ,function handleClick(event) {
               if (!touchTester.isTap(event)) {
                  return true;
               }

               // touch was click or touch equivalent
               // nromal handling goes here.
            });

A: Thanks @Morgan Cheng for the answer, however I've slightly modified the JS function for getting the "touchstart" (code taken from @Timothy Perez answer), though, you need jQuery 1.7+ for this
  $(document).on({ 'touchstart' : function(){
      //do whatever you want here
    } });

A: Given the response provided by Zenexer, a pattern that requires no additional HTML tags is:
jQuery('a').on('mouseover', function(event) {
    event.preventDefault();
    // Show and hide your drop down nav or other elem
});
jQuery('a').on('click', function(event) {
    if (jQuery(event.target).children('.dropdown').is(':visible') {
        // Hide your dropdown nav here to unstick
    }
});

This method fires off the mouseover first, the click second.

A: For those with common use case of disabling :hover events on iOS Safari, the simplest way is to use a min-width media query for your :hover events which stays above the screen width of the devices you are avoiding. Example:
@media only screen and (min-width: 1024px) {
  .my-div:hover { // will only work on devices larger than iOS touch-enabled devices. Will still work on touch-enabled PCs etc.
    background-color: red;
  }
}

A: For someone still looking for a solution if none of the above worked,
Try this,
@media (hover: hover)
{
    .Link:hover
    {
        color:#00d8fe;
    }
}

This hover pseudo will only be applied for devices with pointers and works normal on touch devices with just .active classes.

A: Just look at the screen size....
@media (min-width: 550px) {
    .menu ul li:hover > ul {
    display: block;
}
}

A: heres the code you'll want to place it in
// a function to parse the user agent string; useful for
// detecting lots of browsers, not just the iPad.
function checkUserAgent(vs) {
    var pattern = new RegExp(vs, 'i');
    return !!pattern.test(navigator.userAgent);
}
if ( checkUserAgent('iPad') ) {
    // iPad specific stuff here
}


Q: azure api gateway integration with AKS 502 - Web server received an invalid response while acting as a gateway or proxy server I am in process to integrate Azure API gateway with AKS.
in order to achieve this.
i had

*

*created AKS cluster with advance networking. consider it is in
aks-vnet

*created different vnet for API gateway.

*peer both vnet i.e. vnet for aks and for api gateway.

*created internal load balancer. by
running azure voting app yaml file also added annotation for using
internal load balancer
metadata:
  name: azure-vote-front
  annotations:
    service.beta.kubernetes.io/azure-load-balancer-internal: "true"

*added kubernates internal load balancer public ip in address probe of api gateway.
when i navigate in browser with public ip address of api gateway or dns name associated with api gateway i am getting following error
502 - Web server received an invalid response while acting as a gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

A: First, there is something wrong described in your case: You should provide add the kubernetes internal load balancer private IP to the application gateway backend pool.
Then I did the test as the steps in Integrate Application Gateway with AKS cluster. As the error shows that you should make the check if the application in the AKS works fine, in your case the application is azure voting app.
If you follow the Azure Kubernetes Service tutorial and push the image to Azure Container Registry, you must grant the AKS permission to access your ACR. See Authenticate with Azure Container Registry from Azure Kubernetes Service.
And on my side, I can access the azure voting app from the public IP of the application gateway. Hope this will help you.


Q: How do you monitor small changes to an XHR response? I'd like to be alerted to small changes in the responses of a website, which is not my own..  Any suggestions are welcome, thanks!


Q: Not able to set text in a Text Area I was unable to set text into the text area with browser.text_field(:id,"area").set "1=1". When i typed manually i noticed that the text("1=1") i typed is stored across spans as given below.

1 # the text 1 is stored here and followed by "=1" in next spans
=
1

Is there any other way that i can set text into the text area?

A: This worked for me:
require "watir-webdriver"
browser = Watir::Browser.new
browser.goto "ideone.com"
browser.div(:id => "file_div").textarea.set "1=1"

Are you sure you need to set text in textarea? If you are dealing with wysiwyg editor, you probably need to use send_keys:
browser.pre.send_keys "1=1"

More information: http://watirwebdriver.com/wysiwyg-editors/

A: It is important to send keys on proper element. In my case, after some experimentations, that was:

Editor was defined with this html:

<textarea class="text optional redactor" data-limit="450" data-persist="garlic" data-min-height="120" name="lesson[intro]" id="lesson_intro" dir="ltr" style="display: none;"></textarea>


Q: Efficient Dictionary change value or add (key,value) if not in dictionary Suppose I have a Dictionary<TKey, TValue>, where TValue is a reference type.
I want to assign TValue myNewValue to the element with TKey myKey. If there is no element with myKey, I want to add it.
I want to do this efficiently with a minimal GetHashCode():
private void AddOrReplace(TKey key, TValue value)
{
    Dictionary<TKey, TValue> myDictionary = GetMyDictionary(...);
    TValue existingValue;
    if (myDictionary.TryGetValue(key, out existingValue))
    {   // key already in dictionary
        existingValue = value;
    }
    else
    {   // key not in dictionary yet
        myDictionary.Add(key, value);
    }
}

This way, TKey.GetHashCode() is called once if the key already exist, but it is called twice if the key must be added.
However this wouldn't work if TValue is a value type
existingValue = value; // wrong! won't change the value in the dictionary

Code ought to be something like:
private void AddOrReplace(TKey key, int value)
{
    Dictionary<TKey, int> myDictionary = GetMyDictionary(...);
    if (myDictionary.ContainsKey(key)
    {   // key already in dictionary
        myDictionary.key = value;
    }
    else
    {   // key not in dictionary yet
        myDictionary.Add(key, value);
    }
}

This way TKey.GetHashCode() is always called twice.
Isn't there a more efficient method, where TKey.GetHashCode is only called once?

A: Dennis_E and Panagiotis Kanavos provided the answer. Thanks both of you.
I just add it here, in case someone thinks he has the same problem.
System.Collections.Generic.Dictionary.Item property (TKey) Describes it as follows:
Property Value
Type: TValue
The value associated with the specified key.

*

*get If the specified key is not found, a get operation throws a KeyNotFoundException,

*set a set operation creates a new element with the specified key.


Q: Can't login (through GUI) after upgrade from 11.10 to 12.04 After upgrading from 11.10 to 12.04 I can't login with my account through the GUI. If, at the login screen, I go to a command line I'm able to login and everything seems to work fine. I can also login as the guest account without any problems. But, logging in as my account causes a system freeze.
If I'm quick I can drop back to the command line, after starting graphical login process, and before the system freezes. If I do this I can check logs out and continue to use the system. But, when going back to the graphical session the system freezes immediately and I can no longer return to the command line.
System info: Linux x220r 3.2.0-24-generic #37-Ubuntu SMP Wed Apr 25 08:43:22 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
I also encrypted my home directory through the last (11.10) install. I suspected that might be a problem, but I can access my home directory fine while logging in through the command line.
Syslog taken right after starting a login from the login screen.
Apr 28 17:40:07 x220r sudo: pam_ecryptfs: pam_sm_authenticate: /home/matt is already mounted
Apr 28 17:41:43 x220r acpid: client 1093[0:0] has disconnected
Apr 28 17:41:43 x220r acpid: client connected from 1093[0:0]
Apr 28 17:41:43 x220r acpid: 1 client rule loaded
Apr 28 17:41:43 x220r kernel: [  142.913591] [drm:drm_mode_getfb] *ERROR* invalid framebuffer id
Apr 28 17:41:43 x220r kernel: [  142.913613] [drm:drm_mode_getfb] *ERROR* invalid framebuffer id
Apr 28 17:41:43 x220r kernel: [  143.000528] [drm] Changing LVDS panel from (+hsync, -vsync) to (-hsync, -vsync)
Apr 28 17:41:51 x220r lightdm: pam_ecryptfs: pam_sm_authenticate: /home/matt is already mounted
Apr 28 17:41:51 x220r kernel: [  151.180497] Valid eCryptfs headers not found in file header region or xattr region, inode 524953
Apr 28 17:41:51 x220r kernel: [  151.180507] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO
Apr 28 17:41:51 x220r kernel: [  151.226646] Valid eCryptfs headers not found in file header region or xattr region, inode 524953
Apr 28 17:41:51 x220r kernel: [  151.226649] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO

lightdm.log taken right after starting a login from the login screen.
[+1.47s] DEBUG: Connecting to XServer :0
[+1.47s] DEBUG: Starting greeter
[+1.47s] DEBUG: Started session 1342 with service 'lightdm', username 'lightdm'
[+1.59s] DEBUG: Session 1342 authentication complete with return value 0: Success
[+1.59s] DEBUG: Greeter authorized
[+1.59s] DEBUG: Logging to /var/log/lightdm/x-0-greeter.log
[+1.59s] DEBUG: Session 1342 running command /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter
[+1.82s] DEBUG: Greeter connected version=1.2.1
[+1.82s] DEBUG: Greeter connected, display is ready
[+1.82s] DEBUG: New display ready, switching to it
[+1.82s] DEBUG: Activating VT 7
[+2.40s] DEBUG: Greeter start authentication for matt
[+2.40s] DEBUG: Started session 1536 with service 'lightdm', username 'matt'
[+2.41s] DEBUG: Session 1536 got 1 message(s) from PAM
[+2.41s] DEBUG: Prompt greeter with 1 message(s)

Any ideas about things to look into? I hate to do this, but I've already pulled the files I want and I'm considering a clean reinstall.
UPDATE:
Looks like I'm suffering from this dual-monitor bug: https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-video-intel/+bug/921236
Unplugging my external monitor lets me log in. So far this is no confirmed fix, so I'm without an external monitor for the time being.
UPDATE 2:
I was able to fix the issue by downgrading xserver-xorg-input-evdev. More details here: https://bugs.launchpad.net/evdev/+bug/921236/comments/64

A: I was glad to see the post and the UPDATE2. But I am completely at loss on how to fix it. From - https://launchpad.net/~sarvatt/+archive/sru1/+build/3118994
I installed the .deb package. After that, trying to install .udeb package, throws an error saying it couldn't replace a lib file already in .deb. Am I trying to do it right? Kindly help ! Below is the error when I ran dpkg install on the .udeb package:
dpkg: error processing xserver-xorg-input-evdev-udeb_2.6.99.901-1ubuntu3~lp921236_amd64.udeb (--install):
 trying to overwrite '/usr/lib/xorg/modules/input/evdev_drv.so', which is also in package xserver-xorg-input-evdev 1:2.6.99.901-1ubuntu3~lp921236
Errors were encountered while processing:
 xserver-xorg-input-evdev-udeb_2.6.99.901-1ubuntu3~lp921236_amd64.udeb


Q: Showing xdebug with firefox 29.0 Since the latest update with firefox i can't seem to find  my Xdebug.
I have tried going to Show->tools
but they changed the way you add the developer line.
Has anyone experianced the same and know how to show  the bottom line where you enable / disable xdebug?

A: Update:
With the last update it disappeared almost everything :-)
Now there is an add-on toolbar hidden by default.
If not over there you can search in the upper right corner where there is a button with the tooltext "Open Menu" (3 horizontal lines). When you press the button it appears a panel, if you select customize on the bottom it will open a page with Additional tools and features. I find over there some of the add-on that I installed.

Original:
Did you refer to the bar that appear with Shift + F2 ?
Under Tools-->Web Developer there is the list of tools directly available.
with Crtl + Shift + S you enable the debugger
with Ctrl + Shift + I you toggle the tools panel

A: this is a working add on for xdebug -- firefox 29..
https://addons.mozilla.org/en-US/firefox/addon/easy-xdebug-with-moveable-/?src=api


Q: In Ruby on Rails, is there a way to check the order of the rows in a table using RSpec/Capybara for views testing? I have a table with numerous rows. These rows are ordered specific to the data within them. I am looking to write tests for the order of the rows in the table. Is there a way to do this using RSpec/Capybara?

A: You can try use xpath selectors, for example
within(:xpath, "//table/tr[1]/td") do
  page.should have_content('First row content')
end

within(:xpath, "//table/tr[2]/td") do
  page.should have_content('Second row content')
end


Q: How to show that this polynomial has $n$ positive roots? Let $n \in \mathbb{N}$ and $a_1, \dots, a_n, b_1, \dots, b_n > 0$.
Define the function
$$
P(x) = \Bigg(\sum_{i=1}^n \frac{a_i}{x-b_i}\Bigg) - 1, \qquad x \in \mathbb{R}_+ \setminus \{b_1, \dots, b_n\}.
$$
How can I check that $P$ has $n$ distinct positive roots?
I have rearranged $P(x) = 0$ as
$$
\sum_{i=1} a_i \prod_{j \neq i} (x-b_j) = \prod_{i=1}^n (x-b_i),
$$
but did not know how to proceed.
I have also looked at Sturm chains without much success.

A: Take $x$ slightly larger than $b_i$, then the term $\frac{a_i}{x-b_i}$ is very large positive so $P$ is positive. Similarly take $x$ slightly less than $b_{i+1}$ and you get that $P$ is negetive. Since $P$ is continuous in each interval $(b_i,b_{i+1})$ there is a root in each such interval. That gives $n-1$ positive roots. There is one more root larger than $b_n$ since $P$ is negative for large $x$.

A: Let $b_i<b_{i+1}$ for $1\leq i\leq n-1.$ The derivative $P'(x)$ is negative wherever $P(x)$ is defined. So $P(x)$ is strictly decreasing on $(-\infty,b_1),$ and on $(b_i,b_{i+1})$ for $1\leq i \leq n-1,$ and on $(b_n, \infty).$
Observe that $\lim_{x\to \infty}P(x)=-1$ and  $\lim_{x\to b_n^+}P(x)=+\infty,$ so $P(x)$ has a zero in $(b_n,\infty).$
Observe  for $1<i\leq n-1$ that $\lim_{x\to b^-_{i+1}}P(x)=-\infty$ and that $\lim_{x\to b_i^+}P(x)=+\infty$ so $P(x)$ has a zero in $(b_i,b_{i+1})$.


Q: Codeigniter Insert Multiple Fields Using Foreach Loop I have a problem when I want to insert multiple fields which are using foreach loop (to get the value form database), here is my form:
<form class="stdform" action="<?php echo $action_url; ?>" method="post">

    Check Date <input class="span3" type="text"
        id="datepicker" name="check_date" value="" required="required"
        placeholder="Tanggal cek" />

                #
                Device
                IP Address
                NAT IP Address
                Check OS
                Application/Server
                Shift A
                Shift B
                Remark
                Report

            <?php
                        $num=1;
                        foreach( $get_server_assets as $row ) {

                         ?>

                    <?php echo $num; ?>

                <input class="span12" type="text" name="device[]"
                    value="<?php echo $row->s_device; ?>" />
                <input class="span9" type="text" name="ip_address[]"
                    value="<?php echo $row->s_ip; ?>" />
                <input class="span9" type="text" name="nat_ip[]"
                    value="<?php echo $row->s_nat_ip; ?>" />
                <select class="span12" name="check_os[]">
                        <option value=""></option>
                        <option value="Good">Good</option>
                        <option value="Not Good">Not Good</option>
                </select>
                <input class="span10" type="text" name="app_name[]"
                    value="<?php echo $row->app_server; ?>" />
                <select class="span12" name="check_app_a[]">
                        <option value=""></option>
                        <option value="Good">Good</option>
                        <option value="Not Good">Not Good</option>
                </select>
                <select class="span12" name="check_app_b[]">
                        <option value=""></option>
                        <option value="Good">Good</option>
                        <option value="Not Good">Not Good</option>
                </select>
                <input class="span12" type="text" name="remark[]" value="" />
                <input class="span12" type="text" name="report[]" value="" />

            <?php $num++; } ?>

        <button class="btn btn-primary btn-large" type="submit" name="submit"
            value="true">Submit</button>
          Cancel

</form>

And here is my controller:
$data = array();

        $count = count($this->input->post('device'));

        for($i=0; $i<$count; $i++) {

            $data[] = array(
                'check_date'=>$this->input->post('check_date'),
                'device'=>$this->input->post('device' . $i),
                'ip_address'=>$this->input->post('ip_address' . $i),
                'nat_ip'=>$this->input->post('nat_ip' . $i),
                'check_os'=>$this->input->post('check_os' . $i),
                'app_name'=>$this->input->post('app_name' . $i),
                'check_app_a'=>$this->input->post('check_app_a' . $i),
                'check_app_b'=>$this->input->post('check_app_b' . $i),
                'remark'=>$this->input->post('remark' . $i),
                'report'=>$this->input->post('report' . $i),
            );

        }

        $this->db->insert_batch('server_checklist',$data);

        /*foreach($_POST['data'] as $d) {

            $this->db->insert('server_checklist',$d);

        } */

        redirect('admin/viewServerChecklist');

When I submit there is no data insert, only check_date stored. And the rest give value 0.
Click here for image
Can someone help me??

A: try this, instead of appending, try to access the index of the array.
  $data[] = array(
            'check_date'=>$this->input->post('check_date'),
            'device'=>$this->input->post('device')[$i],
            'ip_address'=>$this->input->post('ip_address')[$i],
            'nat_ip'=>$this->input->post('nat_ip')[$i],
            'check_os'=>$this->input->post('check_os')[$i],
            'app_name'=>$this->input->post('app_name')[$i],
            'check_app_a'=>$this->input->post('check_app_a')[$i],
            'check_app_b'=>$this->input->post('check_app_b')[$i],
            'remark'=>$this->input->post('remark' )[$i],
            'report'=>$this->input->post('report')[$i],
        );

A: Try This:
$data_table = $this->input->post(NULL, TRUE);

        if (empty($data_table['device']))
        {
            redirect('admin/viewServerChecklist?message=error');
        }

        $required = array('device', 'ip_address', 'nat_ip', 'check_os', 'app_name', 'check_app_a', 'check_app_b', 'remark', 'report');
        $data = array();

        foreach ($data_table['device'] as $key => $value)
        {
            // check list table. if value required not exist. continue to next index
            $row = array();
            foreach ($required as $key2 => $value2)
            {
                if (!isset($data_table[$value2][$key])) continue;
                $row[$value2] = $data_table[$value2][$key];
            }
            // since check_date is not array. we need to parse to row data
            $row['check_date'] = $data_table['check_date'];
            $data[] = $row;
        }

        $this->db->insert_batch('server_checklist', $data);

        /*foreach($_POST['data'] as $d) {

            $this->db->insert('server_checklist',$d);

        } */

        redirect('admin/viewServerChecklist');


Q: Will #if __IPHONE_4_0 work on iPad? Will this check work on the iPad as well as iPhone? I guess I am just confused about using the term "iPhone" on an iPad. Is there something else I need to check for iPad OS version or does the macro refer to the general iOS version.
#if __IPHONE_4_0
// Do stuff
#elif __IPHONE_3_0
// Do 3.0 stuff
#endif

A: The problem with __IPHONE_3_0 and the like is that they are defined even if targeting other iOS versions; they are version identification constants, not constants that identify the target iOS version. Use __IPHONE_OS_VERSION_MIN_REQUIRED
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
#elif __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0
#else
#endif

or even:
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
#elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000
#else
#endif

to get around the bug mentioned in the comments for "How to target a specific iPhone version?" __IPHONE_OS_VERSION_MAX_ALLOWED might also be of use, in limited circumstances.
And, yes, it doesn't matter what device the app will run on. These constants are defined by the compiler and don't exist on the devices. Once the pre-processor runs, no macros are left. Though there are differences in the devices themselves, the iPhone and iPad both run iOS, and that's what you're really targetting.

A: The code you posted is a compiler directive. This means that it will not run on iPad or iPhone. It is handled when you build your app binary. Incidentally, if you're building for iPad, then you are building for 3.2, not 3.0 or 4.0.
If you use 3_2 or 4_2 instead of 3_0 or 4_0 it should work.
Good luck.


Q: Acces denied error when I use firewall.dll propertry . (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) I have code that use firewall.dll to add a rule to windows firewall but i get this exception"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
this is my code:
using NetFwTypeLib;
namespace Tserver
{
    class Program
    {
    static void Main(string[] args)
    {

        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
        Type.GetTypeFromProgID("HNetCfg.FWRule"));
                   firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
        firewallRule.Description = "Used to block all internet access.";
        firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.Name = "Block Internet";

        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(firewallRule);
}

A: You need to have admin rights to do what you're doing.
I've had the same problem a client machine, but as soon as I tried to do the same thing on a machine with administrator rights (Windows 7), everything worked perfectly.


Q: Gauge/chart that "fills" an image rather than a plain circle I am trying to create a donut chart/gauge, that illustrates a % amount of something. This value will increase over time, until at somepoint its full/complete
However, the complexity is that instead of just a plain circle/donut shape, I want to illustrate a circle pattern being filled up as the value increases.
Below is an example of a highcharts gauge filled to 25%.
Fiddle Example
See Fiddle Example
And below is a picture (based on a random design from Shutterstock), of the effect I am attempting to achieve.

Would drawing this with SVG be the best way to do it, or is there a better way?
Thanks


Q: Adding legends in a graphic I have several datasets,

and I successfully plotted them as points in a Graphic.

Then, how can I automatically create legends similar to PlotLegends with a color and a label for each dataset in the graphic? And the colors of the dataset points and the legend are consistent.
My goal is to plot a graph like this

Note: the intervals of x-value of my dataset are not equal, therefore I prefer not to use ListPlot.

A: Extract your data using the form:
mydata = (Point[{{1, 2}, {3, 4}, {5, 6}}] /. Point -> List)
then ListPlot[mydata, Legended->True]
or
PlotLegends -> {"mydata1","mydata2"}

A: Have you checked the documentation yet? Here.
This is an example there.
ListLinePlot[Table[Accumulate[RandomReal[{-1, 1}, 250]], {3}],
Filling -> Axis, PlotLegends -> {"one", "two", "three"}]

A: Fake datasets with a structure similar to the structure of your datasets:
SeedRandom[77]
graphics = Table[{PointSize[.001],
 Point @ Transpose[{x = Sort @ RandomInteger[1000, 5000],
    RandomInteger[100] Sin[RandomReal[2 Pi] + RandomReal[2 Pi] x / 500] +
      RandomReal[5, 5000]}]}, {5}];
g1 = Graphics[graphics, AspectRatio -> 1/GoldenRatio,
   ImageSize -> 400, Frame -> True];

Colored version of the same:
colors = ColorData[63, "ColorList"][[;; Length@graphics]];
g2 = Graphics[Transpose[{colors, graphics}],
   AspectRatio -> 1/GoldenRatio, ImageSize -> 400, Frame -> True]

using LineLegend and Legended
labels = Style["dataset " <> ToString[#], 16] & /@ Range[Length@graphics];
legend = LineLegend[Directive[#, AbsoluteThickness[5]] & /@ colors, labels];
Row[{g1, Legended[g2, Placed[legend, {Left, Top}]]}, Spacer[30]]


Q: Plot both multi-index labels on x-axis in pandas plot I have a multi-index dataframe and would like to both index as x-axis labels.  Where each of the "forecasts" index1 is listed as below, but want "year" index[0] to be shown instead of the x-axis label "forecast", so each panel would show the year index: 2020, 2050, 2099 below the forecast names.  I am also trying to place labels above each bar with the values from the "most important observation" column.
  def plot_function(x, ax):
        ax = graph[x]
        ax.set_xlabel(x, weight='bold')
        return df_par_trans.xs(x).plot(kind='bar', stacked='False', ax=ax, legend=False)

n_subplots = len(df_par_trans.index.levels[0])
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, sharey=True, figsize=(14, 8))

graph = dict(zip(df_par_trans.index.levels[0], axes))
plots = list(map(lambda x: plot_function(x, graph[x]), graph))
ax.tick_params(axis='both', which='both', length=0)
fig.subplots_adjust(wspace=0)

plt.legend()
plt.show()

my dataframe looks like this:
year    forecast  most important observation  percent increase when left out
2020    PV6SM     Harkins                     17.371021
2050    PV6SM     Harkins                     10.569719
2099    PV6SM     Harkins                     12.343476
2020    PV3S      PV3S                        34.095863
2050    PV3S      PV3S                        32.565513
2099    PV3S      PV3S                        26.110555

A: You need to rename the index with the year:
groups = df.groupby("year")
fig, axes = plt.subplots(1, len(groups), sharey=True, figsize=(14,8))

for ax, (year, group) in zip(axes, groups):
    # The rename_axis function makes the difference
    group.set_index("forecast").rename_axis(year)["percent increase when left out"].plot(kind="bar", ax=ax)
    ax.tick_params(axis='both', which='both', length=0)

ax.legend()
fig.subplots_adjust(wspace=0)

Output:


Q: Facebook sharing not scraping url correctly in Codeigniter I am trying to share on facebook but didn't get meta data. Also i have try in facebook debug tool but didn't get meta data.
facebook debug tool url https://developers.facebook.com/tools/debug/
I have already added meta data. Bellow meta data and url.

<meta property="og:title" content="Afrocamgist" />
<meta property="og:type" content="article" />
<meta property="og:image" content="https://www.afrocamgist.com/public/campus_post/Screenshot_20180815-132503.png" />
<meta property="og:description" content="Good morning famz!" />
<meta property="og:url" content="https://www.afrocamgist.com/" />
<meta property="og:site_name" content="Afrocamgist" />
<meta property="fb:app_id" content="300434940539027" />

URL : https://www.afrocamgist.com/post/single/434
Please help me. Thanks.

A: Solve issue, Actually problem with protected page. My page is open after user login.
I have a remove permission and publish to solve my issue.
Thanks.


Q: How find all values of $\frac{|x+y|}{|x|+|y|}+\frac{|y+z|}{|y|+|z|}+\frac{|z+x|}{|z|+|x|}$
$$A =
 \frac{|x+y|}{|x|+|y|}+\frac{|y+z|}{|y|+|z|}+\frac{|z+x|}{|z|+|x|}$$
Where $x, y $ and $z$ are real numbers and non-zero. How can we find
  all values of $A$?

My try:
From $x, y$ and $z$ at least two of have same sign $\longrightarrow A \geq 1$
$$\left\{
\begin{array}{}
|x+y| \leq |x| + |y| \longrightarrow \frac{|x+y|}{|x|+|y|} \leq 1 \\
|z+y| \leq |z| + |y| \longrightarrow \frac{|z+y|}{|z|+|y|} \leq 1 \\
|x+z| \leq |x| + |z| \longrightarrow \frac{|x+z|}{|x|+|z|} \leq 1 \\
\end{array}
\right. \longrightarrow A \leq 3$$
Also I have an example for $A = 3$ and $A = 1$:
$A=3 \longleftarrow x=y=z\neq0$
$A=1 \longleftarrow x=y\neq0$ and $z=-x$
But still I can't find all values of $A$.

A: For $t\in[0,1]$ let $(x,y,z)=(1,1,-t)$. Then $$A(x,y,z)=1+2\frac{1-t}{1+t}.$$ When $t=0$ this is $3$, when $t=1$, this is zero. Since $A(x,y,z)$ is continuous on $\mathbb R^3\setminus\{(0,0,0)\}$, $A$ must take all values between $1$ and $3$, by the intermediate value theorem. Or we can find $t$ based on $A$:
$$\frac{A+1}{2}=\frac{2}{1+t}$$ or $t=\frac{4}{A+1}-1.$ Show when $A\in [1,3]$ then $t\in[0,1]$.
Now you need to prove that $1\leq A\leq 3$ in general. $A\leq 3$ is easy, since each term is $\leq 1$ by the triangle inequality. $A\geq 1$ is because one pair of $x,y$ must be the same sign (or one zero) in which case one of the terms is always $1$.

A: You basically already solved this, you just need to think of this from a different PoV:
Think of A as a function $A(x,y,z)=\frac{|x+y|}{|x|+|y|}+\frac{|y+z|}{|y|+|z|}+\frac{|z+x|}{|z|+|x|}.$
Now because you divide by sum of 2 positive numbers this function exist for all values, in other words continuous.
Because you know that A can't be less than 1 and A can't be more than 3 and A is continuous it has to go from 1 to 3 somehow, all the ways to do that have something in common, they all pass through all the numbers between 1 and 3 because if they don't it means there is a hole in the function, but we already know that the function is continuous, therefore $1\le A\le 3$


Q: jQuery increase data attribute value for each items I'm trying to make a jQuery program that increases the data attribute value for each list item.
var current = 0;
$(".kunde-logo-listing").each(function() {
   $(this).attr("data-wow-delay", current);
   current++;
});

I tried to use the above and the output is as follows:
data-wow-delay="0"
data-wow-delay="1"
data-wow-delay="2"
data-wow-delay="3"
data-wow-delay="4"

But the output I'm trying to get should be:
data-wow-delay="000ms"
data-wow-delay="100ms"
data-wow-delay="200ms"
data-wow-delay="300ms"
data-wow-delay="400ms"

Anyone got an idea how to make this work? Is it something with concatenating the value to a string of "ms" ?
Cheers!

A: var current = 0;
$(".kunde-logo-listing").each(function() {
    $(this).data("wow-delay", current+"00ms");
    current++;
});

A: You can use this as follows:
var current = 0;
$(".kunde-logo-listing").each(function () {
    $(this).data("wow-delay", current++ * 100 + "ms");
    //                        ^^^^^^^^^^^^^^^^^^^^^^^
});


Q: TableView not updating after button action I'm relatively new to swift, and I'm trying to have a view that when it loads it will display some info on my tableView, then in the same view I have a textfield and a button
I want that the button performes an action that fetchs data from my server and updates my tableView
The problem is that the table is not being updated. How can I get the table to be updated?
CODE:
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = 80;
    tableView.tableFooterView = UIView();
    self.url = URL(string: "http://xxxxxxxx.com/xxxxx/api/produtos/listagem/favoritos/\(userID)");
    downloadJson(_url: url!);

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return produtos.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProdutoCell1") as? ProdutoCell else{
        return UITableViewCell()
    }

    cell.lbl_nome_json.text = produtos[indexPath.row].nome;
    cell.lbl_categoria_json.text = produtos[indexPath.row].categoria;
    cell.lbl_loja_json.text = produtos[indexPath.row].loja
    //= produtos[indexPath.row].categoria;
   // cell.lbl_loja.text = produtos[indexPath.row].loja;

    if let imageURL = URL(string: "http://xxxxxxxxxx.com/myslim/api/"+produtos[indexPath.row].url){

        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL);

            if let data = data{
                let image = UIImage(data: data);
                DispatchQueue.main.async {
                    cell.imgView_json.image = image;
                }
            }
        }

    }

    return cell;
}

ACTION:
@IBAction func btn_search(_ sender: Any) {

    if self.txt_search.text == "" {
        let alert = UIAlertController(title:"Alert",message: "Insira algo para pesquisar",preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))

         self.present(alert,animated: true,completion: nil)
    }else{
        var pesquisa = String();
        pesquisa = self.txt_search.text!;
        let url2 = URL(string: "http://xxxxxxxx.com/xxxxxx/api/produtos/listagem/favoritos/\(pesquisa)/\(self.userID)");

        downloadJson(_url: url2!);

    }

 func downloadJson(_url: URL){

    guard let downloadURL = url else {return}
    URLSession.shared.dataTask(with: downloadURL){data, urlResponse, error in

        guard let data = data, error == nil, urlResponse != nil else{
            print("algo está mal");
            return;
        }

        do{
            let decoder = JSONDecoder();
            let downloadedProdutos = try decoder.decode([ProdutoModel].self, from: data);
            self.produtos = downloadedProdutos
            print(downloadedProdutos);

            DispatchQueue.main.async {
                self.tableView.reloadData();
                print("reload");
            }
        }catch{
            print("algo mal depois do download")
        }

        }.resume();
}

EDIT
I added some print to see how many object were being returned on my downloadedProdutos variable, on the downloadJson() function.
And at the viewdidload I get 2 object, its normal because I only have 2 Products, but when the action is done I still get 2 object although I should get only 1 object

A: You need to set tableView.dataSource = self in viewWillAppear and it looks you missed func numberOfSections() -> Int method.
Add UITableViewDataSource like this
class YourViewController: UIViewController, UITableViewDataSource and it will recommend you required methods


Q: PageBuilder error when saving category magento 2.3.3 On category page when try to save category has error on console ([ERROR] Page Builder was rendering for 5 seconds without releasing locks.) Can't save category changes.  I try these solutions but it doesn't work https://github.com/mirasvit/module-blog/issues/162, https://github.com/magento/magento2/issues/25620. I have porto theme and module Smartwave_Maegamenu. Please help =)

A: I found bug in Smartmage/Megamenu on category_form.xml and fix it. You need to apply changes for all fields(wyswig). Please take a look example for sw_menu_block_top_content field. Now it'll work with Magento Page Builder.
<field name="sw_menu_block_top_content" template="ui/form/field" sortOrder="90" formElement="wysiwyg">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="wysiwygConfigData" xsi:type="array">
                        <item name="height" xsi:type="string">100px</item>
                        <item name="add_variables" xsi:type="boolean">false</item>
                        <item name="add_widgets" xsi:type="boolean">false</item>
                        <item name="add_images" xsi:type="boolean">true</item>
                        <item name="add_directives" xsi:type="boolean">true</item>
                        <item name="is_pagebuilder_enabled" xsi:type="boolean">true</item>
                        <item name="pagebuilder_button" xsi:type="boolean">true</item>
                    </item>
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <label translate="true">Top menu</label>
                <dataScope>sw_menu_block_top_content</dataScope>
            </settings>
            <formElements>
                <wysiwyg class="Magento\Catalog\Ui\Component\Category\Form\Element\Wysiwyg">
                    <settings>
                        <rows>8</rows>
                        <wysiwyg>true</wysiwyg>
                    </settings>
                </wysiwyg>
            </formElements>
        </field>

A: If you are using text editor in your block/dynamic block, check that text editor having any HTML tags. if yes just use HTML editor instead of text editor, this resolved a problem for me.


Q: I am writing a program to find number of 3's in factorial of a given number. The input from the user is the number I am using this logic. Suppose I have to find number of 3's in 10!. Thenenter image description here
import java.util.*;
import java.io.*;

class testing
{
    public static void main(String args[])
    {
        int temp=0,a;
        Scanner obj = new Scanner(System.in);
        System.out.print("Enter the number ");
        int n = obj.nextInt();
        int i=1;
        while(n<(Math.pow(3,i)))
        {
            a= n/(int)(Math.pow(3,i));
            temp=temp+a;
            i++;
        }
        System.out.println("Answer: " +temp);
    }
}

A: *

*change < to > in  if condition as
   n >(Math.pow(3,i))

*or use below code which calculates pow only once
int temp = 0, a;
Scanner obj = new Scanner(System.in);
System.out.print("Enter the number ");
int n = obj.nextInt();
int i = 1;
while (true) {
    int pow = (int) Math.pow(3, i);
    if (pow > n) {
        break;
    } else {
        temp = temp + n / pow;
    }

    i++;
}
System.out.println("Answer: " + temp);


Q: Пути к файлам <?php
include 'path/to/file.php'; // тут всё ок, при клике на file.php открывается файл
$path_to_file = 'path/to/file.php'; // не ок, мб есть какая-то специальная  директива/phpdoc, которая скажет IDE, что это путь к файлу и нужно распарсить?
?>

A: Если нужно перейти к файлу, указанному как значение в строковой переменной, то есть вот такой способ:

*

*Выберите часть строки, которую нужно считать путем к файлу
 1.а Выделите нужный участок мышкой
 1.б Расширяйте выделение от текущей позиции курсора с помощью ctrl+shift+стрелка [влево|вправо]

*Нажмите Ctrl+Shift+N (откроется окно Go to file и выделенная строка подставится в фильтр)

*Далее по ситуации:
 3.а Клацнуть Enter (если одно совпадение)
 3.б Два раза кликнуть по нужной строке (если несколько совпадений)
После этих манипуляций файл откроется в новой вкладке.
A: Это нормально, ведь Вы создаете переменную с указанием типа данных string, в который вы можете запихнуть что угодно. Поэтому IDE не смысла распарсивать все строковые данные и вставлять туда линк.  Представьте, если в переменную вогнать целую страницу текста и IDE будет тратить свое время, чтобы найти там file.php и создать на него ссылку, это лишнее.
Используйте другую очень удобную фичу у phpStorm: быстро два раза жмете Shift и открывается хороший поиск по всему. Там пишите "file" и вам уже нужный результат будет выдан.


Q: Migration 6i to 10g Oracle reports I have problems with reports when migrating from 6i to 10g. Everything works fine except when a report is opened from another report. I am getting an error-

REP-56107: Invalid environment id myenv for Job Type report in the command line

I only get this error when I try to open a report from another report. My Oracle version is Oracle 10.2.0.4.

A: I think the defaultEnvId attribute for the environment is set incorrectly in your server_name.conf file. Typically the defaultEnvId would look something like below-
<engine id="rwEng" initEngine="1" minEngine="0" maxEngine="10" engLife="50" maxIdle="30" defaultEnvId="JP"/>

And consecutively the definition as-
<environment id="JP">
  <envVariable name="NLS_LANG" value="Japanese_Japan.JA16SJIS"/>
  <envVariable name="NLS_CURRENCY" value="¥"/>
  <envVariable name="DISPLAY" value="MyServer.MyCompany.com:0.0"/>
</environment>

I am assuming that your file has the defaultEnvID="myenv" and <environment id="myenv">. Check this to make sure it points to the right environment. Make sure that the defaultEnvId in enginedefinition matches the environment definition. Also, keep in mind that this is an optional setting so you may or may not need this. See this for details.


Q: Tensorflow / keras issue when optimizing with optuna I'm pretty new to machine learning, I've been trying to teach myself neural networks from following sentdex tutorials. I followed his tutorial on using recurrent neural networks for predicting the price of various crypto-currencies and succeeded after changing NumPy arrays and some of the syntax. Now I've been trying to add optimization to it since I've noticed just how drastically overfitting can change with tweaking the learning rate and layers of the network.
The code of the one that works with no errors is this one
https://colab.research.google.com/drive/1VNeRLeGBByEIdMVwXcbsOR8xjWwsHHoQ?usp=sharing
It looks like I just copied and pasted the code but this is just because I was troubleshooting the code and I just referencing this one with the one I followed from the tutorial and then continued with this one after I got it working.
I've been trying to follow the tutorials for optuna and code I found for optimizing networks online so I'm trying to add it from these sources
https://github.com/optuna/optuna/blob/master/examples/tensorflow/tensorflow_eager_simple.py
https://github.com/optuna/optuna/blob/master/examples/keras/keras_integration.py
https://colab.research.google.com/drive/1-tANR7FopTX_ipAUCJmfZ2h_-iu3ljD_?usp=sharing
and what I'm trying to make is this
https://colab.research.google.com/drive/1cgnz7XUwnhfBvsA9whCXKQ3PrRs_sddh?usp=sharing
this is where I'm getting errors. At first, when I was making this post I was stuck on
ValueError: Shapes (None, 1) and (None, 50, 2) are incompatible
but then I remembered that in the one I followed the tutorial on I needed one recurrent layer without
return_sequences=True before I continued with Dense layers
so I tried to add another recurrent layer without returning sequences and now I'm getting this
ValueError: Input 0 of layer lstm_20 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 2)
I'm not entirely certain where to go from here. I feel like I'm just doing something stupid, I was stuck on trying to figure out how to use a convolutional neural network from a tutorial on my own images for a year because I was reshaping instead of resizing the pictures. I hope it's something simple like that.
Thanks for all your guy's help, you guys have been very helpful since I've started my programming journey.

A: I believe the issue was in building the model using optuna. After several errors and fixing a lot of issues, I got it all working. If anyone's interested here's the section relevant to the errors I was getting.
    def create_model(trial):
# We optimize the numbers of layers, their units and weight decay parameter.

n_layers = trial.suggest_int("n_layers", 3, 20)
weight_decay = trial.suggest_float("weight_decay", 1e-100, 1e-1, log=True)
lr = trial.suggest_float("lr", 1e-12, 1e-1, log=True)

momentum = trial.suggest_float("momentum", 0.0, 1.0)

model = tf.keras.Sequential()

#model.add(Dropout(0.1))
for i in range(n_layers):

    dropout = trial.suggest_float("dropout_l{}".format(i), 0.05, 0.5)

    num_hidden = trial.suggest_int("n_units_l{}".format(i), 32, 256, log=True)

    model = Sequential()

    model.add(LSTM(num_hidden, input_shape=(train_x.shape[1:]), return_sequences=True))

    model.add(Dropout(rate=dropout))

    model.add(LSTM(num_hidden))

    model.add(Dropout(rate=dropout))

    model.add(Dense(num_hidden, activation='relu'))

    model.add(Dropout(rate=dropout))

model.add(tf.keras.layers.Flatten())
    model.add(Dense(
            num_hidden,
            activation="relu",
            kernel_regularizer=tf.keras.regularizers.l2(weight_decay)
        )
    )
model.add(Dense(2, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
    #tf.keras.layers.Dense(2, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))

        # Compile model.
model.compile(
    optimizer=tf.keras.optimizers.SGD(lr=lr, momentum=momentum, nesterov=True),
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)

return model

and if you want to see all of the code for it here's what I have so far, needs a lot of tidying up but it works. Any advice is greatly appreciated.
https://colab.research.google.com/drive/1cgnz7XUwnhfBvsA9whCXKQ3PrRs_sddh?usp=sharing


Q: PHP: Unable to decrypt AES 128 CBC I have a string encrypted in AES 128 + Zero Padding + IV and CBC mode.

*

*About zero padding, if the length is not 128bit, the encryption will
fill the remaining part 0x00 and reach 128 bit.

*An IV value can be specified successfully only if both IV value and IV value confirm are set to the same value

*The default value is all 0x00

*So The Password exampl= ** bit + ** zeros

I've tried too many things to decrypt this, like
function decrypt($data, $key)
{
    $encryption_key = base64_decode($key);
    list($encrypted_data, $iv) = array_pad(explode('::', base64_decode($data), 2), 2, null);
    return openssl_decrypt($encrypted_data, 'aes-128-cbc', $encryption_key, 0, $iv);
}

I tried too many other things, nothing works, what am I doing wrong? I am using "exampl", as the key.


Q: CommandButton action: use value of inputText as parameter in dynamic URL I need to make a small form where user types a number into the inputField, and clicks on a button, then is sent to a page, using that number as a parameter to the page.
So far I got into this:
<p:inputText id="myText" style="width:75px;" />
<p:commandButton id="myButton" value="Ir"
    action="/site/page.xhtml?id=${param['form:myButton']}"
    title="Ir" ajax="false" proces="@this,myText" />

tried with ${param['form:myButton']} and #{param['form:myButton']}, error is the same.
Problem is, JSF thinks its a method expression...
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/intranet] threw exception [/myPage action="/site/page.xhtml?id=${param['form:myButton']}".xhtml @95,41  action="/site/page.xhtml?id=${param['form:myButton']}" Not a Valid Method Expression:  action="/site/page.xhtml?id=${param['form:myButton']}" with root cause
javax.el.ELException: Not a Valid Method Expression:  action="/site/page.xhtml?id=${param['form:myButton']}"
at org.apache.el.lang.ExpressionBuilder.createMethodExpression(ExpressionBuilder.java:236)
at org.apache.el.ExpressionFactoryImpl.createMethodExpression(ExpressionFactoryImpl.java:55)
at org.jboss.weld.util.el.ForwardingExpressionFactory.createMethodExpression(ForwardingExpressionFactory.java:43)
at org.jboss.weld.el.WeldExpressionFactory.createMethodExpression(WeldExpressionFactory.java:64)
at com.sun.faces.facelets.tag.TagAttributeImpl.getMethodExpression(TagAttributeImpl.java:222)
at com.sun.faces.facelets.tag.jsf.ActionSourceRule$ActionMapper2.applyMetadata(ActionSourceRule.java:104)
at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:81)
at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:129)
at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:102)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:402)

and this is the bottom-most exception trace.
Question: how can I pass the value typed into of the input-field into the action of the Button when the button is clicked, so the browser navigates to the desired page passing the value in the input as a parameter, without resorting to a backing bean.
I don't need to communicate with the server, just forward the page.
any solution using jQuery or plain javascript in tandem with JSF is acceptable too.
using mojarra, primefaces 3.3.1

A: use <f:param> It's explained in this article from BalusC http://balusc.blogspot.in/2011/09/communication-in-jsf-20.html#ProcessingGETRequestParameters

A: I do not need a bazooka to kill a mouse. The answer is very simple.
bind a javascript function to the onclick of the button, and in that function, retrieve the value of the input field by its id, then assemble URL with the parameters and navigate away from within the javascript function.
JSF code (assume they are inside a form with myForm as its id):
<p:inputText id="myInput" style="width:75px;" />
<p:commandButton id="myButton" value="Ir" onclick="navega();" title="Ir" ajax="false" proces="@none" />

Javascript script, declared on a separate file or later on in the xhtml document:
function navega() {
     var submittedInputValue = $('#myForm\\:myInput').val();
     window.location.href = "/site/mypage.xhtml?param1=whatever&id=" + submittedInputValue ;
                }

Take note of the prepend id (myForm:myInput), of using \\ to escape the : in jQuery, and using & instead of & in the xhtml so its not treated as an entity.
Note: probably not all of those commandButton attributes are required, feel free to edit this answer and remove the useless ones.
EDIT: removed the submit and changed process to @none on the command button.


Q: same session use in zf1 , zf2 project I have two application in zf1 and zf2 on save server, I have created login system in zf2, when i login zf2 it working fine.
Now i want to access zf2 session in zf1, it showing
   [zf2_auth] => __PHP_Incomplete_Class Object
   (
          [__PHP_Incomplete_Class_Name] => Zend\Stdlib\ArrayObject
   )

How can resolve this i want to run both zf1 & zf2 application run on same session.
Here is directory structure for my project
project
--project/zf1_project
--project/zf2_project

Some times i manually create session in zf1 than run zf2, i have unable to get session as i want in zf2.
Any way by which i can use same login/Auth for both zf1 & zf2 application
Thanks in Advance...

A: ZF use object for store session. When start session, php try unserialize $_SESSION variable and if not found object's class PHP create __PHP_Incomplete_Class Object.
You should start session after classes autoload
Set session.auto_start=0 for fix it.


Q: Proof Check: Elementary LA Vector Space Question From Friedberg....
" Let $V=\{(a_1 ,a_2):a_1 ,a_2\in\mathbb F\}$, where $\mathbb F$ is a field.  Define addition of elements of $V$ coordinatewise, and for $c \in \mathbb F$ and $(a_1 , a_2) \in V$, define
$$c(a_1 , a_2)=(a_1, 0).$$
Is $V$ a vector space over $\mathbb F$ with these operations?  Justify your answer. "

My solution:
"" No, $V$ is not a vector space.  Note that...
$$c(a_1 , a_2)=(ca_1, ca_2)=(a_1 ,0)$$
... implies...

$ca_1=a_1$ and $ca_2=0$
It follows that $c=1$ and $c=0$. ""

Where do I go from here?  It seems that anywhere  else it would've been enough to prove $c=1$ and $c=0$ (which is a contradiction), but my instinct tells me Linear Algebra requires more than this.   Should I let $c=1$ and show that $1 \cdot a_2=a_2 \neq0$ or should I let $c=0$ and show that $0 \cdot a_1=0 \neq a_1?$  Neither?  Both?  I'm completely baffled.  Any help would be greatly appreciated!

A: By stating that $c(a_1, a_2) = (ca_1,ca_2)$, you've made the assumption that scalar multiplication on the set $V$ has been defined in that way, but it hasn't! It's been defined exactly as stated in the question:
For all $c\in \mathbb{F}$ and $(a_1, a_2) \in V$, we define the scalar multiplication operation $\cdot$ by $$c\cdot(a_1,a_2) = (a_1,0).$$ We also define an addition $+$ by $$(a_1,a_2) + (b_1,b_2):=(a_1+a_2,b_1+b_2).$$
Holding that firmly in mind, you have to verify that the vector space axioms are satisfied by the vector space $V$ with the operations $+$ and $\cdot$. It's important to remember that the set $V$ by itself is not a vector space (over the field $\mathbb{F}$), and that the only thing that makes it a vector space is the structure you endow on it by defining the operations $+$ and $\cdot$. Once the problem defines $\cdot$ in a certain way, you forget everything you know about "traditional" scalar multiplication and work directly with the definition given. By introducing componentwise scalar multiplication into your proof in the way you have, you're saying that the operation defined ought to be equivalent to componentwise scalar multiplication, which isn't necessarily the case.
In this case, note that one of the axioms that needs to be satisfied in order for $(V, +, \cdot)$ to be a vector space is that for all $(a_1, a_2)\in V$, if $1\in\mathbb{F}$ is the multiplicative identity in $\mathbb{F}$, we should have: $$1\cdot(a_1,a_2) = (a_1,a_2).$$
In this case, you are actually correct that the multiplicative identity axiom does not hold. By definition, we have $$1\cdot(a_1, a_2) = (a_1, 0),$$ which does not equal $(a_1,a_2)$ unless $a_2 = 0$. A counterexample would be $1\cdot(1,1)=(1,0)\neq(1,1)$. This is enough to say that $(V,+,\cdot)$ is not a vector space, but you should also verify that distributivity over scalar addition does not hold either.

A: $V$ is not a vector space over F with the given operations.  Note that...
$$c(a_1, a_2)=(ca_1,ca_2)$$
                                                                                $=(a_1,0)$
...only holds when $c=1$ and $a_2=0$.  Letting $c=1$, this violates the scalar identity as $1 \cdot (a_1,a_2)\neq(a_1,a_2)$ for all $(a_1,a_2)\in V$.


Q: Chrome notifications API img I'm trying to fire a chrome notification ( in a chrome extension ) with the following code:
 var opt = {
       type: "basic",
       title: "Deploy",
       message: "It worked!",
       iconUrl: "test.png"
    };
    chrome.notifications.create("", opt, function(id) {
       //console.error(chrome.runtime.lastError);
    });

But it shows me the following message :
"Unchecked runtime.lastError while running notifications.create: Unable to successfully use the provided image. "
My image "test.png" is in the root folder of my app( with the manifest.json file ), but I've tried to put the picture also in other folder of my app, it never worked!
I've correctly added the permission for notifications, so I really don't know where the problem is !
Any ideas ?
Thank you,
EDIT: I found the solution ! The image needed to be 80*80 !


Q: Redis NOAUTH authentication required error kubernatives We are getting error NOAUTH Authentication required when deploying in kubernatives cluster.
we need to remove the password which has set automatically. but we don't know from where to change as no config file is there.


Q: Auxillary circle and power of point
In $\triangle ABC$, the points $D$ and $E$ are located on $\overline{BC}$ such that $\angle BAD \cong \angle CAE$. Prove that
  $$\frac{AB^2}{AC^2}=\frac{BD\cdot BE}{CD\cdot CE}$$

Since the condition to prove looks a bit like the power of a point theorem, I tried constructing the circumcircle of $\triangle ADE$. The condition is easy to prove assuming that $\overline{AB}$ and $\overline{AC}$ are tangents to the circumcircle, but how do I prove that they are tangents? Since I haven't yet used the fact that $\angle BAD$ and $\angle CAE$ are equal, can it be proven using that condition?

A: This is a straight forward application of the generalized angle bisector theorem. I am not sure how you can have AB and AC tangential to the circum-circle of triangle ADE unless you have angle BAC = 180 degrees which means ABC is not a triangle. Here is a sketch of the proof of your original proposition.

*

*Apply the generalized angle bisector theorem to triangle ABC with point D on BC ignoring point E. Then you get:
$\frac{BD}{DC} = \frac{AB\  sin(BAD)}{AC\  sin(DAC)}$

*Apply the theorem again to triangle ABC with point E on BC ignoring point D. Then you get: $\frac{CE}{BE} = \frac{AC\  sin(CAE)}{AB\  sin(BAE)}$

*Since angle BAD = angle CAE and angle BAE = angle DAC, we can equate 1 & 2 and rearrange terms to yield the required result.

A: Via the area method: we have
$$
   \frac{BD}{CE} = \frac{[BAD]}{[CAE]} = \frac{AB \cdot AD}{AC \cdot AE}
$$
where $[XYZ]$ denotes the area of $\triangle XYZ$. The first equation holds since $\triangle BAD$ and $\triangle CAE$ have the same height from vertex $A$, the second holds since they have the same angle at vertex $A$. More explicitly, if $H$ is the foot of the perpendicular from $A$,
$$
   \frac{BD}{CE} = \frac{\frac12 \cdot BD \cdot AH}{\frac12 \cdot CE \cdot AH} = \frac{[BAD]}{[CAE]} = \frac{\frac12 \cdot AB \cdot AD \cdot \sin \angle BAD}{\frac12 \cdot AC \cdot AE \cdot \sin \angle CAE} = \frac{AB \cdot AD}{AC \cdot AE}.
$$
For the exact same reason, we have
$$
   \frac{BE}{CD} = \frac{[BAE]}{[CAD]} = \frac{AB \cdot AE}{AC \cdot AD}.
$$
Multiply these together, and you get
$$
   \frac{BD}{CE} \cdot \frac{BE}{CD} = \frac{AB^2}{AC^2}.
$$

A:
The condition is easy to prove assuming that $\overline{AB}$ and $\overline{AC}$ are tangents to the circumcircle

Point $A$ lies on the circle, so it is not possible that both $AB$ and $AC$ be tangents.
Alt. hint:   let $\angle BAD = \theta$ then applying the law of sines a few times:
$$
\begin{align}
\frac{BD}{\sin (\theta)} &= \frac{AB}{\sin(C+A-\theta)} \tag{1}\\[5px]
\frac{BE}{\sin (A-\theta)} &= \frac{AB}{\sin(C+\theta)} \tag{2} \\[5px]
\frac{CE}{\sin (\theta)} &= \frac{AC}{\sin(B+A-\theta)} \tag{3} \\[5px]
\frac{CD}{\sin (A-\theta)} &= \frac{AC}{\sin(B+\theta)} \tag{4} \\[5px]
\end{align}
$$
It then follows by calculating $\,\frac{(1)\,\cdot\,(2)}{(3)\,\cdot\,(4)}\,$ that:
$$\require{cancel}
\frac{BD\cdot BE}{CD\cdot CE} = \frac{AB^2}{AC^2}\cdot \frac{\bcancel{\sin(B+A-\theta)} \cdot \cancel{\sin(B+\theta)}}{\cancel{\sin(C+A-\theta)} \cdot \bcancel{\sin(C+\theta)}}
$$


Q: TestNG - can't get @Factory to work Trying to learn how to use @Factory, but when I execute it in one of two ways, i get either an error or no tests get executed at all.  I am invoking the XML file in Eclipse, by right-clicking on it, and selecting "Run As TestNG Suite".
With this XML file, the suite executes, but zero tests are picked up/executed:
<suite name="suite1" verbose="5">
    <test name="test1">
        <classes>
            <class name="qa.tests.MyFactory"/>
        </classes>
    </test>
</suite>

With this XML file, i get a test failure with an exception:
<suite name="suite1" verbose="5">
    <test name="test1">
        <packages>
            <package name="qa.tests" />
        </packages>
    </test>
</suite>

Error:
Can't invoke public void qa.tests.MyTest.testSample1(): either make it static or add a no-args constructor to your class

MyFactory.java class:
package qa.tests;
import org.testng.annotations.Factory;

public class MyFactory {
    @Factory
    public Object[][] dp() {
        Object[][] data = new Object[][] {
            { "1", "TestCase1", "Sample test 1" },
            { "2", "TestCase2", "Sample test 2" },
            { "3", "TestCase3", "Sample test 3" }
        };
        return data;
    }
}

MyTest.java class:
package qa.tests;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class MyTest {
    private String num;
    private String name;
    private String desc;

     public MyTest(String num, String name, String desc) {
         this.num = num;
         this.name = name;
         this.desc = desc;
     }

     @Test()
     public void testSample1() {
         System.out.println(num + ", " + name + ", " + desc);
         assertTrue( true );
     }
}

What in the world am I doing incorrectly?

A: First of all ,a Factory should return a one dimension Object array.
And that factory method should return instances of the test class that you are trying to execute.
So the factory will run your tests, if you change to this
public class MyFactory {
    @Factory
    public Object[] dp() {
        Object[] data = new Object[] {
            new MyTest("1", "TestCase1", "Sample test 1"), new Mytest("1", "TestCase1", "Sample test 1"), new MyTest("1", "TestCase1", "Sample test 1")
        };
        return data;
    }
}

A: As per this error : either make it static or add a no-args constructor to your class,
Your MyTest class need to have public no-args contructor, Java will not add the default constructor as you already have parametrized constructor, i.e  public MyTest(String num, String name, String desc)
UPDATE
change your factory class
public class MyFactory {

@DataProvider(name = "MyData")
public static Object[][] dp(ITestContext context, Method m) throws Exception {

    return new Object[][] { new Object[] { "1", "TestCase1", "Sample test 1" }};
}

@Factory(dataProvider = "MyData")
public Object[] createInstances(String num, String name, String desc) {
    return new Object[] { new MyTest(num, name, desc) };
}
}

A: //Factory class supplying data to test
public class DataFactory {

    @Factory
    public Object[] DataSupplier(){

        Object[] testData = new Object[3];
        testData[0] = new FactoryTest(1);
        testData[1] = new FactoryTest(2);
        testData[2] = new FactoryTest(3);
        return testData;
    }

}

//Test class
public class FactoryTest {

    int i;

    public FactoryTest(int i) {
        this.i = i;
    }

    @Test
    public void f() {
        System.out.println(i);
    }

}

Testng.xml

<suite name="Suite">
  <test name="Test">
    <classes>
      <class name="factorydata.DataFactory"/>
    </classes>
  </test> <!-- Test -->
</suite>

Datafactory class supplies the test data by creating instances of the test class and passing parameters to FactoryTest class constructor.
FactoryTest class consumes the data from the datafactory.
In the testng.xml refer the class which has factory , in this case it is DataFactory.
This explains a simple working TestNg Factory annotation usage.


Q: Cypress: Using cy.intercept() to check if a call hasnt been made yet? Using cy.intercept() to intercept (and stub) a couple of network requests (to google tag manager), but would like to test at an early point in my test before I expect them to be called.
How would I test that the 2 routes I'm intercepting haven't been called yet?
Thanks!

A: You could take advantage of the cy.spy command:
cy.intercept('/my-route', cy.spy().as('myRequest'));

// later in the test

cy.get('@myRequest').should('not.have.been.called'); // not yet intercepted

// something triggers the API call

cy.get('@myRequest').should('have.been.calledOnce'); // now is intercepted

See: https://docs.cypress.io/api/commands/spy
Credits to: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the-network-call-has-not-been-made

A: Intercept has a routeHandler section which can be a function

cy.intercept(routeMatcher, routeHandler?)
routeHandler (string | object | Function | StaticResponse)

The function receives the request, and inside that another function can receive the response,
see Intercepting a response
cy.intercept('/integrations', (req) => {
  // req.continue() with a callback will send the request to the destination server
  req.continue((res) => {
    // 'res' represents the real destination response
    // you can manipulate 'res' before it's sent to the browser
  })
})

so either on the receipt of req or the inner function on receipt of res, set an external flag and test it at one or more places in the test,
// top of the test

let interceptFlag = false;

cy.intercept('/my-route', (req) => {
  interceptFlag = true;
  req.continue((res) => {
    // or here
    interceptFlag = true;
  })
})

// later in the test

cy.wrap(interceptFlag).should('eq', false);   // not yet intercepted

// something triggers the API call

cy.wrap(interceptFlag).should('eq', true);    // now is intercepted

This is very generalized, if you post some details can be more specific.


Q: How to use google calendar API for personnel project (Without verification) I'am using google calendar API on my personal project for creating events through python.But the problem is its asking to verify app by giving privacy policy details (Otherwise the token would expire after 7 days),which i think is overkill for a personnel project .Here iam using my own account and accessing my own data.So  is there any way that i can use google calendar API without verification,like for my own account.Or is it not possible to do so without verification.Or is there any other libraries to do the same thing,I just need to set events on my calendar Programmatically.Please help me!

A: What you want to do is create a "service account". Then you want create a new calendar for your (not the service account) calendar. Next, you share your new calendar with the service account by adding it under the "Share with specific people" section. Take note of the "Calendar ID" for this new calendar.
Now when you use the api you should add events from your service account to the new calendar by passing the calendar id as the calendarId.


Q: While loop condition in calculating square root using Newton-Raphson method I'm currently taking a course where the instructor used the following code to implement the square root functionality in Java -
public class Sqrt {
    public static void main(String[] args) {

        // read in the command-line argument
        double c = Double.parseDouble(args[0]);
        double epsilon = 1.0e-15;  // relative error tolerance
        double t = c;              // estimate of the square root of c

        // repeatedly apply Newton update step until desired precision is achieved
        while (Math.abs(t - c/t) > epsilon*t) {
            t = (c/t + t) / 2.0;
        }

        // print out the estimate of the square root of c
        System.out.println(t);
    }

}

However, if I slightly change the while loop condition to while (Math.abs(t - (c / t)) >= epsilon) instead of while (Math.abs(t - (c / t)) >= t * epsilon), the program gets stuck on an infinite loop for some inputs like 234.0.
I used the Eclipse debugger and found that my code after a certain point returns a value of t that is close to the square root of 234, but still greater than EPSILON. And using the update formula, yields the same value of t after every iteration, hence the loop gets stuck there forever.
Can someone explain as to why the program fails when using >= EPSILON but works perfectly fine when using >= t * EPSILON? As per my understanding, given the extremely small value of EPSILON, t * EPSILON shouldn't eventually be too different than EPSILON, yet the difference is huge when implemented in the program.

A: You can actually use a debugger to see how the numbers progress and why for example the square root of 234 causes an unending loop when epsilon is not multiplied by t.
I have used IntelliJ with a logging breakpoint to see how the numbers progress and why the unending loop happens:

First I have used this expression in the logging breakpoint:
" " + Math.abs(t - c/t) + " " + epsilon

for this code:
private static void calcRoot(String arg) {
    // read in the command-line argument
    double c = Double.parseDouble(arg);
    double epsilon = 1.0e-15;  // relative error tolerance
    double t = c;              // estimate of the square root of c

    // repeatedly apply Newton update step until desired precision is achieved
    while (Math.abs(t - c/t) > epsilon ) {
        t = (c/t + t) / 2.0;
    }

    // print out the estimate of the square root of c
    System.out.println(t);
}

and this is the result proving that actually epsilon is smaller than Math.abs(t - c/t) and this Math.abs(t - c/t) stops in its progression:
 233.0 1.0E-15
 115.50851063829788 1.0E-15
 55.82914775415816 1.0E-15
 24.47988606961853 1.0E-15
 7.647106514310517 1.0E-15
 0.927185521197492 1.0E-15
 0.014043197832668497 1.0E-15
 3.2230278765865705E-6 1.0E-15
 1.723066134218243E-13 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 1.7763568394002505E-15 1.0E-15
 ...

If I then use epsilon * t I and update the logging expression to " " + Math.abs(t - c/t) + " " + epsilon * t I can see a totally different console output:
 233.0 2.34E-13
 115.50851063829788 1.175E-13
 55.82914775415816 5.974574468085106E-14
 24.47988606961853 3.1831170803771985E-14
 7.647106514310517 1.959122776896272E-14
 0.927185521197492 1.5767674511807463E-14
 0.014043197832668497 1.5304081751208715E-14
 3.2230278765865705E-6 1.529706015229238E-14
 1.723066134218243E-13 1.5297058540778443E-14

Update
If you try the same thing with the BigDecimal class, you will be able to calculate the square root of 234 in case you choose enough rounding digits (see the scale variable below):
private static void calcRootBig(String arg) {
    // read in the command-line argument
    BigDecimal c = new BigDecimal(arg);
    BigDecimal epsilon = new BigDecimal(1.0e-15);  // relative error tolerance
    BigDecimal t = new BigDecimal(c.toString());              // estimate of the square root of c
    BigDecimal two = new BigDecimal("2.0");

    // repeatedly apply Newton update step until desired precision is achieved
    int scale = 10;
    while (t.subtract(c.divide(t, scale, RoundingMode.CEILING)).abs().compareTo(epsilon) > 0) {
        t = c.divide(t, scale, RoundingMode.CEILING).add(t).divide(two, scale, RoundingMode.CEILING);
    }

    // print out the estimate of the square root of c
    System.out.println(t);
}

Yet if you choose just 3 for the rounding scale, you will be caught up again in an unending loop.
So it seems that it is the precision of the floating point division which is actually causing the unending loop in your case. The multiplication of epsilon * t is just a trick to overcome the lack of rounding precision in the default floating point operations.

A: double has around 15 digits of precision (or 1 to 2^52 or 4.5e15). When you calculate t * epsilon you around requiring an error of 1 to 1e15/234 ratio which is possible with double, when you use epsilon you are requiring a ratio of 1 to 1e15 which is at the limits of the precision of double unless it's an exact value and the error is 0. e.g. try this for 256 and it might work, but anything which is not an exactly value probably doesn't.
A simple solution to an arbitrary end point is to stop once the error doesn't improve from one iteration to the next. This is will give you the most accurate solution using this formula possible.


Q: Disable a button inside ion-nav-buttons How can I disable a button inside ion-nav-buttons depending on an action in the ion-content?

example: if I click in a button inside ion-content the button inside
  ion-nav-buttons get disabled.

As I see, I can´t controll the elements inside ion-nav-buttons from the controller of the template that has the ion-nav-buttons.

A: This can be done with ng-disabled in button
Check this Try ng-disabled
<ion-view>
    <ion-nav-buttons side="primary">
      <button class="button" ng-disabled="disabled" ng-click="doSomething()">
        I'm a button on the primary of the navbar!
      </button>
    </ion-nav-buttons>
    <ion-content>
      <button class="button" ng-click="disable()">
        Click to disable
      </button>
    </ion-content>
</ion-view>

//Angular code
$scope.disable=function(){

  $scope.disabled=true;

}


Q: Можно ли динамически определить, как был создан объект - на куче или в стеке? Например проверять объект при очищении контейнера:
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    vector<string*> vec;
    vec.push_back(new string{"ptr1"});
    vec.push_back(new string{"ptr2"});
    string str1{"nonptr1"};
    string str2{"nonptr2"};
    vec.push_back(&str1);
    vec.push_back(&str2);

    for(auto* s : vec) {
        cout << *s << endl;
        delete s; //На третьем элементе очевидно всё повалится
    }

    return 0;
}

Есть ли стандартные механизмы определения, каким способом создан объект?

A: Тут сам подход неверный, если у вас есть пачка указателей на объекты, память для которых была выделена разными способами, то надо хранить и пачку соответствующих функций для их деаллокации. Проверка, лежит объект в куче или на стеке в данном случае никак не поможет; например у вас есть динамический аллокатор использующий буфер на стеке в качестве хранилища вместо кучи.

A: Определить , что адрес в стеке можно с помощью проверки адреса:
bool  isInStack(void * x) {
  volatile  bool  stacktop  ;
  return  x > ( & stacktop ) ;
}

Но проблема с другими адресами: глобальных переменных. У них адреса не в стеке , а в куче. И определить, что нужно удалять или нельзя придётся вручную, задавая вектор структуры с флагом , что нужно удалить. Данный способ определять место информации , что оно стеке очень ИНДИВИДУАЛЬНЫЙ. Это называется ХАКИНГ. Где-то работает, а где-то нет.
Например, в многопотоковой программе у каждого потока свой стек и если проверять указатель у переменной другого потока, то один поток скажет это в его стеке, другой - нет.

A: Можно написать такого рода обёртку, где будет динамически во время исполнения определяться, как был создан объект (на стеке или в куче), с помощью виртуального полиморфизма.
#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::unique_ptr;

class PtrDeallocationWrapper {
public:
    virtual ~PtrDeallocationWrapper() {}
};

template <class T>
class PtrDeallocationWrapperOnHeap
        : public PtrDeallocationWrapper
{
public:
    template <class... Args>
    PtrDeallocationWrapperOnHeap(Args&&... args)
        : ptr_(new T(std::forward<Args>(args)...))
    {}
    virtual ~PtrDeallocationWrapperOnHeap() {
        cout << "heap deallocation" << endl;
    }

private:
    unique_ptr<T> ptr_;
};

template <class T>
class PtrDeallocationWrapperOnStack
        : public PtrDeallocationWrapper
{
public:
    PtrDeallocationWrapperOnStack(T * ptr) : ptr_(ptr) {}
    virtual ~PtrDeallocationWrapperOnStack() {
        cout << "stack not deallocation" << endl;
    }

private:
    T * ptr_;
};

template <class T, class... Args>
auto make_heap_ptr(Args&&... args)
    -> unique_ptr<PtrDeallocationWrapper>
{
    return std::move(unique_ptr<PtrDeallocationWrapper>(
                         new PtrDeallocationWrapperOnHeap<T>
                            (std::forward<Args>(args)...))
                     );
}

template <class T>
auto make_stack_ptr(T* ptr)
    -> unique_ptr<PtrDeallocationWrapper>
{
    return std::move(unique_ptr<PtrDeallocationWrapper>(
                         new PtrDeallocationWrapperOnStack<T>(ptr))
                     );
}

int main() {
    vector<unique_ptr<PtrDeallocationWrapper> > vec;

    vec.push_back(make_heap_ptr<string>("lol"));
    string str1 = "kek";
    vec.push_back(make_stack_ptr<string>(&str1));

    vec.pop_back();
    vec.pop_back();

    return 0;
}

A: Например так, если конечно Вы имеете доступ к коду:

#define onHeap 0b11111111

struct A
{
    unsigned char placement;

    void *operator new(size_t size)
    {

        void* ptr = malloc(size);
        static_cast<A*>(ptr)->placement = onHeap;

        return ptr;
    }
};

Проверяем, где находится объект, так:
instance_of_A.placement == onHeap;

Для объектов класса A, если он в хипе, область памяти под placement будет заполнена единицами. Если где-то ещё - скорее всего какой-нибудь мусор. Но конечно нужно помнить, что может возникнуть случайность, когда на стеке под placement будут одни единичные биты.
Только не нужно путать. До конструирования объекта класса, его там нет, по сути. Просто мы заранее в нужное место записываем определенное значение, а при конструировании нужно сделать так, чтобы его не переписать, т.е. важно написать конструктор класса так, чтобы он не перезаписал область памяти под placement.


Q: Table without a identity column but this column can't have repeated values I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005

A: Make the first column the primary key of the table.

A: Set the column as a primary key. I doesn't have to be an identity column to has a PK.

A: Create it the same way you would any other column: create table sometable (column1 varchar(10), column2 varchar(20)) or whatever.
Do you mean: How can you get the database to force it to be unique? Either declare it to be the primary key, or create a unique index on the column.
Perhaps you're thinking that a primary key must be auto-generated? There's no such rule. Whether you invent the value yourself or use an autonumber feature has nothing to do with whether a field can be a primary key.

A: Why not just put a unique constraint on it:
ALTER TABLE <table_name>
 ADD CONSTRAINT <constraint_name>
 UNIQUE(<column_name>)


Q: How to make a particular record stay at the end of sql server database I am making a dialog based application in MFC, where in there is a need to read the database and display the contents from database, i managed to find the record and display it in a list box by comparing unique Id from edit box and database, but the problem is I cannot display the last record for some reason it's not happening, I am successfully able to display from 1 to n-1 so I decided to put nth record as dummy so I just need a method in which I can make that dummy record to always stay at the last or end of the database,
Thank you
{
int flag = 0;
    CString ID;
    CDatabase database;
    CString sqlString=L"SELECT *FROM FM_REGISTER";
    wchar_t connstring[500] = L"Driver={SQL SERVER};Server=FCS-LOKANATH\\SQLEXPRESS;DataBase=FM;Integrated Security=True";
    database.Open(NULL, 0, 0, connstring);
    m_InfoID.GetWindowText(ID);
    m_InfoList.ResetContent();//this is a report command
        CRecordset recordset(&database);
        CString temp, record,temp2;
        recordset.Open(CRecordset::forwardOnly, sqlString, CRecordset::readOnly);
        while (!recordset.IsEOF()){//is null
            record = _T("");
            register int len = recordset.GetODBCFieldCount();
            for (register int i = 0; i < 2; i++)
            {
                recordset.GetFieldValue(i, temp);
                if (i == 0 & ID.CompareNoCase(temp) == -1)
                {
                    //MessageBox(L"Positive Macth");
                    flag = 1;
                }
                else
                {
                    //MessageBox(L"Nagative Macth");
                    flag = 0;
                }
                record += temp + _T("|");
            }
            m_InfoList.AddString(record);
            recordset.MoveNext();
        }
    MessageBox(_T("Query done."), 0, 0);
    // TODO: Add your control notification handler code here
}

A: OK, re-read and this didn't answer what you asked.
Post your code, we need to see how you are iterating the results.  The answer below is about ordering and not a missing record.
You can do this with an order by on your query.
SELECT id, description, order FROM mytable ORDER BY order ASC
This will cause the query to be retrieved ordered by the order column, and you just need to make sure that the order in the database is largest for the record you want to appear last.


Q: Visible lines but no idea where in the html or css I've a small problem by creating my website. Some div or text element show some lines by moving the mouse over it.
they get invisible by clicking somewhere else. But I haven't define a border.
I do not know how to continue, may someone has a idea what that could be?
My website use bootstrap 4.0
example Picture

A: Did you try
text-decoration: none;

It is hard to guess the problem from your description.
You can also try inspecting that perticular div. Right click that div and select inspect element. There the browser will show you the css applied to that div or text.


Q: How to get database off of localhost and running permanently? So not sure it this is stupid to ask, but I'm running a neo4j database server (using Apollo server) from my React Application. Currently, I run it using node in a separate terminal (and I can navigate to it on localhost), then run npm start in a different terminal to get my application going. How can I get the database just up and running always, so if customers use the product they can always access the database? Or, if this isn't good practice, how can I establish the database connection while I run my client code?
Technologies being used: ReactJS, Neo4j Database, GraphQL + urql
I tried moving the Apollo server code into the App.tsx file of my application to run it from there directly when my app is launched, but this was giving me errors. I'm not sure if this is the proper way to do it, as I think it should be abstracted out of the client code?

A: If you want to run your server in the cloud so that customers can access your React application you need two things:

*

*one server/service to run your database, e.g. Neo4j AuraDB (Free/Pro) or other Cloud Marketplaces https://neo4j.com/docs/operations-manual/current/cloud-deployments/

*A service to run your react application, e.g. netlify, vercel or one of the cloud providers (GCP, AWS, Azure) that you then have to configure with the server URL + credentials of your Neo4j server
You can run neo4j-admin dump --to database.dump on your local instance to create a copy of your database content and upload it to the cloud service. For 5.x the syntax is different, I think neo4j-admin database dump --path folder.


Q: Orthogonal set of complex functions Show that the functions $e^{in\pi x/l}$, n = 0, ±1, ±2, ..., are a set of orthogonal functions on $(-l, l)$
using:
$A(x)$ and $B(x)$ are orthogonal on $(a,b)$ if
$\int^b_a A^*(x)B(x)dx = 0$
where $A^*(x)$ is the complex conjugate of $A(x)$.
I'm assuming you rewrite the function as:
$\cos(n\pi x/l) + i\sin(n\pi x/l)$,
so the complex conjugate would be
$\cos(n\pi x/l) - i\sin(n\pi x/l)$
This would make the integral
$\int^l_{-l} \cos(n\pi x/l) - i\sin(n\pi x/l)(\cos(n\pi x/l) + i\sin(n\pi x/l))dx = 0$
I think that this is correct so far and that I'm pretty close, just struggling with this integral and how it proves the claim. Any guidance would be greatly appreciated, Thanks!

A: In the definition of orthogonality functions $A$  and $B$ must be different; for the system $\left \lbrace  e^{\frac{in\pi x}{l}} \right\rbrace_{n\in\mathbb{Z}}$ write
$$\int\limits_{-l}^{l}{A_{n}^{*}(x)B_{k}(x)\ dx}=\int\limits_{-l}^{l}e^{\frac{ik\pi x}{l}}e^{-\frac{in\pi x}{l}}\ dx, \;\;k \ne n$$
and then integrate:
$$\int\limits_{-l}^{l}e^{\frac{ik\pi x}{l}}e^{-\frac{in\pi x}{l}}\ dx=\int\limits_{-l}^{l}e^{\frac{i(k-n)\pi x}{l}}\ dx.$$


Q: How can I display the values from my DB (phpmyadmin) into a drop-down-box in unity? I am new in codding and I couldn't find any solution to solve my issue.
I just need to see the data from the database in my drop-down-box in Unity.
Please give me advices step by step.

A: I managed for now to connect to the DB.
    <?php

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "database";

    // create conntection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // check connection
     if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
     }
     $sql = "SELECT item_name FROM items";
     $result = $conn->query($sql);
     if ($result->num_rows > 0) {
         // output data of each row
             while($row = $result->fetch_assoc()) {
             echo "-".$row["item_name"]. "<br>";
         }
     }
    $conn->close();
?>


Q: How to validate or wrap user inputted HTML to fix unclosed tags I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?

A: You may try jquery-clean
$.htmlClean($myContent);

A:
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?

Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:
var div = $("
");
div.html($("#the-textarea").val());
var html = div.html();

Live example — type an unclosed tag in and click the button:

$("input[type=button]").on("click", function() {
    var div = $("
");
    div.html($("#the-textarea").val());
    var html = div.html();
    $(document.body).append("
You wrote:

" + html + "
End of what you wrote.");
});

Type something unclosed here:

<textarea id="the-textarea" rows="5" cols="40"></textarea>

<input type="button" value="Click when ready">

Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.
Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.

A: You could try and use : http://ejohn.org/blog/pure-javascript-html-parser/ .
But if the user is entering the html by hand you could just check to have all tags closed properly. If not, just display an error message to the user.

A: You can create a jQuery element using the text and then get it's html, like so
Sample
<textarea>

            some content
            some content

</textarea>

Script
alert($($('textarea').text()).html());

alert($($('textarea').text()).html());

<textarea>

      some content
      some content

      </textarea>

A: The simple way to check if entered HTML is actually valid and parseable by browser is to let browser try it out itself using DOMParser. Then you could check if result is ok or not:

function checkHTML(html) {
    var dom = new DOMParser().parseFromString(html, "text/xml");
    return dom.documentElement.childNodes[0].nodeName !== 'parsererror';
}

$('button').click(function() {
    var html = $('textarea').val();
    var isValid = checkHTML(html);console.log(isValid)
    $('div').html(isValid ? html : 'HTML is not valid!');
});

<textarea cols="80" rows="7"><div>Some HTML</textarea> <button style="vertical-align:top">Check</button>