text:
Q: How to select link of current page I am trying to have my links in a menu styled when I mouse over them.
Then when the mouse leaves the link (without clicking on it) I want the current link to go back to being styled.
html:

TitleSubtitle

ABOUT

GALLERY

BIO

CONTACT

HOME

css
.current { color: #FFBB3F;}

js
$( "nav a" ).on('mouseover', function(){

    $( "nav a.current" ).removeClass("current");
        $(this).addClass("current");
    });

$( "nav a" ).on('mouseleave', function(){
    $(this).removeClass("current");
    var pageURL = $(location).attr("href");
    $('a[href="pageURL"]').addClass("current");

});

but this is not working. if I do an alert
 alert(pageURL);

it gives me the path to the current page, and if I paste just an href
$('a[href="index.html"]').addClass("current");

it does style that link, but obviously I would want the current link to be styled. First time I try this. Any help appreciated. Thanks

A: This will add and remove the current class as well as style links being hovered over:

var anchors = document.querySelectorAll("#menu a");

// Assign mouseover and mouseout event handlers to each anchor
for(var i = 0; i < anchors.length; i++){
  anchors[i].addEventListener("mouseover", styleIn);
  anchors[i].addEventListener("mouseout", styleOut);
}

// This will hold a reference to whichever anchor has the current class
var currentAnchor = null;

function determineCurrent(){
  for(var i = 0; i < anchors.length; i++){
    if(anchors[i].classList.contains("current")){
      currentAnchor = anchors[i];
    }
  }
}

function styleIn(e){
  determineCurrent();
  e.target.classList.add("hover");
  currentAnchor.classList.remove("current");
}

function styleOut(e){
  e.target.classList.remove("hover");
  currentAnchor.classList.add("current");
}
a { text-decoration:none; }
.current { color: #FFBB3F; }
.hover { text-decoration:underline;}

TitleSubtitle

ABOUT

GALLERY

BIO

CONTACT

HOME

A: Using just CSS, a combination of rules can get really close (perhaps close enough depending on how #menu is), see comments in CSS section:

/*
  1. Color the current one if the menu isn't being hovered
  2. Color the current link if being hovered
*/
#menu:not(:hover) .current, /* 1 */
#menu a:hover {             /* 2 */
  color: #FFBB3F;
}

TitleSubtitle

ABOUT

GALLERY

BIO

CONTACT

HOME

That CSS-only version has the issue that if you're not hovering a link but you are hovering the #menu, nothing is highlighted. I can't think of a pure CSS way to handle that, so a bit of JavaScript (see comments):

// Set a class on #menu only when hovering a link
$("#menu")
  .on("mouseenter", "a", function() {
    $("#menu").addClass("link-hover");
  })
  .on("mouseleave", "a", function() {
    $("#menu").removeClass("link-hover");
  });
/*
  1. Color the current one if the menu doesn't have the link-hover class
  2. Color the current link if being hovered
*/
#menu:not(.link-hover) .current, /* 1 */
#menu a:hover {                  /* 2 */
  color: #FFBB3F;
}

TitleSubtitle

ABOUT

GALLERY

BIO

CONTACT

HOME


text:
Q: In VB.NET, How to listen to the load event of any dropdown list in the application? I have several dropdown lists in different pages of the app.
I need to run some function when any dropdown is loaded in the WHOLE APP.
I am trying the below but not working:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    GetAllDropdowns(Me.Page)
End Sub

Private Sub GetAllDropdowns(ByVal Ctrl As Control)
    Dim dd As DropDownList = Nothing
    For Each c In Ctrl.Controls
        If TypeOf c Is DropDownList Then
            dd = DirectCast(c, DropDownList)
            AddHandler dd.Load, AddressOf doIt
        Else
            GetAllDropdowns(c)
        End If
    Next
End Sub

Private Sub doIt(ByVal sender As Object, ByVal e As EventArgs)
    'Do whatever....
End Sub

A: I think that the problem is the event you are using.
The Page_Load event runs after all of the load events of the controls so the sub doIT won't run.
Try moving your code in the Page_Init event which seems more appropriate for this task.
See here for more information about asp.net page life cycle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Very poor network performance between Windows 7 and Server 2008 R2 I've been banging my head against the wall on this problem for a few days, please help.
I just installed a new fileserver, (Windows Server 2008 R2), And replaced a few users laptops (Windows 7 Pro 32bit).
I am seeing incredibly slow response times between this server and the Windows 7 laptops. Only between these two types of systems though. The laptops can access file shares on Server 2003 boxes with no problems. Older Windows XP machines can access files on the Server 2008 R2 box with no problems.
Specifically, if a user tries to open a Excel file from the network share, it will open right away but Excel will be frozen and become nonresponsive for at least 30 seconds. It is not just Office files, pdfs, jpgs and other file types as well.
I ended up testing this out with others servers as well with the same results, always with Win 7 and Srv 08 R2. On the laptops, I have tried:
disabling "autotuning"
disabling IPv6
disabling Remote Differential Compression
reinstall network drivers
disable antivirus (network threat protection)
disable firewall
various other fixes found around the internet.
Ping is 1ms response time, transferring a file exhibits erratic transfer speeds, 22MB/s down to 130kb/s and back up and back down or it just locks up. Wired or wireless
On the server I have tried
disabling "autotuning"
disabling IPv6
disable antivirus (network threat protection)
This server is also the Domain Controller and DNS server as well as a file server. I know this really isn't the desired config, but this is for a branch office, I had no options.
Nothing in the event logs on the clients, and nothing relevant in the event logs on the server.
More details: when a user opens an Excel file for example; the file opens right away but Excel becomes unresponsive. During this time while it's frozen, the green progress bar starts again in the address bar of Windows Explorer. Once the progress bar is done loading then the file becomes available for editing.
About the only thing I haven't done is install Wireshark on the laptops and server and watch the traffic.
Any thoughts? What technologies are in Win 7 and Srv 08 R2 that is causing this type of network slowness?
As always, thanks to anyone who reads this and/or responds.
Lys

A: This has the fetid spoor of SMB2-related shenanigans I've seen before with a certain Symantec AV product. The fact that Win7 is affected but XP isn't, and the Win7 machines can talk to the Win2003 server just fine points a big finger at SMB2 somehow falling on its head. I saw that before about two years ago with Symantec Endpoint Security (since patched, IIRC) installed on the 2008 server. This suggests your AV or firewall product might possibly be getting in the way here


text:
Q: How to put a keylistener in this method So, I have this method (with nothing in it yet)
class Transmitter {
    public static void main(String[] args) {

    }
}

and I want to put a keylistener in it, to detect when the space key is pressed.
I've looked at tutorials online, and they are all to complicated for my needs; I just want a simple "Print something in the console" when the space key is pressed. Thanks!

A: As some others have commented, there is no concept of a key listener from a console application. If you just want to read input keys from the console, you can use System.in.read() within a loop: What is the use of System.in.read()?
Not sure if that's what you are looking for.


text:
Q: How to build react-native app for iOS properly? I developed a react native app (version 57.4) on windows for android and it works fine.
Now I'm trying to build for iOS with no luck (as I don't have any experience with Xcode).
What I tried so far:
I knew that it requires a Mac and Xcode so I downloaded a VM, install Xcode.

*

*Git clone myApp

*react-native run-ios
But I got a lot of errors and build failures so after some search, I make these more steps:

*

*react-native link

*link some fonts manually

*add a pod file and pod install

*make some Xcode changes which I can't remember

*react-native run-ios
And it works :)

BUT I had an issue with axios so I tried to fix it but I ruined the app so I removed the folder and re-cloned it again.
This time, I can't build successfully again!! and if it builds it crashes instantly!
My Question is what the exact steps do I need to make to build successfully on Mac (especially steps for Xcode)? including how to link all native dependencies correctly? and Is the pod file is necessary?


text:
Q: SpriteKit & Swift, how to calculate the time spend in update, didEvaluateActions, didSimulatePhysics, didApplyConstraints and didFinishUpdate? Im trying to find out how much time SpriteKit spends in update, didEvaluateActions, didSimulatePhysics, didApplyConstraints and didFinishUpdate. This would allow me to find whether its my physics, actions, constraints or graphics that are slowing my game down sometimes. Im facing a fps drop of a few frames every now and then and this would be a good way to go i think. But how can i do that? I created a timeInterval() variable but how would i start and stop it?
    override func didEvaluateActions() {
    let currentTime = TimeInterval() // How to start?

    print("didEvaluateActions: \(currentTime)")
}

Thank you in advance.


text:
Q: Refreshing specific parent resolve cache Is it possible to cache-bust/refresh specific resolves in the parent resolves? Or even disable ui-router resolve caching for specific items?
I have this setup where company is provided to 2 child states by an abstract parent state. controller.dashboard.company makes an update to this object but when the user navigates to dashboard.overview and comes back to dashboard.company, the old resolve's values are loaded. Only a hard-refresh of the page gets the new data from the API.
router.js
.state('dashboard', {
  abstract: true,
  resolve: {
    company: ['api.company', 'user', function ($company, user) {
        return $company.id(user.company);
    }]
  }
})
.state('dashboard.overview', {
  url: '/',
  templateUrl: 'dashboard/overview/overview.html',
  controller: 'controller.dashboard.overview',
  resolve: { ... more API calls ... }
})
.state('dashboard.company', {
  url: '/company',
  templateUrl: 'dashboard/company/company.html',
  controller: 'controller.dashboard.company',
  resolve: { ... more API calls ... }
})

I can call $state.reload(); but this refetches every resolve from the dashboard downwards, which is about 30 different states which shouldn't be refetched.
I'm caching the company object in-memory via a service (api.company) but since the resolve doesn't re-fire, the service cache is never queried again.
Any ideas?
Angular 1.6.8 / ui-router 1.0.14

A: try and add it to your transitions.Onstart function
 $transitions.onStart({},function ($transition) {
    console.log("\n %c From: " + $transition.$from() + " To: " +
    $transition.$to() + "\n\n");
      $transition.addResolves({ company: ['api.company', 'user', function
            $company, user) {
            return $company.id(user.company);
        }]
     });
   })

A: I ended up moving the "company" resolve into the immediate children states, letting my factory level cache to keep it hydrated. So, still no API calls were made but I was getting the latest company between route parent changes. This allows the company to be updated from the factory cache when moving between dashboard.overview.* and dashboard.company.* routes.


text:
Q: Dynamically generated tabItems Right now I'm using uiOutput with renderUI to show my content. But I wanna use Google Analytics, so I must work with tabItems for tracking pages of my app. But it doesn't work for me.
Simple example of my code:
UI <- dashboardPagePlus(
  header = dashboardHeaderPlus(...),
  sidebar = dashboardSidebar(
    ...,
    sidebarMenu(
      menuItemOutput(
        outputId = 'EventsMenu'
      ),
      ...
    ),
  body = dashboardBody(
    ...,
    uiOutput(
      outputID = 'EventsBody'
    ),
    ...
  )
)

Server <- function(
  input,
  output
) {
  output$EventsMenu <- renderMenu(
    {
      lapply(
        X = 1:10,
        FUN = function(
          ID
        ) {
          menuItem(
            text = 'Event',
            tabName = paste0(
              'Event',
              ID
            )
          )
        }
      )
    }
  )
  ...
  output$EventsBody <- renderUI(
    {
      if(
        stri_detect(
          str = 'Event'
        )
      ) {
        fluidPage(
          fluidRow(
            ...
          )
        )
      }
    }
  )
  ...
}

shinyApp(
 ui = UI,
 server = Server
)

How could I change my code for using tabItems?

A: Just deal it with shiny.router
So my menu item looks like:
menuItem(
    text = "Homepage",
    href = route_link(
        path = "Home"
    ),
    newtab = FALSE
)


text:
Q: perl regexp minimal match the word before underscore may i know how to write the regexp for this case?
$aword = abc_def_ghi regexp substitute to abc_def_xxx
$bword = jkl_mno_pqr regexp substitute to jkl_mno_xxx
$cword = abc_def     regexp substitute to abc_xxx

Zh

A: $aword = 'abc_def_ghi';
$aword =~ s/[^_]+$/xxx/;  # [^_]+$: to match non-underscore at the end of string.
print $aword  # => abc_def_xxx

A: s/^[a-z]+(?:_[a-z]+)*_\K[a-z]+\z/xxx/

In strings composed solely of two or more "words" of letters a through z, replace the last "word" with xxx.
You can read about regexes in perlre.
^ \z: zero width assertions
[]: character class
+ *: quantifiers
(?: ): extended pattern (clustering)
\K: special escape


text:
Q: How to increase the width of my template? I am thinking to increase the width of my template.
Website: laptopsisland.com
Here is the css code for site width.
/**************** MAIN WIDTH *********************/
.wrapper { padding: 0; min-width:960px }
.boxed-layout .wrapper  { width:1000px; background: #FFF; margin:0 auto; }
.inner { width:960px; position:relative; margin:0 auto; /* main width */ }
.responsive .inner { max-width:960px; width:auto; }
body.responsive.isMobile .wrapper { overflow:hidden; }
/*************************************************/

Please find complete css code here.
Can anyone teach me how to increase the width using above css code?

A: The width of your site is currently constrained by these specifications:
.boxed-layout .bg-shadow { max-width: 1023px; }
.boxed-layout .wrapper { width: 1000px; }

If you increase those, your site will get wider.


text:
Q: React.js library not working on CodePen? I'm having a very simple issue with using React.js on CodePen! I'm new to React, and I'm trying to use the React library on CodePen. It just doesn't appear to be working for some reason, even though I'm also using Babel as the pre-processor.
I feel like this may have something to do with the version I'm using? - 15.3.1
http://codepen.io/anfperez/pen/aBomwp
My code:
var React = require('react');
var ReactDOM = require('react-dom');

var Test = React.CreateClass({
  render: function() {
    return (
    <h2> Yo </h2>
    );
  }
});

ReactDOM.render(<Test />, getElementById("test"));

Any tips are appreciated.

A: The problem is RequireJS is not needed for your example.  Please try: http://codepen.io/anon/pen/JbPWeO
var Test = React.createClass({
    render: function() {
        return (
            <h2> Yo </h2>
        );
    }
});

ReactDOM.render(<Test />, document.getElementById("test"));

A: You should add these external scripts in your javascript pen settings :
https://unpkg.com/react/umd/react.development.js
and
https://unpkg.com/react-dom/umd/react-dom.development.js

A: Here are some suggestions:

*

*You should also need to include ReactDOM as you only included React in Codepen.

*Line 4 should be React.createClass (createClass should be in Camel
case).

*Line 12 should be document.getElementById instead of
getElementById

A: Add react-js first and then add react-dom js, the order matters in code pen or it will show error


text:
Q: Local reference to inner array in swift I came from C# world, and used to arrays being reference types. As I understand, in swift arrays are value types, but they try to play as reference ones.
I don't actually know how to ask what I need (I think this is the case when I need to know answer to be able to ask question), but in C# I would say I need to store a reference to inner array of a jagged array into local variable.
Consider the following piece of code:
// a function to change row values in-place
func processRow(inout row : [Int], _ value : Int)
{
    for col in 0..<row.count
    {
        row[col] = value;
    }
}

// a function to change matrix values in-place
func processMatrix(inout matrix : [[Int]])
{
    for rowIdx in 0..<matrix.count
    {
        // (1) Works with array in-place
        processRow(&(matrix[rowIdx]), -1)

        // (2) Creates local copy
        var r = matrix[rowIdx]; // <--- What to write here to not make a copy but still have this local variable?
        processRow(&r, -2);
    }
}

var matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

processMatrix(&matrix)

print(matrix) // outputs [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]

Swift sandbox here http://swiftlang.ng.bluemix.net/#/repl/8608824e18317e19b32113e1aa08deeb4ec5ab96ed8cdbe1dbfb4e753e87d528
Here I want to I process multidimensional array in-place, so that I don't create a copy of array or parts of array.
In option (1) I change everything to "-1", and it works, but is uses additional function for this.
In option (2) I try to use local variable to store matrix[rowIdx], but it actually creates a copy of inner array - not what I want; working with this variable changes copy of array, and not original one.
How can I achieve results like in option (1), but using local variable instead of function? That is, how can I obtain reference to inner array and put it to local variable?
I would understand answer "there's no way for this", but I want such answers to be accompanied by some Apple refs.

A: I don't believe that there is a way to copy an array into a local variable without making a copy. That is just the way that value types work in Swift. Says Apple:

The most basic distinguishing feature of a value type is that copying — the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data[.]

And here:

A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function...
[...]
All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create—and any value types they have as properties—are always copied when they are passed around in your code.

It's just part of the definition of value type - and every array is a value type.
The easiest way to get the result you are seeking is simply to reassign the value of r to the row that you want to change in matrix:
// (2) Creates local copy
var r = matrix[rowIdx]
processRow(&r, -2)
matrix[rowIdx] = r

The closest thing to what you are suggesting is to work with pointers: UnsafeMutablePointer, UnsafePointer, etc. But that is really fighting against the way that Swift was designed to be used. If you wanted to, however, it would look something like this:
func processRow(ptr: UnsafeMutablePointer<Int>, _ value : Int, count: Int) {
    for col in 0..<count {
        ptr.advancedBy(col).memory = value
    }
}

func processMatrix(inout matrix : [[Int]]) {
    for rowIdx in 0..<matrix.count {

        let r = UnsafeMutablePointer<Int>(matrix[rowIdx])
        processRow(r, -2, count: matrix[rowIdx].count)
    }
}

var matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

processMatrix(&matrix)
print(matrix)   // [[2, 2, 2], [2, 2, 2], [2, 2, 2]]

A: Swift arrays are pretty painful when it comes to work with mutable data. There are two ways to fix that:
1) Use NSMutableArray
import Foundation

func processRow(_ row : NSMutableArray, _ value : Int) {
    for col in 0..<row.count {
        row[col] = value;
    }
}

func processMatrix(_ matrix : inout [NSMutableArray]) {
    for rowIdx in 0..<matrix.count {
        let r = matrix[rowIdx]
        processRow(r, -2);
    }
}

var matrix = [
    NSMutableArray(array: [1, 2, 3]),
    NSMutableArray(array: [4, 5, 6]),
    NSMutableArray(array: [7, 8, 9])
]

processMatrix(&matrix)

print(matrix) // outputs , <__NSArrayM 0x6000027a1560>(-2,-2,-2)]

2) Use class wrapper
class Wrapper<T: CustomDebugStringConvertible>: CustomDebugStringConvertible {
    var value: T

    init(_ value: T) {
        self.value = value
    }

    var debugDescription: String {
        return value.debugDescription
    }
}

func processRow(_ row : Wrapper<[Int]>, _ value : Int) {
    for col in 0..<row.value.count {
        row.value[col] = value;
    }
}

func processMatrix(_ matrix : inout [Wrapper<[Int]>]) {
    for rowIdx in 0..<matrix.count {
        let r = matrix[rowIdx]
        processRow(r, -2);
    }
}

var matrix = [
    Wrapper([1, 2, 3]),
    Wrapper([4, 5, 6]),
    Wrapper([7, 8, 9])
]

processMatrix(&matrix)

print(matrix) // outputs [[-2, -2, -2], [-2, -2, -2], [-2, -2, -2]]

However it doesn't look very nice.


text:
Q: Maintaining the scroll position of multi select jquery My client does not want control key to used to select/unselect items in multi-select list. I have come up with a solution but can't seem to keep the scroll position of the selected item in Chrome. This seems to be working fine in Firefox. What's wrong here? Or if there is any better solution, please suggest.

$(document).ready(function () {
    $('.multi-select option').on('mousedown',function (e) {
        e.preventDefault();

        var select = $(this).parent();
        var selectTop = select.scrollTop();

        $(this).prop('selected', $(this).prop('selected') ? false : true);
        select.scrollTop(selectTop);

        return false;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select title="Title" class="multi-select" style="width: 143px; height: 250px; overflow: scroll;" multiple="multiple">
        <option  value="1">1 </option>
        <option  value="2">2 </option>
        <option  value="3">3</option>
        <option  value="4">4</option>
        <option  value="5">5</option>
        <option  value="6">6</option>
        <option  value="7">7</option>
        <option  value="8">8</option>
        <option  value="9">9</option>
        <option  value="10">10</option>
        <option  value="11">11</option>
        <option  value="12">12</option>
        <option  value="13">13</option>
        <option  value="14">14</option>
        <option  value="15">15</option>
        <option  value="16">16</option>
        <option  value="17">17</option>
        <option  value="18">18</option>
        <option  value="19">19</option>
        <option  value="20">20</option>
        <option  value="21">21</option>
        <option  value="22">22</option>
        <option  value="23">23</option>
        <option  value="24">24</option>
        <option  value="25">25</option>
        <option  value="26">26</option>
        <option  value="27">27</option>
        <option  value="28">28</option>
        <option  value="31">31</option></select>

A: Solution

$(document).ready(function () {

    var selectTop;
    var mustChangeScrollTop = false;

    $('.multi-select').on('scroll',function (e) {
        if (mustChangeScrollTop){
            $(this).scrollTop(selectTop);
             mustChangeScrollTop = false;
        }
        return true;
    });

    $('.multi-select option').on('mousedown',function (e) {
        e.preventDefault();

        selectTop = $(this).parent().scrollTop();
        $(this).prop('selected', $(this).prop('selected') ? false : true);
        mustChangeScrollTop = true;

        return false;
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select title="Title" class="multi-select" style="width: 143px; height: 250px; overflow: scroll;" multiple="multiple">
        <option  value="1">1 </option>
        <option  value="2">2 </option>
        <option  value="3">3</option>
        <option  value="4">4</option>
        <option  value="5">5</option>
        <option  value="6">6</option>
        <option  value="7">7</option>
        <option  value="8">8</option>
        <option  value="9">9</option>
        <option  value="10">10</option>
        <option  value="11">11</option>
        <option  value="12">12</option>
        <option  value="13">13</option>
        <option  value="14">14</option>
        <option  value="15">15</option>
        <option  value="16">16</option>
        <option  value="17">17</option>
        <option  value="18">18</option>
        <option  value="19">19</option>
        <option  value="20">20</option>
        <option  value="21">21</option>
        <option  value="22">22</option>
        <option  value="23">23</option>
        <option  value="24">24</option>
        <option  value="25">25</option>
        <option  value="26">26</option>
        <option  value="27">27</option>
        <option  value="28">28</option>
        <option  value="31">31</option></select>

Explanation
I noticed that in Chrome there is an unnecessary scroll after the return from the mousedown event. So a solution/workaround is to add an onscroll event and reset ($(this).scrollTop(selectTop);) the top of the select area (selectTop) to what it was before the change of the selected option (selectTop = $(this).parent().scrollTop();). The mustChangeScrollTop variable is needed because the onscroll event is not called only when the unnessary scroll in Chrome occurs, but also when the user scrolls by hand. So when the unnecessary scroll is about to happen (which is when the user selects an option) we set the mustChangeScrollTop to true and then (when the unnecessary scroll occurs) we understand it by checking that it is true and then we set it back to false, so that it won't bother the user's scroll.
I tested it in Chrome and it works fine. I hope this helped you.


text:
Q: Kivymd call a page by function to open after click on the button I hope you are doing well.
I would like to ask a question about how to call a page in kivy from a function and I m using screen_manager.
I want this function to open the next page
if(clickedStart):
                screen_manager.add_widget(Builder.load_file("splashloading.kv"))
                screen_manager.current = "splashloading.kv"
                Clock.schedule_once(self.Login,6)

but it doesn't open why and how i can pass to splashloading page and after 5s of splashloading page must go to main page which is commented in the code right now.
this my main python code
from kivy.uix.screenmanager import ScreenManager,Screen, WipeTransition, FadeTransition, NoTransition
from kivymd.app import MDApp
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout

Window.size =(350, 580)
clickedStart = False
class StartPage(MDApp):
    def build(self):
        LabelBase.register(name='Lemonada',fn_regular='fonts/Lemonada-VariableFont_wght.ttf')
        global screen_manager
        screen_manager = ScreenManager()
        screen_manager.add_widget(Builder.load_file("firstUse.kv"))
        print(screen_manager)
        #screen_manager.add_widget(Builder.load_file("main.kv"))
        #screen_manager.add_widget(Builder.load_file("result.kv"))
        return screen_manager

    print(clickedStart)
    def getStarted(self, instance):
        clickedStart = True
        print(clickedStart)
    print(clickedStart)
    def on_start(self):
        if(clickedStart):
            screen_manager.add_widget(Builder.load_file("splashloading.kv"))
            screen_manager.current = "splashloading.kv"
            Clock.schedule_once(self.Login,6)
    def Login(self, *args):
        screen_manager.current = "main page"

if __name__ == "__main__":
    StartPage().run()

then the firstpage.kv code
MDScreen:
    name:"oneFirst"
    MDFloatLayout:
        md_bg_color: (255/255, 250/255, 245/255, 1)
        Image:
            source:"assets/1.png"
            size_hint:.50,.50
            pos_hint:{"center_x":.5,"center_y":.8}

        MDLabel:
            text:"the Vine Reco App"
            pos_hint:{"center_x":.5,"center_y":.63}
            halign:"center"
            theme_text_color:"Custom"
            text_color: (106/255, 90/255, 200/255, 1)
            font_size:"28sp"
            font_name:"Lemonada"
        MDLabel:
            text:"Recognizing the Type of the vine based on the image of list leaves"
            pos_hint:{"center_x":.5,"center_y":.4}
            halign:"center"
            theme_text_color:"Custom"
            text_color: (5/255, 215/255, 80/255, 1)
            font_size:"22sp"
            padding:[40,0]

        MDRaisedButton:
            id: startdBtn
            text:"Get Started"
            font_name: 'Fonts/Poppins-Regular.ttf'
            font_size:35
            markup: True
            pos_hint:{"center_x":.5,"center_y":.12}
            md_bg_color:(140/255, 220/255, 150/255, 1)
            text_color: (22/255, 160/255, 133/255, 1)
            on_press:app.getStarted(self)
        MDLabel:
            text:"2022 ELTE-IK (NWYUK6)| All Rights Reserved ©"
            pos_hint:{"center_x":.5,"center_y": .03}
            halign:"center"
            theme_text_color:"Custom"
            text_color: (51/255, 140/255, 180/255, 1)
            font_size:"13sp"

the page i want to open after click on Button is that one
splashloading.kv
MDScreen:
    name:"laodingFirst"
    MDFloatLayout:
        md_bg_color: (1,1,1,1)
        Image:
            source:"assets/start.gif"
            size_hint:1,1
            pos_hint:{"center_x":.5,"center_y":.5}


text:
Q: When does logic belong in the Business Object/Entity, and when does it belong in a Service? In trying to understand Domain Driven Design I keep returning to a question that I can't seem to definitively answer.
How do you determine what logic belongs to a Domain entity, and what logic belongs to a Domain Service?
Example:
We have an Order class for an online store.  This class is an entity and an aggregate root (it contains OrderItems).
Public Class Order:IOrder
{
    Private List<IOrderItem> OrderItems

    Public Order(List<IOrderItem>)
    {
        OrderItems = List<IOrderItem>
    }

    Public Decimal CalculateTotalItemWeight()
    //This logic seems to belong in the entity.
    {
        Decimal TotalWeight = 0
        foreach(IOrderItem OrderItem in OrderItems)
        {
            TotalWeight += OrderItem.Weight
        }
        return TotalWeight

    }
}

I think most people would agree that CalculateTotalItemWeight belongs on the entity.  However, at some point we have to ship this order to the customer.  To accomplish this we need to do two things:
1)  Determine the postage rate necessary to ship this order.
2)  Print a shipping label after determining the postage rate.
Both of these actions will require dependencies that are outside the Order entity, such as an external webservice to retrieve postage rates.  How should we accomplish these two things?  I see a few options:
1)  Code the logic directly in the domain entity, like CalculateTotalItemWeight.  We then call:
Order.GetPostageRate
Order.PrintLabel

2)  Put the logic in a service that accepts IOrder.  We then call:
PostageService.GetPostageRate(Order)
PrintService.PrintLabel(Order)

3)  Create a class for each action that operates on an Order, and pass an instance of that class to the Order through Constructor Injection (this is a variation of option 1 but allows reuse of the RateRetriever and LabelPrinter classes):
 Public Class Order:IOrder
{
    Private List<IOrderItem> OrderItems
    Private RateRetriever _Retriever
    Private LabelPrinter _Printer

    Public Order(List<IOrderItem>, RateRetriever Retriever, LabelPrinter Printer)
    {
        OrderItems = List<IOrderItem>
        _Retriever = Retriever
        _Printer = Printer
    }

    Public Decimal GetPostageRate
    {
        _Retriever.GetPostageRate(this)
    }

     Public void PrintLabel
    {
        _Printer.PrintLabel(this)
    }
}

Which one of these methods do you choose for this logic, if any?  What is the reasoning behind your choice?  Most importantly, is there a set of guidelines that led you to your choice?

A: I would use (2).
It doesn't add extra complexity to your Order Item.
To me, it seems the natural use of a helper service.
Update: in response to comment: The wiki page states:

Anemic Domain Model: With this
  pattern, logic is typically
  implemented in separate classes which
  transform the state of the domain
  objects

A: I would tend to have an external service determine the shipping rate.  For me that's application logic rather then order-specific logic.  For example you might decide for a period to offer free shipping for orders over a certain size, or to a particular group of loyal customers.  For me that logic will tend to change independently of how an order is constructed.
Most likely I would have the code which is responsible for placing the order (some kind of Order Processor service, in an application layer or in a command handler) hand off to a service to get the shipping rate, and then pass that rate into the order, so I guess option 2.
For printing a shipping label, I'd tend towards having the domain raise an event along the lines of http://www.udidahan.com/2009/06/14/domain-events-salvation/.  A separate handler would then deal with printing the label.  Again, the logic for this is that the way you print labels is likely to vary independently of how you construct an order, so it makes sense to keep that separate.  Using a domain event seems to be the cleanest way of ensuring that the label is printed at the right time without requiring the Order (or indeed the order processor) to be aware of the printing logic.

A: If you are accessing external webservices to get Postage rate, it is better to create interface in Application layer, because evan itself suggested that if you want to talk with external webservices you should construct interface in Application layer, you would have the service implementation injected into your Domain Object. For printing shipping label, because label is printed only when postage rate is determined, so is a kind of event like PostageRateConfirmed your domain can raise this event.
http://danhaywood.com/2010/04/30/accessing-domain-services-from-entities/

A: My point of view:
The domain is what contains the logic of your application, without the infrastructure cruft. The logic is that when an order is confirmed a label is printed and the shipping rate is determined. That should be in the domain.
The infrastructure then accomplishes what the domain wants to do. The domain may let the infrastructure know through messaging, or events.
That way no infrastructure leaks into the domain, you only require a way to transport messages out of the domain.


text:
Q: The command button in dialog does not update the outputText with the id given I have an outputText in a panelGrid which is also in a fieldset with the id of "foo". And I have a dialog. There is a datatable in this dialog and a commandbutton in the datatable. When I select an item of this datatable, and after clicking the commandbutton, I want the "foo" outputText's value to be changed with the data in the datatable in the dialog. But nothing seems to happen. I could use any help. Thanks in advance. Below is my xhtml snippet.
Edit: the method in the backing bean is also added to the post.

                <h:panelGrid columns="3"
                             columnClasses="formLayoutLabel, formLayoutInput, formLayoutValidator"
                             rowClasses="formLayoutOddRow, formLayoutEvenRow" cellpadding="0"
                             cellspacing="0" width="100%">
                    <h:outputText id="offerText" value="Offer" />
                    <h:outputText id="foo"
                                  rendered="#{notificationGroupSupport.instance.offers!=null}" />

                </h:panelGrid>

        <h:form id="selectOfferForm">
            <h:panelGrid columns="3" bgcolor="#eff5fa" cellspacing="5"
                         frame="box" styleClass="center">

                    <f:facet name="header">

Offer List

                    </f:facet>

                        <h:outputText value="#{offer.offerId}" />

                        <h:outputText value="#{offer.externalOfferId}" />

                        <h:outputText value="#{offer.description}" />

                    <f:facet name="footer">

                    </f:facet>

            </h:panelGrid>
        </h:form>

// This is my method for this commandbutton's actionListener in my backing bean. I don't think this is an issue about my backing bean. The method called after select offer button got clicked
 public void updateOffer()
 {
    campaignList = new ArrayList<Campaign>();
    lifecyclePolicyList = new ArrayList<LifecyclePolicy>();

    List<Offer> offers = getInstance().getOffers();

    for (Offer offer : offers) {

        if ( ( offer != null ) && ( offer.getOfferCampaignPairs() != null                )
                && ( offer.getOfferCampaignPairs().size() > 0 ) ) {
            for ( OfferCampaignPair pair : offer.getOfferCampaignPairs() ) {
                campaignList.add( pair.getCampaign() );
                if ( pair.getPrepaidLifecyclePolicy() != null ) {
                    lifecyclePolicyList.add( pair.getPrepaidLifecyclePolicy() );
                }
                if ( pair.getPostpaidLifecyclePolicy() != null ) {
                    lifecyclePolicyList.add( pair.getPostpaidLifecyclePolicy() );
                }
            }
        } else if ( offer == null ) {
            // todo
            getInstance().setCampaigns( campaignList );
            getInstance().setOffers( offerList );
            getInstance().setLifeCyclePolicies( lifecyclePolicyList );
        }
      }
      initConstants();
    }


text:
Q: why is the log/root of a negative number "invalid" when it is possible to compute it? Example:
$\ln(x^2+7x-6) - \ln(2x) = 0$
$x^2+7x-6=2x$
$x^2+5x-6=0$
$(x+6)(x-1)=0$
$x_1=-6$, $x_2=1$
Now, if I stopped here, I would only get half a point. That is because $0 < x$ and therefore $x_1=-6$ is invalid. $0 < x$ because you can't take the log of a negative number. Except you can. Okay, you get a complex number, it is hard to compute and above our level, but in this instance the final answer is just "$-6$", so you dont even have to compute $\ln(2\cdot(-6))$. So why is the $x_1$ soltion invalid? $1/x$, $x=0$ is invalid, but that is not because it is a difficult problem, it is invalid because it enables contradictions. $\ln(-1)=x$ won't lead to contradictions even if you dont know what imagninary numbers are, just leave it like $\ln(-1)$ uncomputed. If we then got $e^x$ in a follow up question we could compute the whole thing as $-1$. Kinda like if we didn't have negative numbers, we could still simplify $2-4=x$ to $0-2=x$ and then if we got $3+x=a$ we could solve it like this:
$3+x=a$
$3+(0-2)=a$
$3+0-2=a$
$(3+0)-2=a$
$(3)-2=a$
$1=a$
According to the logic I am arguing this doesn't work because $0-2=y$ is invalid so you can't use $y$ in the first place.
So am I in the right for saying that $x_1=-6$ is a valid answer or am I missing something? Is there anything I stated wrong?

A: There is a fundamental difference between negative numbers and logarithms of negative numbers, as far as equations are concerned.
A number has a single opposite (or negative): the opposite of $2$ is $-2$.
If you want to consider logarithms of negative numbers, you have to take care of the fact that the operation has not a unique result, but infinitely many.
So, writing $\operatorname{Log}$ for the logarithm in the complex numbers, the seemingly innocuous equation $\operatorname{Log}x=2$ has infinitely many solutions, namely all complex numbers of the form $e^2+2k\pi i$, for $k$ an integer.
Thus it's already a bit confusing to think about what's the meaning of $\operatorname{Log}x=\operatorname{Log}y$; not to mention that if we interpret $2\operatorname{Log}x$ as doubling every possible logarithm of $x$ and $\operatorname{Log}x+\operatorname{Log}y$ as adding every possible logarithm of $x$ with every possible logarithm of $y$, then
$$
2\operatorname{Log}x\ne\operatorname{Log}x+\operatorname{Log}x
$$
Don't use what you don't know about.
To make a different case, consider $S=\sum_{n=0}^\infty 2^n$. You don't know about series, but this seems to mean $1+2+4+\dotsb$, fairly simple. Then
$$
2S=2+4+8+\dotsb
$$
Look! If we add $1$ to both sides we get
$$
1+2S=1+2+4+8+\dotsb=S
$$
Uh, oh! This means $S=-1$.
The fact that you applying formal properties to objects doesn't mean the properties won't give contradictory results. You have to prove that no contradiction can arise.
By the way, the derivation above of $S=-1$ is perfectly fine if we interpret it in the $2$-adic numbers, but certainly not in the real numbers.
Or you can prove that, in the field of fractions of the ring of formal power series over the rational numbers,
$$
\sum_{n=0}^\infty x^n=\frac{1}{1-x}
$$
but this doesn't mean you can substitute $x=2$ in that equality and "prove" that $S=2$, because substitution is not allowed in that field.

A: It's a difference of solving the equation over $\mathbb{R}$ versus over $\mathbb{C}$. If you are asked to solve the equation over $\mathbb{R}$, then $x=-6$ is not a solution because the equation is not defined at $x=-6$ in $\mathbb{R}$. If you are asked to solve it over $\mathbb{C}$ then $x=-6$ is a valid solution because the equation is defined at $x=-6$ in $\mathbb{C}$.


text:
Q: Style by tag in a div tag not sure if this is possible but, can you style a single tag within a div tag? EG, could i put a
 around a section of my page then say make all
 tags green? is this possible or do you have to use classes?
thanks

A: If I understand what you're asking correct, then yes, it is possible. Here's an example. For more information, read up on CSS selectors.
On re-reading the question, the only way to style an arbitrary element within a div is by using either classes or id (with CSS selectors). Here's another example styling a single item using selectors.

A: For any single arbitrary element you must use an ID or a single-use class and select that:
#green-headings h2 { color: green; }

However, if there is some structural information about your
 that can be queryable with CSS selectors, you can use CSS pseudo-classes without needing to add an ID or class to your markup. For example, if your
 is always the first child of body:
body > div:first-child h2 { color: green; }

A: background to green HTML

hello everyone!

 hi. i'm a green bgd box

nice. i don't have background.

CSS
div > div {background-color: green}


text:
Q: MODULE_INITIALIZER like APP_INITIALIZER in lazy loaded modules Does any one know any functionality like APP_INITIALIZER that we can use in our lazy loaded modules?

Any workaround appreciated!!!

*

*I need to perform some API calls before module gets initialized and
it will return a promise.

*Calling from constructor not appreciated.

*Using resolve in app-routing-module not appreciated.


text:
Q: sort objects by key value 0 by number size how i can sort this object by user_id ?
{
 key_1: { user_id: 3 },
 key_2: { user_id: 1 },
 key_3: { user_id: 2 }
}

I need this:
{
 key_2: { user_id: 1 },
 key_3: { user_id: 2 },
 key_1: { user_id: 3 }
}

thanks for help

A: ES6 states a traversal order for object keys (see this article):

*

*Integer indices in ascending numeric order.

*Then, all other string keys, in the order in which they were added to the object.

*Lastly, all symbol keys, in the order in which they were added to the object.

This means that as long as you're using non integer keys of strings or symbols (not both), you can "sort" an object keys by creating a new object with the keys in the insertion order you need.
For example, use Object.entries() to get an array of [key, value] pairs, sort by user_id, and then convert back to an object using Object.fromEntries():

const obj = { key_1: { user_id: 3 }, key_2: { user_id: 1 }, key_3: { user_id: 2 }}

const result = Object.fromEntries(
  Object.entries(obj)
    .sort(([, a], [, b]) => a.user_id - b.user_id)
)

console.log(result)

However, this would fail for an object with integer keys:

const obj = { 1: { user_id: 3 }, 2: { user_id: 1 }, 3: { user_id: 2 }}

const result = Object.fromEntries(
  Object.entries(obj)
    .sort(([, a], [, b]) => a.user_id - b.user_id)
)

console.log(result)

So, it's better and less error prone to create an array of keys, sort it by the order you want, and then use it to get property values in that order:

const obj = { key_1: { user_id: 3 }, key_2: { user_id: 1 }, key_3: { user_id: 2 }}

const result = Object.keys(obj)
  .sort((a, b) => obj[a].user_id - obj[b].user_id)

console.log(result.forEach(key => console.log(obj[key])))

A: You can't. I think you are missing the nature of objects and arrays. The order of properties in an object doesn't matter. Of course, in an array it may.
If, for example, you receive an object and you want to display that data sorted, I would recommend you transform that object into an array and then sort it:

const object = {
  key_1: {
    user_id: 3
  },
  key_2: {
    user_id: 1
  },
  key_3: {
    user_id: 2
  }
};
const array = Object.entries(object)
const sortedArray = array.sort(([, aValue], [, bValue]) => aValue.user_id > bValue.user_id)

console.log(sortedArray)


text:
Q: Websockets Bundle Dependency on sun.misc I am attempting to create a Websockets- based application using the Grizzly Websockets bundles. I am doing this in Apache Felix using Bndtools.
Unfortunately, I seem to have all the needed dependencies, but the Grizzly bundles are failing to load due to the following failure:
org.glassfish.grizzly.websockets-server-2.3.23Unable to resolve
org.glassfish.grizzly.websockets-server [23](R 23.0): missing
requirement [org.glassfish.grizzly.websockets-server [23](R 23.0)]
osgi.wiring.package; (osgi.wiring.package=sun.misc) Unresolved
requirements: [[org.glassfish.grizzly.websockets-server [23](R 23.0)]
osgi.wiring.package; (osgi.wiring.package=sun.misc)]

I have researched this failure, originally looking for a bundle, only to discover that apparently this is some kind of JVM library that is really not needed. I have seen workarounds and solutions that involve adding a line to a conf/config.properties file:
org.osgi.framework.system.packages.extra=sun.misc

I understand that this is a dangerous workaround, and there are rumors of "safer" solutions to this problem. They all involve making changes to  tags or to the config.properties file.
Unfortunately, in a Bndtools environment, there are apparently no such tags or files for me to edit!
Or, at least, I cannot find these things in my Bndtools project.
Is there some way to fix this "sun.misc" problem within a Bndtools- based project? I am using Bndtools repository and am wondering which of the various "bnd" files I need to edit, as well as what to put into those files.
Someone please advise...

A: You need to add -runsystempackages: sun.misc to the bnd/bndrun file.

A: The best tool for that is https://github.com/diffplug/osgiX
You just will change PKG=sun.misc(or another package) in gradle.properties and run gradlew build.
It will generate bundle-fragment, which you will can add to your class path.
The bundle then contains:
Manifest-Version: 1.0
Export-Package: sun.misc
Fragment-Host: system.bundle; extension:=framework
Bundle-ManifestVersion: 2
Bundle-License: public domain - http://unlicense.org/
Bundle-SymbolicName: com.diffplug.osgi.extension.sun.misc
Bundle-Version: 0.0.0


text:
Q: Changing expression from sync to async I have the following expression :
    var rules = rules.OrderBy(rule => (int)rule.RuleType)
    .FirstOrDefault( item  =>  item.IsMatch(request.data))
    ?.Execute(request.data);

What this piece of code does - it takes a set of rules (which all implement the same interface),
sorts them in ascending order, and then calls the IsMatch function that each one of these rules implements - the first 'True' that returns from any IsMatch function will stop the iteration and call the Execute function.
If all returned False, Execute will not be called.
The rules object is at the beginning (after the OrderBy) a IOrderedEnumerable<IRule> , and later changes to IEnumerable<IRule> (the type FirstOrDefault returns).
I am refactoring some of my code, now the isMatch function has changed to an Async function.
I am using .NET 472 and found that the FirstOrDefaultAsync that is in the EntityFramework.DynamicLinq namespace, can only be called on an IQueryable type of object.
Once I change it to :
 var rules = rules.OrderBy(rule => (int)rule.RuleType).ToList().AsQueryable()
    .FirstOrDefaultAsync(async item  => await item.IsMatchAsync(request.data))
    ?.Execute(request.data);

I get an error that there is no overload to the FirstOrDefaultAsync function that accepts a boolean (or in this case lambda that returns booleans)
So my question is - how can I change this code to asynchronous code?

A: Using the library System.Linq.Async, and assuming that the Rule class contains the methods public Task<bool> IsMatchAsync(string arg) and public Task ExecuteAsync(string arg):
var matchedRule = await rules.ToAsyncEnumerable()
    .OrderBy(rule => (int)rule.RuleType)
    .FirstOrDefaultAwaitAsync(async item => await item.IsMatchAsync(request.data));
if (matchedRule != null) await matchedRule.ExecuteAsync(request.data);


text:
Q: Combine two triangular meshes I have two triangular meshes over a given 2-D domain. The goal is to combine these meshes and create a third triangular mesh such that it contains all edge and node information of the initial meshes. The following image is a pictorial presentation of what I am looking for:

I am looking for a Matlab code to do this. I have searched a lot, but what I have found seems to be different.

A: This function does exactly what I want:
https://www.mathworks.com/matlabcentral/fileexchange/48613-surface-intersection?requestedDomain=www.mathworks.com


text:
Q: Yii2 Kartik mdfp not showing watermark I use kartik\mpdf\Pdf; However when i add a watermark it does not show on the pdf generated.
here is my code
    $pdf = new Pdf([
        'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
        'format' => Pdf::FORMAT_A4,
        'filename' => $model->code . '.pdf',
        'content' => $this->render('_pdf', [
            'models' => [$model],
            'title' => $title,
        ]),
        'options' => [
            'title' => $title,
        ],
        'methods' => [
            'SetHeader' => [$header . $date],
            'SetTitle' => '#' . $model->code,
            'SetWatermarkImage' => [\yii\helpers\Url::to(['/images/logo.png'])],
        ],
    ]);
    return $pdf->render();

A: well I checked the mpdf original documentation they have
$pdf->SetWatermarkImage('image file')

I tried using the same but it didn't work.
But this worked for me
'options' => [
            'title' => $title,
            'showWatermarkImage' => true,
        ],


text:
Q: Laravel Models - add non-database field I have a model in Laravel called Checkout. It is just tied to a table in the database called checkouts.
namespace App;

use Illuminate\Database\Eloquent\Model;

class Checkout extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'checkouts';
}

What I would like to do is add a field to the model that isn't a field in the table. Is this even possible?
If need be, I will completely manually build the model, but I have never seen any examples of that either.
Any help would be greatly appreciated! Thanks,

A: You can use Laravel's Accessor as:
public function getSomeExtraFieldAttribute()
{
    return 2*4; // just for exmaple
}

Then you can access it using
$checkout = App\Checkout::find(1);

$checkout->some_extra_field;


text:
Q: How to specify "windows-curses" be installed only on Windows with pypi This is my setup.py:
 install_requires=[
        'requests',
        'appdirs',
        'windows-curses; platform_system=="Windows"'
        ],

When I install the project on Windows it says 'windows-curses; platform_system=="Windows"' can not be found, however pip install windows-curses works.
ERROR: Could not find a version that satisfies the requirement windows-curses; platform_system == "Windows" (from nodreader==0.1.9) (from versions: none)


text:
Q: Trivia Game not scoring correctly So as I'm learning, I've been tasked with creating a Trivia Game. I really thought I was on the right track. The problem is, when I click "done" on my game, no matter the answers. They all come back incorrect. I'm not sure where the flaw is in my coding. If someone could point out the error that would be amazing.
$('#start').on('click', function(){
game.start();
})

$(document).on('click','#end',function(){
game.done();
})

var questions = [{
question:"The Fantastic Four have their headquarters in what building?",
answers:["Stark Tower","Fantastic Headquarters","Baxter Building","Xavier Insitute"],
correctAnswer:"Baxter Building",
}, {
question:"Peter Parker works as a photographer for?",
answers:["The Daily Planet","The Daily Bugle","New York Times","The Daily Rag"],
correctAnswer:"The Daily Bugle"
}, {
question:"S.H.I.E.L.D.'s highest ranking agent is?",
answers:["Nick Fury","Captain America","Natalia Romanova","Peter Parker"],
correctAnswer:"Nick Fury"
}, {
question:"What vehicle is the Avengers primary mode of transport?",
answers:["A bus","The Quinjet","The Blackbird","The Blackhawk"],
correctAnswer:"The Quinjet"
}, {
question:"Ghost Rider is also known as?",
answers:["The Guardian Devil","The Spirit of Hate","The Spirit of Vengeance","The Red Skull"],
correctAnswer:"The Spirit of Vengeance"
}];

var game = {
correct: 0,
incorrect: 0,
counter: 10,
countdown: function(){
    game.counter--;
    $('#counter').html(game.counter);
    if(game.counter<=0){
        console.log("Time is up!");
        game.done();
    }
},
start: function(){
        timer = setInterval(game.countdown,1000);
        $('#wra').prepend('
Time Remaining: 120 Seconds </h2')
        for (var i=0;i<questions.length;i++){
            $('#wrap').append('
'+questions[i].question+'</h2');
            for(var j = 0; j<questions[i].answers.length;j++){
            $("#wrap").append("<input type = 'radio' name =  'question-" +i+"' value = '"+questions[i].answers[j]+" '> "+questions[i].answers[j])
        }
    }
    $('#wrap').append('
<button id="end">DONE</button>')
},
done: function(){
    $.each($('input[name="question-0"]:checked'), function(){
        if($(this).val()===questions[0].correctAnswer){
            game.correct++;
        } else {
            game.incorrect++;
        }
    });

    $.each($('input[name="question-1"]:checked'), function(){
        if($(this).val()===questions[1].correctAnswer){
            game.correct++;
        } else {
            game.incorrect++;
        }
    });

    $.each($('input[name="question-2"]:checked'), function(){
        if($(this).val()===questions[2].correctAnswer){
            game.correct++;
        } else {
            game.incorrect++;
        }
    });

    $.each($('input[name="question-3"]:checked'), function(){
        if($(this).val()===questions[3].correctAnswer){
            game.correct++;
        } else {
            game.incorrect++;
        }
    });

    $.each($('input[name="question-4"]:checked'), function(){
        if($(this).val()===questions[4].correctAnswer){
            game.correct++;
        } else {
            game.incorrect++;
        }
    });

    this.result();
},

result: function(){
    clearInterval(timer);
    $('#wrap h2').remove();
    $('#wrap').html("
All done!
");
    $('#wrap').append("
Correct Answers: " + this.correct + "
");
    $('#wrap').append("
Incorrect Answers: " + this.incorrect + "
");
    $('#wrap').append("
Unanswered Questions: " + (questions.length-(this.incorrect+this.correct)) + "
");

}

}

A: Your error is in the line
   $("#wrap").append("<input type = 'radio' name =  'question-" +i+"' value = '"+questions[i].answers[j]+" '> "+questions[i].answers[j])

if you notice you append an extra "space" on each correct answer at questions[i].answers[j]+" '
So your values comparison between the correct answers and selected values is never true due to that extra space


text:
Q: Change dropdown index after downloading file I have a drop down list having Download as one option
When ever user selects Download option, i am using Response to download the file. After downloading the file, i want to change the drop down list index to 0. I tried it by setting the selected index of drop down to 0 after downloading the file. But it is not at all wroking.
If any postback occurs after downloading the file, again Download option selected automatically in the drop down list.
I am calling the following method when Download option is selected.
protected void downloadfile()
{
         Response.Clear();
         Response.Buffer = false;
         Response.AddHeader("Accept-Ranges", "bytes");
         Response.ContentType = "application/octet-stream";
         Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         Response.AddHeader("Connection", "Keep-Alive");
         Response.OutputStream.Write(buffer, 0, bytesRead);
         Response.Flush();
}

Please share your suggestions to resolve this....

A: I resolved this issue, by using Iframe.
As soon as the Download option is selected in the drop down,I am calling the javascript function DownloadFile() in the server side as follow:
protected void ddlSelectedAction_SelectedIndexChanged(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.Page, GetType(), "download", "DownloadFile();", true);

    // We can do what ever we want, You can redirect to another page or anything you want
    //Here I am changing the ddlSelectedAction selected index to 0
    ddlSelectedAction.SelectedIndex = 0;

}

Below is of that javascript function
DownloadFile()
{

    var filename= $get("Filename").value;

    // Point the IFRAME to GenerateFile, with the
    //   desired region as a querystring argument.
    iframe.src = "GenerateFile.ashx?fname=" + filename;

    // This makes the IFRAME invisible to the user.
    iframe.style.display = "none";

    // Add the IFRAME to the page.  This will trigger
    //   a request to GenerateFile now.
    document.body.appendChild(iframe);
}

In the above function I am creating a Iframe, the source will be the handlerfile(GenerateFile.ashx) and any query string you can pass, that are used for downloading like filename,filepath etc.
In the pageload of handler file I am writing the code for downloading the file. Now we can do what ever operation we want after downloading the file.


text:
Q: Unable to connect GRPC microservice with client - Nest JS Node on k8s I'm currently stuck with connecting clusterIp  services in kubernetes. The main goal is to connect one pod (microservice) using grpc  and other pod (client) using node .
I'm using the service name to expose and connect to the microservice products-microservice  but I'm getting this error when try to call the microservice on the client.
"Error: 14 UNAVAILABLE: failed to connect to all addresses",
            "    at Object.exports.createStatusError (/usr/src/app/node_modules/grpc/src/common.js:91:15)",
            "    at Object.onReceiveStatus (/usr/src/app/node_modules/grpc/src/client_interceptors.js:1209:28)",
            "    at InterceptingListener._callNext (/usr/src/app/node_modules/grpc/src/client_interceptors.js:568:42)",
            "    at InterceptingListener.onReceiveStatus (/usr/src/app/node_modules/grpc/src/client_interceptors.js:618:8)",
            "    at callback (/usr/src/app/node_modules/grpc/src/client_interceptors.js:847:24)"

I review the docker image that I created and it's pointing to this address url: '0.0.0.0:50051'  but not working as this article recommends https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears/
Until now I have just one microservice for products that contains the logic to manage products  and was developed with node-js and grpc (locally works perfect). I named xxx-microservice-products-deployment  and contains their definition in k8s looks like:
kind: Deployment
metadata:
  name: pinebox-microservice-products-deployment
  labels:
    app: pinebox
    type: microservice
    domain: products
spec:
  template:
    metadata:
      name: pinebox-microservice-products-pod
      labels:
        app: pinebox
        type: microservice
        domain: products
    spec:
      containers:
        - name: pg-container
          image: postgres
          env:
            - name: POSTGRES_USER
              value: testuser
            - name: POSTGRES_PASSWORD
              value: testpass
            - name: POSTGRES_DB
              value: db_development
          ports:
            - containerPort: 5432
        - name: microservice-container
          image: registry.digitalocean.com/pinebox/pinebox-microservices-products:latest
      imagePullSecrets:
        - name: regcred
  replicas: 1
  selector:
    matchLabels:
      app: pinebox
      type: microservice
      domain: products

Then in order to connect to them, we create a service with a clusterIp  that exposes the 50051 , and their definition in k8s looks like:
kind: Service
apiVersion: v1
metadata:
  name: pinebox-products-microservice
spec:
  selector:
    app: pinebox
    type: microservice
    domain: products
  ports:
    - targetPort: 50051
      port: 50051

Now, we create a client in node too, that contains the api  (get,post)  methods that under the hood make the connection with the microservice. I named the client xxx-api-main-app-deployment and their definition in k8s looks like:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pinebox-api-main-app-deployment
  labels:
    app: pinebox
    type: api
    domain: main-app
    role: users-service
spec:
  template:
    metadata:
      name: pinebox-api-main-app-pod
      labels:
        app: pinebox
        type: api
        domain: main-app
        role: products-service
    spec:
      containers:
        - name: pinebox-api-main-app-container
          image: registry.digitalocean.com/pinebox/pinebox-main-app:latest
      imagePullSecrets:
        - name: regcred
  replicas: 1
  selector:
    matchLabels:
      app: pinebox
      type: api
      domain: main-app
      role: products-service

Also, I create a service to export the api and their k8s definition looks like:
kind: Service
apiVersion: v1
metadata:
  name: pinebox-api-main-app-service
spec:
  selector:
    app: pinebox
    type: api
    domain: main-app
    role: products-service
  type: NodePort
  ports:
    - name: name-of-the-port
      port: 3333
      targetPort: 3333
      nodePort: 30003

Until here, all looks good. So I tried to make the connection with the service but I got this error
"Error: 14 UNAVAILABLE: failed to connect to all addresses",
            "    at Object.exports.createStatusError (/usr/src/app/node_modules/grpc/src/common.js:91:15)",
            "    at Object.onReceiveStatus (/usr/src/app/node_modules/grpc/src/client_interceptors.js:1209:28)",
            "    at InterceptingListener._callNext (/usr/src/app/node_modules/grpc/src/client_interceptors.js:568:42)",
            "    at InterceptingListener.onReceiveStatus (/usr/src/app/node_modules/grpc/src/client_interceptors.js:618:8)",
            "    at callback (/usr/src/app/node_modules/grpc/src/client_interceptors.js:847:24)"

I didn't find anything useful to make it work. Anyone has any clues ?
So, after digging into a solution for the issue, I found that the kubernetes team recommend to use linkerd to literally convert the connection to http  due to the k8s doesn't work in this case. So I followed this post https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears/, then I go to the linkerd guide and follow the installation steps.
Now I was able to see the linkeird dashboard, but not able to communicate the microservice with the client.  So I tried to check if the port was exposed in the client pod so, I validate using this command:
$ kubectl exec -i -t pod/pinebox-api-main-app-deployment-5fb5d4bf9f-ttwn5 --container pinebox-api-
main-app-container -- /bin/bash
$ pritnenv

and this was the output:
PINEBOX_PRODUCTS_MICROSERVICE_PORT_50051_TCP_PORT=50051
KUBERNETES_SERVICE_PORT_HTTPS=443
PINEBOX_PRODUCTS_MICROSERVICE_SERVICE_PORT=50051
KUBERNETES_PORT_443_TCP_PORT=443
PINEBOX_API_MAIN_APP_SERVICE_SERVICE_PORT_NAME_OF_THE_PORT=3333
PORT=3000
NODE_VERSION=12.18.2
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
PINEBOX_API_MAIN_APP_SERVICE_PORT_3333_TCP_PORT=3333
PINEBOX_PRODUCTS_MICROSERVICE_SERVICE_HOST=10.105.230.111
TERM=xterm
PINEBOX_API_MAIN_APP_SERVICE_PORT=tcp://10.106.81.212:3333
SHLVL=1
PINEBOX_PRODUCTS_MICROSERVICE_PORT=tcp://10.105.230.111:50051
KUBERNETES_SERVICE_PORT=443
PINEBOX_PRODUCTS_MICROSERVICE_PORT_50051_TCP=tcp://10.105.230.111:50051
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PINEBOX_API_MAIN_APP_SERVICE_SERVICE_PORT=3333
KUBERNETES_SERVICE_HOST=10.96.0.1
_=/usr/bin/printenv
root@pinebox-api-main-app-deployment-5fb5d4bf9f-ttwn5:/usr/src/app#

So as you can see there is and env variable that contains the port for the service, for this is working. I'm not using the IP direclty, because it won't work when I scale the deployment to have more resources.
Then, I validate that my microservice was running using :
kubectl logs pod/xxx-microservice-products-deployment-78df57c96d-tlvvj -c microservice-container

and this was the output:
[Nest] 1   - 07/25/2020, 4:23:22 PM   [NestFactory] Starting Nest application...
[Nest] 1   - 07/25/2020, 4:23:22 PM   [InstanceLoader] PineboxMicroservicesProductsDataAccessModule dependencies initialized +12ms
[Nest] 1   - 07/25/2020, 4:23:22 PM   [InstanceLoader] PineboxMicroservicesProductsFeatureShellModule dependencies initialized +0ms
[Nest] 1   - 07/25/2020, 4:23:22 PM   [InstanceLoader] AppModule dependencies initialized +0ms
[Nest] 1   - 07/25/2020, 4:23:22 PM   [NestMicroservice] Nest microservice successfully started +22ms[Nest] 1   - 07/25/2020, 4:23:22 PM   Microservice Products is listening +15ms

All looks good. So then I re-validate which port I'm using on the code:

*

*Microservice

const microservicesOptions = {
 transport: Transport.GRPC,
 options: {
   url: '0.0.0.0:50051',
   credentials: ServerCredentials.createInsecure(),
   package: 'grpc.health.v1',
   protoPath: join(__dirname, 'assets/health.proto'),
 },
};

*

*Client:

ClientsModule.register([
     {
       name: 'HERO_PACKAGE',
       transport: Transport.GRPC,
       options: {
         url: '0.0.0.0:50051',
         package: 'grpc.health.v1',
         protoPath: join(__dirname, 'assets/health.proto'),
         // credentials: credentials.createInsecure()
       },
     },
   ])

Then, I decide to check the logs inside the linkerd pod that is running for the client.
kubectl logs pod/xxx-api-main-app-deployment-5fb5d4bf9f-ttwn5 -c linkerd-init
and the output was this:
2020/07/25 16:37:50 Tracing this script execution as [1595695070]
2020/07/25 16:37:50 State of iptables rules before run:
2020/07/25 16:37:50 > iptables -t nat -vnL
2020/07/25 16:37:50 < Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
2020/07/25 16:37:50 > iptables -t nat -F PROXY_INIT_REDIRECT
2020/07/25 16:37:50 < iptables: No chain/target/match by that name.
2020/07/25 16:37:50 > iptables -t nat -X PROXY_INIT_REDIRECT
2020/07/25 16:37:50 < iptables: No chain/target/match by that name.
2020/07/25 16:37:50 Will ignore port(s) [4190 4191] on chain PROXY_INIT_REDIRECT
2020/07/25 16:37:50 Will redirect all INPUT ports to proxy
2020/07/25 16:37:50 > iptables -t nat -F PROXY_INIT_OUTPUT
2020/07/25 16:37:50 < iptables: No chain/target/match by that name.
2020/07/25 16:37:50 > iptables -t nat -X PROXY_INIT_OUTPUT
2020/07/25 16:37:50 < iptables: No chain/target/match by that name.
2020/07/25 16:37:50 Ignoring uid 2102
2020/07/25 16:37:50 Redirecting all OUTPUT to 4140
2020/07/25 16:37:50 Executing commands:
2020/07/25 16:37:50 > iptables -t nat -N PROXY_INIT_REDIRECT -m comment --comment proxy-init/redirect-common-chain/1595695070
2020/07/25 16:37:50 <
2020/07/25 16:37:50 > iptables -t nat -A PROXY_INIT_REDIRECT -p tcp --match multiport --dports 4190,4191 -j RETURN -m comment --comment proxy-init/ignore-port-4190,4191/1595695070
2020/07/25 16:37:50 <
2020/07/25 16:37:50 > iptables -t nat -A PROXY_INIT_REDIRECT -p tcp -j REDIRECT --to-port 4143 -m comment --comment proxy-init/redirect-all-incoming-to-proxy-port/1595695070
2020/07/25 16:37:50 <
2020/07/25 16:37:50 > iptables -t nat -A PREROUTING -j PROXY_INIT_REDIRECT -m comment --comment proxy-init/install-proxy-init-prerouting/1595695070
2020/07/25 16:37:50 <
2020/07/25 16:37:50 > iptables -t nat -N PROXY_INIT_OUTPUT -m comment --comment proxy-init/redirect-common-chain/1595695070
2020/07/25 16:37:50 <
2020/07/25 16:37:50 > iptables -t nat -A PROXY_INIT_OUTPUT -m owner --uid-owner 2102 -o lo ! -d 127.0.0.1/32 -j PROXY_INIT_REDIRECT -m comment --comment proxy-init/redirect-non-loopback-local-traffic/1595695070
2020/07/25 16:37:51 <
2020/07/25 16:37:51 > iptables -t nat -A PROXY_INIT_OUTPUT -m owner --uid-owner 2102 -j RETURN -m comment --comment proxy-init/ignore-proxy-user-id/1595695070
2020/07/25 16:37:51 <
2020/07/25 16:37:51 > iptables -t nat -A PROXY_INIT_OUTPUT -o lo -j RETURN -m comment --comment proxy-init/ignore-loopback/1595695070
2020/07/25 16:37:51 <
2020/07/25 16:37:51 > iptables -t nat -A PROXY_INIT_OUTPUT -p tcp -j REDIRECT --to-port 4140 -m comment --comment proxy-init/redirect-all-outgoing-to-proxy-port/1595695070
2020/07/25 16:37:51 <
2020/07/25 16:37:51 > iptables -t nat -A OUTPUT -j PROXY_INIT_OUTPUT -m comment --comment proxy-init/install-proxy-init-output/1595695070
2020/07/25 16:37:51 <
2020/07/25 16:37:51 > iptables -t nat -vnL
2020/07/25 16:37:51 < Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 PROXY_INIT_REDIRECT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* proxy-init/install-proxy-init-prerouting/1595695070 */
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 PROXY_INIT_OUTPUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* proxy-init/install-proxy-init-output/1595695070 */
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain PROXY_INIT_OUTPUT (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 PROXY_INIT_REDIRECT  all  --  *      lo      0.0.0.0/0           !127.0.0.1            owner UID match 2102 /* proxy-init/redirect-non-loopback-local-traffic/1595695070 */
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0            owner UID match 2102 /* proxy-init/ignore-proxy-user-id/1595695070 */
    0     0 RETURN     all  --  *      lo      0.0.0.0/0            0.0.0.0/0            /* proxy-init/ignore-loopback/1595695070 */
    0     0 REDIRECT   tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            /* proxy-init/redirect-all-outgoing-to-proxy-port/1595695070 */ redir ports 4140
Chain PROXY_INIT_REDIRECT (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RETURN     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 4190,4191 /* proxy-init/ignore-port-4190,4191/1595695070 */
    0     0 REDIRECT   tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            /* proxy-init/redirect-all-incoming-to-proxy-port/1595695070 */ redir ports 4143
    ```
I'm not sure where the problem is, and thanks in advance for your help.
Hopefully this give you more context and you can point me out in the right direction.

A: The iptables output from the Linkerd proxy-init looks fine.
Did you check the logs of the linkerd-proxy inside the container? That might help to understand what is happening.
It's also worth trying the port-forward test that @KoopaKiller recommends


text: Q: Multivariable calculus problem Suppose $F(x,y)$ is a continuously differentiable function in $\mathbb{R}^2$, and $F(x,y)=0$ is a figure "8" in the $\mathbb{R}^2$ plane. Then at least, how many solutions does the following system have in $\mathbb{R}^2$: $$F_x(x,y)=0, F_y(x,y)=0$$


text:
Q: Create a layout with a titled border in Vaadin I want to create a layout with a titled border just like in the Java application screenshot below:

Is it possible?

A: Does it have to be 100% like the image above? If not, you can try the Panel class with default (valo) theme, there's a sample with code at http://demo.vaadin.com/sampler/#ui/structure/panel

A: There is no layout which displays the same layout as you shown in image. However vaadin gives flexibility to play around its components look and feel. As #Jorge mentioned, you can have panel and then play around CSS to get the layout like you shown.
There is no ready to use layout like that in vaadin and even don't see the reason to have it one in core vaadin. if someone builds the add-on is different story.


text:
Q: laravel 9 Error in my project admincontroller and auth I am using Laravel latest version 9
When writing the code I know now I am not an expert.
I encountered this error even though I applied everything correctly from the video clip.
Any help :)
my error : https://flareapp.io/share/q5YMDKj5#F48 .
my code admin.php:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if(!Auth::guard('admin')->check()){
            return redirect('/admin/login');
        }
        return $next($request);
    }
}

my code adminController.php:

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Middleware\Authenticate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function dashboard(){
        return view('admin.dashboard');
    }

    public function login(Request $request){
        if ($request->isMethod('post')) {
            $data = $request->all();
            // echo "<pre>"; print_r($data); die;
            if (Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password'],'status'=>1])) {
                return redirect('admin/dashboard');
            }else{
                return redirect()->back()->with('error_message','Invalid Email or Password');
            }
        }
        return view('admin.login');
    }
}


text:
Q: Flex 4 Button state in a HGroup I have a HGroup with some buttons inside which is my application's menu.
<s:HGroup id="nav">
    <s:Button id="homeButton" label="Home" />
    <s:Button id="showroomButton" label="Showroom" />
    <s:Button label="Catalogue" />
    <s:Button label="Offers" />
    <s:Button label="My Account" />
    <s:Button label="My Orders" />
</s:HGroup>

What I want is when I click for example the #homeButton to change it's state to "over", become disabled and reset all other buttons to the "up" state.
I've written this function
    private function resetNavState():void {
        for(var i:int = 0,ii:int = nav.numChildren-1;i<ii;i++) {
        Button(nav.getChildAt(i)).mouseEnabled = true;
        Button(nav.getChildAt(i)).skin.setCurrentState("up",true);
    }
}

And then on the homeButton click handler for example i use
protected function homeButton_clickHandler(event:MouseEvent):void
{
    resetNavState();
    currentState = "home";
    homeButton.skin.setCurrentState("over",true);
    homeButton.mouseEnabled = false;

}

I resets the states of the #nav buttons but it doesn't change the state of the pressed button.
Any ideas?
Thanx in advance

A: You'll want to place your buttons in a in a <s:ButtonBar /> control rather than the HGroup.


text:
Q: How to catch exception from member destructor I wonder whether (and how) it's possible to catch an exception thrown in a member destructor. Example:
#include <exception>

class A
{
public:
    ~A() {
        throw std::exception("I give up!");
    }
};

class B
{
    A _a;
public:
    ~B() {
        // How to catch exceptions from member destructors?
    }
};

A: Yes, you can catch such an exception, using the function-try-block:
class B
{
    A _a;
public:
    ~B() try {
        // destructor body
    }
    catch (const std::exception& e)
    {
        // do (limited) stuff
    }
};

However, you cannot really do much with such an exception. The standard specifies that you cannot access non-static data members or base classes of the B object.
Also, you cannot silence the exception. Unlike with other functions, the exception will be re-thrown implicitly once the function-try-block handler of a destructor (or constructor) finishes execution.
All in all, destructors should really not throw exceptions.

A: Here is a self-explanatory example what you can do:
#include <stdexcept>
#include <iostream>

class A
{
public:
    ~A() noexcept(false) {
        throw std::runtime_error("I give up!");
    }
};

class B
{
    A _a;
public:
    ~B() noexcept(false) try {
        // dtor body
    }
    catch (std::exception const& e)
    {
        std::cout << "~B: " << e.what() << std::endl;
        // rethrown and you can't do anything about it
    }
};

int main()
{
    try
    {
        B b;
    }
    catch (std::exception const& e)
    {
        std::cout << "main: " << e.what() << std::endl;
    }
}

Demo
I believe, the right reference to the C++ standard (I use copy of n3376) is in 15.3 Handling an exception:

15 The currently handled exception is rethrown if control reaches the
  end of a handler of the function-try-block of a constructor or
  destructor.


text:
Q: Рандомный выбор числа из диапазона Используется С#
Как сделать чтобы рандомизация осуществлялась по двум вариантам?
Вариант 1: min=1 000;  max=5 000; col=1;
Вариант 2: min=1;  max=20; col=4;
Приложенный код не удалось настроить, поэтому буду признателен, если кто-нибудь поможет настроить или предложит свой вариант для решения данной задачи.
Ссылка на проект
ссылка на проект ИЗМ1
Как скачать проект см (http://prntscr.com/dmh2iw)

КОД
namespace rsh
{
   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Random r = new Random();

        // РАНДОМИЗАЦИЯ ВАРИАНТ 1
        private void button1_Click(object sender, EventArgs e)
        {
            int min = Convert.ToInt16(textBox1.Text); // МАКС - максимальное число диапазона
            int max = Convert.ToInt16(textBox2.Text); // МИН - минимальное число диапазона
            int col = Convert.ToInt16(textBox3.Text); // количество итераций
            int[] perm = Enumerable.Range(min, max + 1).ToArray();

            for (int i = col; i >= 1; i--)
            {
                int j = r.Next(i + 1);
                // exchange perm[j] and perm[i];
                int temp = perm[j];
                perm[j] = perm[i];
                perm[i] = temp;

                textBox4.AppendText(perm[i] + "  " + "\r\n"); // выдаёт ОДИН ряд цифр
            }
        }

        // РАНДОМИЗАЦИЯ ВАРИАНТ 2
        private void button3_Click(object sender, EventArgs e)
        {
            int min = Convert.ToInt16(textBox1.Text); // МАКС - максимальное число диапазона
            int max = Convert.ToInt16(textBox2.Text); // МИН - минимальное число диапазона
            int col = Convert.ToInt16(textBox3.Text); // количество итераций
            int[] perm = Enumerable.Range(min, max + 1).ToArray();

            for (int i = col; i >= 1; i--)
            {
                int j = r.Next(i + 1);
                // exchange perm[j] and perm[i];
                int temp = perm[j];
                perm[j] = perm[i];
                perm[i] = temp;

                textBox4.AppendText(perm[i] + "  " + "\r\n"); // выдаёт ОДИН ряд цифр
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            textBox4.Clear();
        }
    }
  }

A: Ссылка ваша нерабочая. Вот вам пример консольной программы:
class Program
{
    static void Main(string[] args)
    {
        foreach (var item in GetRandomNumbers(1000, 5000))
        {
            Console.WriteLine(item.ToString());
        }

        Console.WriteLine(new string('=', 20));

        foreach (var item in GetRandomNumbers(1, 20))
        {
            Console.WriteLine(item.ToString());
        }

        Console.ReadKey();
    }

    public static List<int> GetRandomNumbers(int min = 0, int max = 5)
    {
        if (max - min <= 0) throw new ArgumentException("Неверные аргументы в вызове метода");

        int seed = (int)DateTime.Now.Ticks;
        Random rnd = new Random(seed);

        List<int> result = Enumerable.Range(min, max).OrderBy(n => rnd.Next()).ToList();

        return result;
    }
}

Только я не совсем понимаю, что значит это ваше: "Приложенный код не удалось настроить..."?


text:
Q: What is the point of seperating analog ground and digital ground if they are going to meet at the end First off, I'm fairly new to electronics, I don't have much knowledge so bear with me. I saw a schematic of an ADC connection to an MCU, and I noticed that the grounds are split into two - Analog and Digital ground. I read up on why they are split. It's to prevent the high frequency noise of the digital signals to interfere with the analog components.
In theory I can understand but practically, if I were to make any product where I use an ADC, then if I were getting power from the mains or a battery, ultimately won't the grounds meet at one point? So then what is the point of separating the ground lines. How does this whole thing work?
Thank you

A: The simple answer is that it keeps digital and analog ground currents separated. Digital ground current is typically "noisy". If the analog and digital ground are intermixed, noisy digital ground currents can induce noise into the analog parts of the circuit.
But if the circuit is configured properly, the digital and analog parts of the circuit are kept independent except at one controlled point configured so that digital ground currents don't enter any parts of the analog circuit. This is often back at the bulk smoothing/filter capacitor at the output of the power supply.


text:
Q: SVN how to resolve "local add, incoming add upon update" on a *folder*? Here is my scenario:
Assume we have an SVN repo with the following content:
myfolder
myfolder\file.txt
Now I create two checkouts of this repo, co1 and co2.
In co1 we modify file.txt.
In co2 we:

*

*svn delete myfolder

*svn commit

*Create a new folder named myfolder

*svn add myfolder

*svn commit

Now if I attempt an update in co1 I get a tree conflict:
A  +  C myfolder >   local edit, incoming delete upon update
M  +    myfolder\file.txt

I want to keep myfolder and the modified file, so I resolve the tree conflict:
svn resolve --accept working folder

Now if I try to commit, I get "svn: Directory '/myfolder' is out of date". If I try to resolve this using svn up myfolder, I get a tree conflict again:
A  +  C folder >   local add, incoming add upon update
M  +    myfolder\file.txt

Okay, so we try svn resolve --accept working folder again. But we still can't commit, we get the same message that "svn: Directory '/myfolder' is out of date", if we do svn up myfolder, we get right back to the last tree conflict.
What is the correct procedure to resolve this type of conflict (when we wish to keep myfolder and its changes)?
EDIT: Windows cmd line script to illustrate:
rmdir /S /Q C:\svntest
mkdir C:\svntest

cd C:\svntest

svnadmin create repo

svn co file:///c:/svntest/repo co1
svn co file:///c:/svntest/repo co2

cd co1
mkdir folder
echo content > folder\file.txt
svn add folder
svn commit folder -m ""

cd C:\svntest\co2
svn up

cd C:\svntest\co1
svn del folder
svn commit -m ""
mkdir folder
svn add folder
svn commit -m ""

cd C:\svntest\co2
echo changed_content > folder\file.txt
svn up
svn resolve --accept working folder
svn commit -m ""

svn up folder
svn resolve --accept working folder
svn commit -m ""

And here is the output of running that script (note the commit failures at the end):
C:\>rmdir /S /Q C:\svntest

C:\>mkdir C:\svntest

C:\>cd C:\svntest

C:\svntest>svnadmin create repo

C:\svntest>svn co file:///c:/svntest/repo co1
Checked out revision 0.

C:\svntest>svn co file:///c:/svntest/repo co2
Checked out revision 0.

C:\svntest>cd co1

C:\svntest\co1>mkdir folder

C:\svntest\co1>echo content  1>folder\file.txt

C:\svntest\co1>svn add folder
A         folder
A         folder\file.txt

C:\svntest\co1>svn commit folder -m ""
Adding         folder
Adding         folder\file.txt
Transmitting file data .
Committed revision 1.

C:\svntest\co1>cd C:\svntest\co2

C:\svntest\co2>svn up
A    folder
A    folder\file.txt
Updated to revision 1.

C:\svntest\co2>cd C:\svntest\co1

C:\svntest\co1>svn del folder
D         folder\file.txt
D         folder

C:\svntest\co1>svn commit -m ""
Deleting       folder

Committed revision 2.

C:\svntest\co1>mkdir folder

C:\svntest\co1>svn add folder
A         folder

C:\svntest\co1>svn commit -m ""
Adding         folder

Committed revision 3.

C:\svntest\co1>cd C:\svntest\co2

C:\svntest\co2>echo changed_content  1>folder\file.txt

C:\svntest\co2>svn up
C folder
At revision 3.
Summary of conflicts:
  Tree conflicts: 1

C:\svntest\co2>svn resolve --accept working folder
Resolved conflicted state of 'folder'

C:\svntest\co2>svn commit -m ""
Adding         folder
svn: Commit failed (details follow):
svn: Directory '/folder' is out of date

C:\svntest\co2>svn up folder
   C folder
At revision 3.
Summary of conflicts:
  Tree conflicts: 1

C:\svntest\co2>svn resolve --accept working folder
Resolved conflicted state of 'folder'

C:\svntest\co2>svn commit -m ""
Adding         folder
svn: Commit failed (details follow):
svn: Directory '/folder' is out of date

A: Try
C:\svntest\co2>move folder folder.SAVE
C:\svntest\co2>svn revert folder
C:\svntest\co2>svn update

Svn should then bring in a fresh folder directory version identical with the one from co1. You can then overwrite with the content from folder.SAVE.

A: I figured out with
svn resolve --accept working  PATH_TO_FILE

which should end up with:
Resolved conflicted state of 'PATH_TO_FILE'

A: Tree Conflicts gives a nice overview of tree conflicts and their resolution. In some cases svn revert might help as well, while loosing all your local modifications. As last resort a new working copy with manually merged changes from the 'broken' one will bring you back on track. Definitely the dark side of subversion.

A: I am not able reproduce what you have mentioned. Here is what I have tried.
test@test:/tmp$ cd /tmp/
test@test:/tmp$ svn co http://localhost:8080/svn/stackoverflow so --username=admin
A    so/trunk
A    so/branches
A    so/tags
Checked out revision 1.
test@test:/tmp$ cd so/trunk/
test@test:/tmp/so/trunk$ mkdir x
test@test:/tmp/so/trunk$ ls /tmp > x/test.txt
test@test:/tmp/so/trunk$ svn add x/
A         x
A         x/test.txt
test@test:/tmp/so/trunk$ svn ci -m "test"
Adding         trunk/x
Adding         trunk/x/test.txt
Transmitting file data .
Committed revision 2.
test@test:/tmp/so/trunk$ cd /tmp/
test@test:/tmp$ svn co http://localhost:8080/svn/stackoverflow so1 --username=admin
A    so1/trunk
A    so1/trunk/x
A    so1/trunk/x/test.txt
A    so1/branches
A    so1/tags
Checked out revision 2.
test@test:/tmp$ cd /tmp/so1/trunk/
test@test:/tmp/so1/trunk$ svn remove x
D         x/test.txt
D         x
test@test:/tmp/so1/trunk$ svn ci -m ""
Deleting       trunk/x

Committed revision 3.
test@test:/tmp/so1/trunk$ mkdir x
test@test:/tmp/so1/trunk$ cp ../../so/trunk/x/test.txt x
test@test:/tmp/so1/trunk$ ll /tmp > x/test.txt
test@test:/tmp/so1/trunk$ svn add x/
A         x
A         x/test.txt
test@test:/tmp/so1/trunk$ svn ci -m ""
Adding         trunk/x
Adding         trunk/x/test.txt
Transmitting file data .
Committed revision 4.
test@test:/tmp$ cd so/trunk/
test@test:/tmp/so/trunk$ svn up
D    x
A    x
A    x/test.txt
Updated to revision 4.
test@test:/tmp/so/trunk$

Apparently I tried the same approach which you did and did not face any problem again. What version of svn are you using ?
export REPOPATH=/tmp/svntest
test@test:/tmp/co2/trunk$ rm -rf $REPOPATH
test@test:/tmp/co2/trunk$ mkdir $REPOPATH
test@test:/tmp/co2/trunk$ svnadmin create $REPOPATH/repo
test@test:/tmp/co2/trunk$ svn co file:///$REPOPATH/repo co1
svn: Repository UUID '2d803eb8-2030-4dd3-bb6f-34ab07c74813' doesn't match expected UUID '82764ae8-6410-4565-933f-9a420cb60013'
test@test:/tmp/co2/trunk$ svn co file:///$REPOPATH/repo co2
svn: Repository UUID '2d803eb8-2030-4dd3-bb6f-34ab07c74813' doesn't match expected UUID '82764ae8-6410-4565-933f-9a420cb60013'
test@test:/tmp/co2/trunk$
test@test:/tmp/co2/trunk$ cd $REPOPATH/co1
bash: cd: /tmp/svntest/co1: No such file or directory
test@test:/tmp/co2/trunk$ mkdir folder
mkdir: cannot create directory `folder': File exists
test@test:/tmp/co2/trunk$ echo content > folder/file.txt
test@test:/tmp/co2/trunk$ svn add folder
svn: warning: 'folder' is already under version control
test@test:/tmp/co2/trunk$ svn commit folder -m ""
test@test:/tmp/co2/trunk$
test@test:/tmp/co2/trunk$ cd $REPOPATH/co2
bash: cd: /tmp/svntest/co2: No such file or directory
test@test:/tmp/co2/trunk$ svn up
At revision 10.
test@test:/tmp/co2/trunk$
test@test:/tmp/co2/trunk$ cd $REPOPATH/co1
bash: cd: /tmp/svntest/co1: No such file or directory
test@test:/tmp/co2/trunk$ svn del folder
svn: Use --force to override this restriction
svn: 'folder/file.txt' is not under version control
test@test:/tmp/co2/trunk$ svn commit -m ""
test@test:/tmp/co2/trunk$ mkdir folder
mkdir: cannot create directory `folder': File exists
test@test:/tmp/co2/trunk$ svn add folder
svn: warning: 'folder' is already under version control
test@test:/tmp/co2/trunk$ svn commit -m ""
test@test:/tmp/co2/trunk$
test@test:/tmp/co2/trunk$ cd $REPOPATH/co2
bash: cd: /tmp/svntest/co2: No such file or directory
test@test:/tmp/co2/trunk$ echo changed_content > folder\file.txt
test@test:/tmp/co2/trunk$ svn up
At revision 10.
test@test:/tmp/co2/trunk$ svn --version
svn, version 1.6.6 (r40053)
   compiled Dec 12 2009, 05:04:54

Copyright (C) 2000-2009 CollabNet.
Subversion is open source software, see http://subversion.tigris.org/
This product includes software developed by CollabNet (http://www.Collab.Net/).

The following repository access (RA) modules are available:

* ra_neon : Module for accessing a repository via WebDAV protocol using Neon.
  - handles 'http' scheme
  - handles 'https' scheme
* ra_svn : Module for accessing a repository using the svn network protocol.
  - with Cyrus SASL authentication
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme

A: In this particular case, I think you'll have to re-apply the local changes manually. That is, create a patch file (svn diff > mine.patch, or copy files somewhere else), revert your changes or resolve using theirs, then apply the patch (or copy files back). Perhaps you will need to svn copy the base of your files back in the recreated folder before applying your changes.
Like zellus said, it's the dark side of subversion, and this is something the current implementation is unable to handle. Then again, deleting a folder and adding an identically named one back in doesn't sound quite right. What would you expect subversion to do? What if the file is not recreated in the folder? What if its content is different?
Try avoiding the situation altogether by not deleting a folder you want to keep :)


text:
Q: How can I run composer install --dev on Heroku? How can I override default Heroku behavior about dependencies installation with Composer? AFAIK Heroku executes composer install --no-dev by default which is perfect for prod, but what if I intend to deploy PHP application in dev environment on the Heroku server?
So I need somehow to load dependencies from require-dev section of composer.json. Is it possible? Are there any hooks, events, etc. that could help me with it?

A: Access heroku shell with command heroku run bash --app=app-dev in terminal
So, update composer components with composer update --dev


text:
Q: how to add \n before 4th pipe and after last double Quotes in a file in unix I have a line in a file. like:

*

*1|4|ab|"abnchf "dnvjnkjf" fdvjnfkjnv" 2|12|df|"dskfnkfv "A"

I want to break the into two rows by adding \n at before 4th pipe and after last double quotes.
it should be like:

*

*1|4|ab|"abnchf "dnvjnkjf" fdvjnfkjnv"
2|12|df|"dskfnkfv "A"
i have tried sed command but its not working
sed 's/\(|[^|]*\)(|[^|]*\)(|[^|]*\)|/\1\n|/g'

A: You may use
sed 's/\([^|]*|\)\{3\}[^|]* /&\n/' file > newfile

See the online demo
Details

*

*\([^|]*|\)\{3\} - three consecutve occurrences of

*

*[^|]* - 0+ chars other than |

*| - a pipe symbol

*[^|]* - 0+ chars other than |

*  - a space

The replacement pattern is &\n, the whole match (&) and a newline (\n).
The replacement is only done once per line since I removed the g option.
To avoid overescaping, you may use a POSIX ERE based sed:
sed -E 's/([^|]*\|){3}[^|]* /&\n/' file > newfile

where you do not need to escape capturing parentheses and range/interval quantifier braces (but you have to escape a literal | char).

A: This might work for you (GNU sed):
sed 's/[^ |]*|/\n&/4' file

Insert a newline before the fourth field delimited by |.