text:
Q: What happens if a UITableViewCell is not released? What will happen if the autorelease is removed from cell creation in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

STVCell *cell = (STVCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[STVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
}

A: It will lead to a memory leak.
Because you call alloc, you are responsible for also calling release (or in this case autorelease).
The UITableView will automatically retain the cell and release its use of the cell at the appropriate time, but unless your code also releases the reference that it holds, the cell can never be deallocated.

A: Nothing. And that's a bad thing: The cell will never be released and become a memory leak.


text:
Q: How can I create a recursive function in LISP that counts the number of times an atom occurs in a nested list Just started learning lisp and I need to write a function, COUNTER, that would do as mentioned in the title. For example,
(COUNTER 'fizz '(fizz (buzz (fizz) (buzz fizz)) fizz))

should return 4
First try
I've written the following
(defun COUNTER (atom list)
  (cond
   ((null list) 0)
   ((equal atom (first list)) (+ 1 (COUNTER atom (rest list))))
   (t (COUNTER atom (rest list)))))

Which only counts the atom at the top most level (in the case of the example, my output is 2). What do I need to add to have it read the nested lists? I know I should be traversing the sublist and sum the results, but I'm not exactly sure which predicate I should be using and where exactly I should place it. I'm thinking right after
((equal atom (first list)) (+ 1 (COUNTER atom (rest list))))

Second try
I have tried the following to no avail
(defun COUNTER (target nest_list)
  (cond ((null nest_list) 0)
    (cond (atom (first nest_list) ((equal target (first nest_list)) (+ 1 (COUNTER target (rest nest_list)))))
      (t (COUNTER target (first nest_list))))
    (t (COUNTER target (rest nest_list)))))

I am receiving compilation errors from it. The logic to me seems to make sense. I'm testing to see whether the entity is an atom or a list, if atom, then see if it's equal and add 1, otherwise recur if it's a list. I'm not sure if I'm doing something wrong with the parenthesis placement or whether I'm allowed to use a cond within a cond like that.

A: You can close over a counter to avoid passing too many parameters.
Also, you probably should pass a custom test function like CL functions do.
(defun counter (search tree &key (test #'eql))
  (let ((total 0))
    (labels
        ;; Our tree walker. Both counter and search are accessible
        ;; from the lexical environment, so there is no need to
        ;; pass them as arguments.
        ((walk (tree)
           (cond
             ;; First, see if current element matches the search.
             ;; That allows to search for a list inside a tree.
             ((funcall test tree search) (incf total))

             ;; Otherwise, if this is a cons-cell, recurse in CAR and CDR
             ((consp tree)
              (walk (car tree))
              (walk (cdr tree))))))

      ;; Initiate walk
      (walk tree)

      ;; Return total
      total)))

If this is a homework, I don't think this could satisfy your requirements (you are probably expected to provide a purely recursive function). However, if you understand the above, it should not be hard to build a recursive approach that never mutates variables.
For reference:

*

*LABELS: local, possibly recursive, functional bindings

*COND : generalized, cascading if

*LET : local variable bindings

*&KEY : named arguments in lambda lists

*INCF : increment place

*What's the difference between eq, eql, equal, and equalp in Common Lisp?
Example
(counter '(3 2)
         '(a b (c d 3) (3 2) e f)
         :test #'equalp)
=> 1

(counter 3 '(a b (c d 3) (3 2) e f))
=> 2

A: You also need to check whether first list is, itself, an atom or a list.  If it's an atom, then your current logic is correct; if it's a list, then you also need to recur on this list.
I removed my comment about parameter names, since it's not a problem in most full-featured LISP versions.  Thanks to coredump for the correction.
(defun COUNTER (target nest_list)
  (cond ((null nest_list) 0)
    (cond (atom (first nest_list))
      (equal target (first nest_list)) (+ 1 (COUNTER target (rest nest_list))))
      (t (COUNTER target (rest nest_list)))))

Now, in the else branch of the new cond, insert another recursion:
(COUNTER (target (first nest_list)))

You'll need to add this (instead of 1) to the count for (rest nest_list).  Does this get you moving?  I know I haven't been careful with my structure, but I'm trying to avoid doing the job for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any shorter version for checking both empty and/or null string in Dart? I saw many similar questions but I haven't found one which satisfy the question I'm asking now.
So suppose I have 3 maps like these:
final map1 = {name: Bill, age: 34, nickname: ''};
final map2 = {name: John, age: 50};
final map3 = {name: Dan, age: 21, nickname: 'Avengers'};

I want to be able to check whether nickname is null or empty so I check like this:
if(map[nickname] != null && map[nickname] != '')

Or
if(map[nickname] == null || map[nickname] == '')

I had to use two conditional checks every time.
Is there a way in Dart so we can shorten this into one condition check?
Thanks and I apologize if this is a duplicate of some other question but I have searched a a bunch of similar questions without finding anything exactly for Dart yet.

A: if (['', null].contains(map[nickname]))

is the shorter version of
if(map[nickname] == null || map[nickname] == '')

This method uses the contains method of the List class, which returns true if the collection contains an element equal to the input. So if your input String is either null or empty, it returns true.

A: You can write an extension for this
void main() {
  String str;
  print(str.isNotNullAndNotEmpty);
}

extension on String {
  bool get isNotNullAndNotEmpty => this != null && this.isNotEmpty;
}


text:
Q: jQuery - Rename elements Got a div whose ID="cartArea" in there I have mulitple textbox
<input type="text" id="tb_1" name="tb_1" />
<input type="text" id="tb_2" name="tb_2" />
<input type="text" id="tb_3" name="tb_3" />

and so on, there could be more or less items in the list.  Beside each textbox there is a remove option. I can get the selected textbox to be removed from the container div no problem, but what I need to be able to do is then rename the remaining textboxes.
So if I remove tb_2, I'm not left with tb_1 and tb_3, but rather tb_1 and tb_2
Can this be done and if so how?

A: Put this code in some function and call that function after deleting element.
Try this, Live Demo
 $('#cartArea').children('input[type=text]').each(function(){

    this.name ='tb_' + eval($(this).index()+1);
    //alert( this.name)
  });

A: You can achieve your goal very simply like following:
$('#cartArea input[type=text]').attr('id', function(){
  return 'tb_' + $(this).index();  // change id
}).attr('name', function() {
  return 'tb_' + $(this).index();  // change name
});

DEMO

A: Afer you remove, you can run this code to rename them:
$('input[id^=tb_]').each(function(i, v){ this.name = 'tb_' + i; });

A: After deletion you can loop through remaining element and change there name attr
Sample HTML:
<input type="text" id="tb_1" name="tb_1" />remove
<input type="text" id="tb_2" name="tb_2" />remove
<input type="text" id="tb_3" name="tb_3" />remove

Sample Code:
jQuery('span').click(function(){
   jQuery(this).prev().remove();
   jQuery(this).remove();
    jQuery('input').each(function(index){
       jQuery(this).attr('name','tb_' + (index +1));
    });
});

JSFiddle

A: I didn't like others responses because they either used the costly input[id^=] selector, the wordy input[type=text] selector, didn't account for i-being 0 based or didn't set the name attribute.
You can run this code after removal to rename the textboxes.
$('#cartArea input:text').each(function(i){ this.id = this.name = 'tb_' + (i + 1); });

JSFiddle: http://jsfiddle.net/HT6gS/

A: No need for a quirky javascript solution here.
Just do it like:
<input type="text" id="tb_1" name="tb[]" />
<input type="text" id="tb_2" name="tb[]" />
<input type="text" id="tb_3" name="tb[]" />

Server side it is accessible via $_GET['tb'] which is an array. So $_GET['tb'][0], $_GET['tb'][1] and $_GET['tb'][2] representing your data if you sent 3 inputs to the server.


text:
Q: radio button inside dropdown bootstrap i have this dropdown from bootstrap:

i insert radio button inside of the dropdown but if u can see the radio button inside dosnt have style, i want the same color when is showing the radio button inside of dropdown.
this is the html from dropdown:

            <button class="btn btn-default dropdown-toggle botn-todos" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Todos

            </button>

<input value="1" name="busqueda1" type="radio" class="todoss"> Todos

<input value="1" name="busqueda1" type="radio" class="enc"> En camino

<input value="1" name="busqueda1" type="radio" class="enca"> En camino - 2do intento

<input value="1" name="busqueda1" type="radio" class="entre"> Entregado

<input value="1" name="busqueda1" type="radio" class="entre2"> Entregado al 2do intento

<input value="1" name="busqueda1" type="radio" class="nose"> No se puede entregar

<input value="1" name="busqueda1" type="radio" class="cancelado"> Cancelado

and this is my script code when is clicking the item:
$('.dropdown-menu').on( 'click', 'a', function() {
                var text = $(this).html();
                alert(text);
                var htmlText = text + ' ';
                $(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);
            });

this is the css for every radio button:
li:first-child input[type='radio']{
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #6a706d;
    border-radius:50%;
    outline:none;
    margin: 0 13px -3px 0;
    /*box-shadow:0 0 5px 0px #6a706d inset;*/
    }
    li:first-child input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:first-child input[type='radio']:checked:before {
        background:#6a706d;
    }
    li:nth-child(2) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #f1d04d;
    border-radius:50%;
    outline:none;
     margin: 0 13px -3px 0;
    }

    li:nth-child(2) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(2) input[type='radio']:checked:before{
        background:#f1d04d;
    }

    li:nth-child(3) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #caaf40;
    border-radius:50%;
    outline:none;
    /*box-shadow:0 0 5px 0px #caaf40 inset;*/
    margin: 0 13px -3px 0;
    }

    li:nth-child(3) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(3) input[type='radio']:checked:before{
        background:#caaf40;
    }

    li:nth-child(4) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #92d04f;
    border-radius:50%;
    outline:none;
    /*box-shadow:0 0 5px 0px #92d04f inset;*/
    margin: 0 13px -3px 0;
    }

    li:nth-child(4) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(4) input[type='radio']:checked:before{
        background:#92d04f;
    }

    li:nth-child(5) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #7aaf42;
    border-radius:50%;
    outline:none;
    /*box-shadow:0 0 5px 0px #7aaf42 inset;*/
    margin: 0 13px -3px 0;
    }
    li:nth-child(5) input[type='radio']:hover {
        box-shadow:0 0 5px 0px #7aaf42 inset;
    }
    li:nth-child(5) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(5) input[type='radio']:checked:before{
        background:#7aaf42;
    }

    li:nth-child(6) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #ed5850;
    border-radius:50%;
    outline:none;
    /*box-shadow:0 0 5px 0px #b70218 inset;*/
    margin: 0 13px -3px 0;
    }

    li:nth-child(6) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(6) input[type='radio']:checked:before{
        background:#ed5850;
    }

    li:nth-child(7) input[type='radio'] {
    -webkit-appearance:none;
    width:15px;
    height:15px;
    border:3px solid #b70218;
    border-radius:50%;
    outline:none;
    /*box-shadow:0 0 5px 0px #b70218 inset;*/
    margin: 0 13px -3px 0;
    }
    li:nth-child(7) input[type='radio']:before {
        content:'';
        display:block;
        width:60%;
        height:60%;
        margin: 20% auto;
        border-radius:50%;
    }
    li:nth-child(7) input[type='radio']:checked:before{
        background:#b70218;
    }


text:
Q: Can i reuse a for loop for multiple functions? I would like to reuse a for loop which loops over a querySelectorAll variable I have named 'allRooms' I'm just not to sure how to. I want to be able to play around with adding/removing classes on the elements in the loop. In my code below i have used the same for loop twice as you will see although its executing different things its still looping over the same 'allRooms' variable which is what I want to avoid doing. Appreciate any help, I'm still learning javascript.
This is the effect im using the javascript for
https://iamrufus.github.io/

(function() {
  let roomsWrap = document.querySelector('.rooms__wrap');
  let roomImg = document.querySelectorAll('.rooms__img');
  let allRooms = document.querySelectorAll('.rooms__type');
  let roomType;

  roomsWrap.addEventListener('mouseover', function(e) {
    reset();
    if (e.target.classList.contains('rooms__type')) {
      roomType = e.target.dataset.room;
      roomImg[roomType].classList.add('active');
      e.target.classList.add('active');
    }
    for (var i = 0; i < allRooms.length; i++) {
      allRooms[i].classList.add('hide');
      e.target.classList.remove('hide');
    }
  });

  roomsWrap.addEventListener('mouseleave', function() {
    reset();
  });

  function reset() {
    for (var i = 0; i < allRooms.length; i++) {
      allRooms[i].classList.remove('active', 'hide');
    }
    for (var i = 0; i < roomImg.length; i++) {
      roomImg[i].classList.remove('active');
    }
  }
})();

      Traditional Suite

      Grande Suite

      Deluxe Suite

A: I wouldn't recommend it but you could wrap the for-loop inside a parameter-driven function, which does different things based on this parameter.
Something like:
function doAllRooms(param, e) {

  for (var i = 0; i < allRooms.length; i++) {
    if (param == 1) {
      allRooms[i].classList.add('hide');
      e.target.classList.remove('hide');
    }
    if (param == 2) {
      allRooms[i].classList.remove('active', 'hide');
    }
  }
}

roomsWrap.addEventListener('mouseover', function(e) {
  doAllRooms(1, e);
});

function reset() {
  doAllRooms(2);
}


text:
Q: Which command can be used to configure a router to reject the address for example 192.168.100.0/24 network using the route command? Which  command can be used to configure a router to reject the address for example 192.168.100.0/24 network using the route command

A: this would be just the right answer:
route add -net 192.168.100.0 netmask 255.255.255.0 reject

A: you can use the firewall to do so
sudo ufw deny from <ip address>


text:
Q: Not able to inject Bean I am trying to inject using a java bean . Its a very basic implementation however the injection is not working. Could you please guide me?
test.java
 public class TempClass{
@Autowired
        HashMap<String,HashMap<String,String>> newMap = new HashMap<String,HashMap<String,String>>();

        public void setNewMap(HashMap<String, HashMap<String,String>> newMap)
        {
            newMap= newMap;
        }

        public HashMap<String, HashMap<String,String>> getNewMap()
        {
            return newMap;
        }
    }

Also:
for my bean config conn.xml
       <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <util:map id="xyz" map-class="java.util.HashMap">
        <entry key="x" value-ref="x" />
        <entry key="y" value-ref="y" />
        <entry key="z" value-ref="z" />
    </util:map>

    <util:map id="x" map-class="java.util.HashMap">
        <entry key="xx" value="xx" />
        <entry key="xy" value="xy" />
        <entry key="xz" value="xz" />
    </util:map>

    <util:map id="y" map-class="java.util.HashMap">
        <entry key="yx" value="yx" />
        <entry key="yy" value="yy" />
        <entry key="yz" value="yz" />
    </util:map>

    <util:map id="z" map-class="java.util.HashMap">
        <entry key="zx" value="zx" />
        <entry key="zy" value="zy" />
        <entry key="zz" value="zz" />
    </util:map>

 <bean id="bean123" class="reference.to.class" autowire="byName">
      <property name="newMap" ref="xyz" />
   </bean>

</beans>

Could someone guide me as to what is wrong?

A: The @Autowired annotation should be above the field you want to inject. And that field shouldn't be assigned only declared.
Also, injecting a map isn't the easiest example to start with. You should write a simpler test case just to get the hang of it. For example,
package test;
public class SpringInjectionTest {
    @Autowired
    private String injectThis;

    public void setInjectThis(String s) {
         injectThis = s;
    }

    public String getInjectThis() {
         return injectThis;
    }
}

And here's the applicationContext:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config />

    <bean id="testBean" class="test.SpringInjectionTest" autowire="byName"/>
</beans>

A: You have two possible fixes:
a. Declare your newMap as being of type Map<String, Map<String, String>> not concrete Hashmap, this is because internally util:map returns an object type of Map and autowiring will not be able to find suitable candidates.
b. Remove the @Autowired from newMap and instead inject the dependency directly through xml, the way you have done:
<bean id="bean123" class="...">
   <property name="newMap" ref="xyz" />
</bean>


text:
Q: Access Private Docker Registry with a DoD CAC We have a privately hosted docker repo that we wish to protect with "2-factor" authentication via DoD CAC (PKI, PIV, X.509, Smart Card).
Setting up an HTTPS reverse proxy in front of the docker repo (in our case NexusOSS-based) that requires DoD CACs is simple,
but I don't see an obvious way to have the docker pull command interact with a the CAC reader hardware.


text:
Q: javascript- How do I create a global variable among all pages I implemented a toggle in my home page through javascript in content editor web part, the toggle has state between 1 and 0. Now I need the exact same toggle in all other pages of my site, but I'm not sure how to share the data about the current state of toggle among all the pages.
For instance, if I change the toggle from "0" to "1" in page A, I would like to see the state of toggle to be "1" in page B, page C, page D ...
How do I share one javascript Boolean variable among all pages in my sharepoint site?
here's the code in my content editor web part:
<button id="toggle" type="button" class= "button" value="True">True</button>

    <button id="toggle" type="button" class= "button" value="True">True</button>

A: You can access the Site's Property Bag using the JavaScript Client Object Model.
Here's a walkthrough:
http://www.jeremythake.com/2013/10/using-the-sharepoint-csom-api-to-get-a-property-bag-value/

A: A few options:

*

*Write the value to a list on the site (it may only have a couple of columns and a single row if it's just storing one value) and read that.

*Create a single frame in the window and use JavaScript to navigate through the pages. You can either read from this frame's JavaScript or by tacking a query string onto the links on the page and reading it from the URL on the target.

You may be better off with server side code (ASP or .NET) if it's going to be everywhere and you don't want to have to code everywhere.

A: If all these pages are on the same site you could look at using the sites property bag.
Read in Property Bag values
var ctx = new SP.ClientContext.get_current();
var site = ctx.get_site();
var web = site.get_rootWeb();
var webProp =  web.get_allProperties();
ctx.load(web);
ctx.load(this.props);
ctx.executeQueryAsync();

To set the property
webProp.set_item("<PropertyName>", true);
web.update();
ctx.executeQueryAsync();

If you are setting this one time - you can actually use SharePoint Designer to create and set the property and then just read in the value in your webpart.  If you need to persist across sites - then you need to look at server side assistance for things like:
Storing value in web.config
Storing values in farm level property bag.
Enabling the ASP.NET Session State which uses SQL to persist values.


text:
Q: python code automatically open raspberry pi i have raspberry pi3 raspbian(os)i have some kind of python code (it is related pi camera) i want to start automatically when raspberry pi start is it possible ?
from picamera import PiCamera
from time import sleep

camera = PiCamera()

camera.start_preview()
sleep(10)
camera.stop_preview()

A: You can put #!/bin/env python on top of your file, then make it executable with chmod +x <filename> and then call it from /etc/rc.local. rc.local is run whenever that system boots.


text:
Q: Git: Ignore tracked files I have some tracked files in a repository which are automatically modified when building the code. I don't want to untrack them, I just don't want them to appear as modified and I don't want them to be staged when I git add.
Is this possible?

A: An another solution using git attributes and %f in filter command:
git config filter.orig.clean "cat %f.orig"
cp filename filename.orig
echo "filename filter=orig" >> .git/info/attributes
echo "filename.orig" >> .git/info/exclude

A: Sure.
git update-index --assume-unchanged [<file> ...]

To undo and start tracking again:
git update-index --no-assume-unchanged [<file> ...]

A: The accepted answer is not correct. --assume-unchanged only causes Git to skip certain (sometimes expensive) file system checks -- it doesn't guarantee that Git shows the file as "unchanged".
The same command but with the option --skip-worktree, however, does work. So to prevent a tracked but changed file from appearing as changed in the Git status, use
git update-index --skip-worktree [<file> ...]

To undo and start showing it as changed again:
git update-index --no-skip-worktree [<file> ...]

See also the cited email from a Git maintainer in this answer, the Git documentation git-update-index, and FallenGameR's blog entry about how the two react to different scenarios.

A: Another approach (from a now deleted answer by Seth Robertson, but I found it helpful so resurrecting it) is to maintain a "tracked" template file, then have local untracked version of it, ex: "config.sample.ini" or "config.ini.template" see https://gist.github.com/canton7/1423106 for a full example.
Then there won't be any concerns if the file is changed within git, etc. and you can use .gitignore (finally) on the local untracked files.


text:
Q: $C^1$ surjective map from $\Bbb{R}\to\Bbb{R}^2$? I now there is a continuous surjective map from $\Bbb{R}\to\Bbb{R}^2$ thanks to Peano curve.
My question is simple: does there exist a $C^1$ surjective map from $\Bbb{R}\to\Bbb{R}^2$ ? I think that the answer is no and I have seen this long time ago but I was too young to understand the proof. Unfortunately I cannot think of a proof now.
Any idea ?

A: The image of a $C^1$ map from $\Bbb R$ to $\Bbb R^2$ has Lebesgue measure zero, so it cannot be surjective, nor have non-empty interior.

A: Notation: $f''S=\{f(x):x\in S\}$ when $S$ is a subset of the domain of $f.$
Let $f:\Bbb R\to \Bbb R^2$ be a continuous surjection.  For $n\in \Bbb Z,$ each $[n,n+1]$ is compact so $f''[n,n+1]$ is compact and therefore closed in $\Bbb R^2.$ Since $\Bbb R^2=\cup_{n\in \Bbb Z}f''[n,n+1],$ the Baire category theorem implies that some $f''[n,n+1]$ has non-empty interior. So for some $n$ we have $f''[n,n+1]\supset [a,a+b]\times [a',a'+b']$  with positive $b,b'$.
To simplify the notation we will assume WLOG (by a change of scale and a change of variable)  that $f''[0,1]\supset [0,1]^2.$
For $1<n\in \Bbb N,$ consider $[0,1]^2$ as an  $n\times n$ checkerboard of closed sub-squares  with sides of length $1/n.$  Let $C_n$ be the set of centers of these sub-squares. (The point is that $C_n$ has $n^2$ members and if $(u,v),(u',v')$ are distinct members of $C_n$ then $|u-u'|\geq 1/n$ or $|v-v'|\geq 1/n$...or both).
Let $B_n \subset [0,1]$ where $B_n$ has $n^2$ members and $f''B_n=C_n.$  Choose distinct $x_n,x'_n\in B_n$ such that $|x_n-x'_n|\leq (n^2-1)^{-1}.$  Let $f(x_n)=(u_n,v_n)$ and $f(x'_n)=(u'_n,v'_n).$ We have $|u_n-u'_n|\geq 1/n$ or $|v_n-v'_n|\geq 1/n$ (or both).
Let $A$ be an infinite subset of $\Bbb N$ \ $\{1\}$ such that $\forall n\in A\;(|u_n-u'_n|\geq 1/n)$ or $\forall n\in A\; (|v_n-v'_n|\geq 1/n\} .$
WLOG assume $\forall n\in A\; (|u_n-u'_n|\geq 1/n).$
Suppose $f$ were continuously differentiable. Then with $f(x)=(f_1(x),f_2(x)),$ the function $f'_1(x)$ is continuous. Now  $\frac {f_1(x_n)-f_1(x'_n)}{x_n-x'_n}= f'_1(y_n)$ for some $y_n$ between $x_n$ and $x'_n$ by the MVT.
For all $n\in A$ we have $|f'_1(y_n)|=$ $\frac {|u_n-u'_n|}{|x_n-x'_n|}\geq$ $ \frac {1/n}{(n^2-1)^{-1}}=n-n^{-1}.$
But $A$ is infinite; therefore  $\{|f'_1(x)|: x\in [0,1]\}$ is unbounded  above, which is impossible if $f'_1$ is continuous.


text:
Q: Генерация случайных чисел с дискретным распределением вероятностей Как на java сгенерировать одно из двух случайных чисел. Генерировать надо только 2 или 4. Прчем генерировать надо с задааной вероятностью — 90 процентов генерация 2ки и с 10 процентной вероятностью генерация 4ки.

A: В общем случае решается как-то так:
Random r = new Random(); // заведите общий экземпляр на программу

double total = 90 + 10;
double random = r.nextDouble() * total;
if (random < 90)
    return 2;
else
    return 4;

Решение естественным образом обобщается на массив значений и «весов»:
double total = DoubleStream.of(weight).sum();
double random = r.nextDouble() * total;
for (int i = 0; i < N; i++)
{
    random -= weight[i];
    if (random < 0)
        return value[i];
}


text:
Q: Add a CAShapeLayer between annotation and MKMapView I'm trying to add an animation below the annotations of my MKMapView but with no luck.
I tryed to change the CAShapeLayer zPosition but the circle end up below the map.
Here is my current code to add the animation to the map:
int radius = 55;
CAShapeLayer *circle = [CAShapeLayer layer];

circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
                                         cornerRadius:radius].CGPath;

circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
                              CGRectGetMidY(self.view.frame)-radius);

circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor blackColor].CGColor;
circle.lineWidth = radius*2;
circle.opacity = 0.5;

[self.mapView.layer addSublayer:circle];

CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration            = 2.5; // "animate over 10 seconds or so.."
drawAnimation.repeatCount         = 100.0;  // Animate only once..
drawAnimation.removedOnCompletion = YES;   // Remain stroked after the animation..

drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue   = [NSNumber numberWithFloat:1.0f];

functionWithName:kCAMediaTimingFunctionEaseIn];

[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

A: After 3 days without an answer I decided to remove my annotation from the mkview and put the animation and the image corresponding to the annotation in another view, above the map.


text:
Q: Octopus Deploy - SQL - Execute Scripts Ordered step giving Exception In Octopus deploy I have added a step in process to run the stored procedure with library script "SQL - Execute Scripts Ordered step".
When I'm providing the script to execute the stored procedure it is throwing the below Exception:

Exception calling "ReadAllText" with "1" argument(s): "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."
Closing connection

I believe this is because of the large script as text I've provided to execute in field "SQL Script File".
As shown in examples I can run script directly. So I'm providing the stored procedure execution script but in library's PowerShell scipt -
$content = [IO.File]::ReadAllText($OctopusParameters['SqlScriptFile'])

ReadAllText is expecting something less than 260 characters.
One solution I can think of is to provide the execution script as a file within package itself. But this will be the last resort.
How can I run the stored procedure directly from the step in process?

A: Apparantly [IO.File]::ReadAllText($OctopusParameters['SqlScriptFile']) is expecting file path as SqlScriptFile. I updated the library's powershell script to take the full sql script from field "SQL Script File" as parameter and passed it directly to the function.
$content= $OctopusParameters['SqlScriptFile']
        Execute-SqlQuery -query $content

providing below the full powershell script for reference:
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $OctopusParameters['ConnectionString']
Register-ObjectEvent -inputobject $connection -eventname InfoMessage -action {
    write-host $event.SourceEventArgs
} | Out-Null

function Execute-SqlQuery($query) {
    $queries = [System.Text.RegularExpressions.Regex]::Split($query, "^\s*GO\s*`$", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Multiline)

    $queries | ForEach-Object {
        $q = $_
        if ((-not [String]::IsNullOrWhiteSpace($q)) -and ($q.Trim().ToLowerInvariant() -ne "go")) {
            $command = $connection.CreateCommand()
            $command.CommandText = $q
            $command.CommandTimeout = $OctopusParameters['CommandTimeout']
            $command.ExecuteNonQuery() | Out-Null
        }
    }
}

Write-Host "Connecting"
try {
    $connection.Open()
    Write-Host "Executing script in" $OctopusParameters['SqlScriptFile']
    # $content = [IO.File]::ReadAllText($OctopusParameters['SqlScriptFile'])
    $content= $OctopusParameters['SqlScriptFile']
    Execute-SqlQuery -query $content
}
catch {
    if ($OctopusParameters['ContinueOnError']) {
        Write-Host $_.Exception.Message
    }
    else {
        throw
    }
}
finally {
    Write-Host "Closing connection"
    $connection.Dispose()
}

A: The SQL - Execute Scripts Ordered template is meant to be run against a folder of SQL script files.
The SQL - Execute Script template may be a better match for your scenario.


text:
Q: How to upgrade tensorflow in anaconda environment? I am having TensorFlow version 2.0.0 in my anaconda environment.
I want to upgrade it to an upgraded version.
How can I do it?

A: conda update <package name>

or
conda install <package name>

Note: A second install equals an Override...
Specific to your case:
conda install -c conda-forge -n <environment> tensorflow==<wanted version>


text:
Q: html page with xlsm file as backend I was wondering whether is that possible to have xlsm file as backend while having html as frontend? How can I achieve this if yes?
Thanks in advance.

A: Since the question lacks the understanding of an application structure in the programming realm, I will put this as an answer hoping to clarify a few things.
First of all I don't think you understand what the term "back-end" means.
Please read https://en.wikipedia.org/wiki/Front_and_back_ends AND http://blog.teamtreehouse.com/i-dont-speak-your-language-frontend-vs-backend
hopefully these will clarify a few thing for you.
Just to explain these concepts shortly:
In an application Front-end and back-end refer to two interfaces that communicate with each other and exchange data in some form. Such separation is made when the program and the user are separate (such as when you have a server and a client such as in distributed programming). This however, is only one of many programming patterns today. Although rare in today's world, there are programs that do not separate functionality in such way and thus delegate all this functionality to the core program that is statically installed on the clients computer. But in other cases here is what the terms front-end vs. Back-end means:
Reason why such separation is necessary:
       In today's world many applications (such as web applications and mobile applications) are deployed on common servers to provide wider and faster access, better support and to reduce the cost of access for the client (not requiring any space, no download time etc.). However in such cases, since the client doesn't have access to the program locally, they need to access it over internet protocols such as TCP (which is used by today's http). The problem is that the frontend files are served everytime the application is loaded and can not keep track of states of data (they are stateless) [excluding the edge cases of cookies and caches]
Front End:
         The sole reason that the front end exists for the user to interact with the application and to collect data from the user such as login information etc. (User Interface)
Back end:
          Now back-end is a little bit more complicated. There are 2 major components to a good back-end design:

*

*Logic

*Data

The backend is responsible for processing the data from the user (front-end) in a correct and meaningful way. For example in a really simple program which adds two numbers the front end would be responsible of asking the user for two numbers and the back-end would carry out the actual addition and send the result back to front end to be displayed.
If the data has states. The backend would also need to save the last state of the data somewhere on the server. This is where the second component comes in. The most common practice is to have a ".db" file(s) which represents a database. However there is no obligation for you to do so. When necessary, if you wanted your backend could read data any where from a plain text file to STDIN.
Why do we use databases? ==> The queries. Query languages that come with data bases make it so much easier for us to extract and isolate the relevant data
After processing and modifying the data, the backend sends it back to the front end to be displayed to the user. The common data transferring ways are JSON, XML and SExpressions.
So following this short lecture, back to your question:
Can I have an xlsm file in the backend?
    Yes. You can preserve the data in the backend(server) in anyway that you want. The only thing you need to make sure is that the endpoint the front end communicates to reads data from this file and writes back onto this file. (Sometimes CSV files are used in such a way that is similar to xlsm files)
Is it a good idea?
No. Databases exists for a reason. Use them.
Hope this sheds light on a few things. I highly advise you understand the application stack before writing any code


text:
Q: Running python scripts in blender I am trying to run a script called sun exposure that is written for blender but when I try I am getting this message that is below. What is wrong?
The Message:

File "\exposure.py.001", line50
  print "There are" + str(px_w) + " White pixel, and " + str(px_b) + "black ones."
SyntaxError: invalid syntax
Location: unknown location:1
Python script fail, look in the console for now…

A: Blender uses Python 3, so you need to use brackets in print:
print ("There are" + str(px_w) + " White pixel, and " + str(px_b) + "black ones.")


text:
Q: Remove \cite{ref1} output of [1] I added the references using BibFile1.bib and in BibFile1.bib include the reference label as ref1. My TeX document code is:
\documentclass[12pt,a4paper,oneside]{report}
\begin{document}
\cite{ref1}
\bibliographystyle{IEEEtran}
\bibliography{BibFile1}
\end{document}

In out put first print [1] and then reference information. I need to delete this [1]. What I need to do?

A: If you want to print the bibliography without explicitly citing the references, then you can use \nocite{*}:
\documentclass[12pt,a4paper,oneside]{report}
\begin{document}
\nocite{*}
\bibliographystyle{IEEEtran}
\bibliography{BibFile1}
\end{document}


text:
Q: Where Do I Turn in Queen Endregas Quest? I've killed the cocoons and Queen Endregas but the quest doesn't have a check-box in my journal.  Does this quest turn in somewhere, if so where?

A: You can double-click on quests in your journal to switch them to the tracked quest. Sometimes (but not always) this will label your target objective on both the minimap, and the map page (default: m) itself.
The answer to your question, is Flotsam's Castellan (I think that's his title?) He's on the 2nd floor of the house directly to the left of the eastern Gate out of Flotsam (with Geralt facing towards Lobinden). He's also the one you talk to to complete the Nekker Contract, and he's involved with the first part of the Mystic River quest (finding a royal postbox) as well.


text:
Q: Add vertical lines on non-numerical x-axis in R I want to create a graph in R using the image()-function. My x-axis has non-numerical subdivisions. The axis is divided like this: "Arctic Ocean" - "North Atlantic Ocean" - etc.
How can I add vertical lines to this axis in order to separate different groups on my axis using the abline(v = [value]) function?
This is the code I used to create the image (which works fine):
dev.new()
par(mar = c(9,9,1,1), bg = "grey90")
n.bins <- 24
image(log10(data.stand), col = colorRampPalette(blues9)(n.bins), xaxt = "n", yaxt = "n", useRaster = F)
axis(side = 2, at = 0:(n.taxa.data - 1) / (n.taxa.data - 1), labels = colnames(data.by.tax), las = 1)
axis(side = 1, at = 0:(n.iho.obis - 1) / (n.iho.obis - 1), labels = rownames(data.by.tax), las = 2, cex.axis = 0.5)

I tried implementing the vertical lines using the abline() function, but it doesn't appear on the figure.
Now my question is: how do I implement it correctly in this code? And how can I also make it appear in the figure?
Cheers!!

A: Since you didn't provide x and y arguments to image but only a z matrix, it took by default seq(0,1,nrow(z)) and seq(0,1,ncol(z)) as x and y values. So your vertical lines will have to be expressed in the [0,1] range. Let's say your 10 first columns out of 100 are one group then abline(v=.1) should do the trick. Of course it may be more convenient for you to declare a x and a y directly so you'll have better control on it.


text:
Q: get distance by array of latitude and longitude on google map var path = [
    { "lat": 43.00678, "lng": -89.53743 },
    { "lat": 43.00656, "lng": -89.53732 },
    { "lat": 43.005878, "lng": -89.53797 },
    { "lat": 43.005344, "lng": -89.53684 },
    { "lat": 43.003834, "lng": -89.535400 },
    { "lat": 43.003692, "lng": -89.533834 },
    { "lat": 43.006384, "lng": -89.533796 },
    { "lat": 43.0120328, "lng": -89.533667 },
    { "lat": 43.015931, "lng": -89.533635 },
    { "lat": 43.023030, "lng": -89.5335390 },
    { "lat": 43.032010, "lng": -89.533249 },
    { "lat": 43.040221, "lng": -89.5329596 },
    { "lat": 43.04632176, "lng": -89.5318224 },
    { "lat": 43.052562, "lng": -89.5277883 },
    { "lat": 43.060300, "lng": -89.52759526 },
    { "lat": 43.06401556, "lng": -89.5268978 },
    { "lat": 43.06681381, "lng": -89.5241620 },
    { "lat": 43.0714224, "lng": -89.52499888 },
    { "lat": 43.07468269, "lng": -89.52698371 },
    { "lat": 43.07490213, "lng": -89.53292749 },
    { "lat": 43.076203059, "lng": -89.53269145 },
    { "lat": 43.0765949, "lng": -89.5314576 },
    { "lat": 43.0793377, "lng": -89.53323862 },
    { "lat": 43.0803799, "lng": -89.53454754 },
    { "lat": 43.0835927, "lng": -89.5340754 },
    { "lat": 43.08458789, "lng": -89.5334853 },
    { "lat": 43.0844468, "lng": -89.53403256 },
    { "lat": 43.08445469, "lng": -89.5352985 },
    { "lat": 43.084619242, "lng": -89.5358993791 }
];

this is Javascript array by this I want to draw a polyline on google map for vehicle tracking and find total distance of vehicle trip.

A: The most simple way to calculate the total distance of the path is looping through the path array and calculate the distance between each points with
Haversine formula: https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula or with
google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB); method and summarize the results.
(latter case you must load the geometry library: https://maps.googleapis.com/maps/api/js?libraries=geometry)
e.g.:
function calcPathLength(path){
    var total = 0;
    for (var i = 0; i < path.length - 1; i++) {
        var pos1 = new google.maps.LatLng(path[i].lat(), path[i].lng());
        var pos2 = new google.maps.LatLng(path[i + 1].lat(), path[i + 1].lng());
        total += google.maps.geometry.spherical.computeDistanceBetween(pos1, pos2);
    };
    return total;
};

This gives you only an approximate result, because the distances between two points sometimes too big and the path does not follow the roads precisely.
Another approach to solve this problem is using the Google Maps Roads API snap to roads feature. (https://developers.google.com/maps/documentation/roads/snap) In this case we still have the problem with the distances between the points, because the documentation says that the consecutive pairs of points should be within 300m of each other. I think the best we can do is adding more points to the path.
In the following example I show you how to display and calculate the total distance of your path. I modified the google's Snap to Road demo for your purpose. Please note that the roads API requires an API key, so you should replace the YOUR_API_KEY with your key.
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Roads API Demo</title>

Hope this helps.


text:
Q: Swift Core Data - Save, Populate, Edit an Entity Attribute/Relationship I'm pretty new to iOS dev/Core Data and am having trouble implementing one part of my workflow within my app. See below:

Core Data Properties:

*

*item

*Attributes: title, amount, date, status, category (rel), note (rel)

*note

*Attributes: title, contents, createdAt, updatedAt, item (rel)

When a user creates a new item, all attributes are required, except for .note as I'd like to give the user the option to create a note at a later time if only needed.
What I want to accomplish:

*

*User selects row to display item details

*On item details view, user selects notes (highlighted in yellow above) to go to Add/Edit notes

*The note is just a single object that the user can enter/update the note. So basically, one note per item.

MY CODE
Xcode 11.5, Swift 5
import UIKit
import CoreData

class NoteVC: UIViewController, UITextFieldDelegate, UITextViewDelegate {

//MARK: - Core Data

var item: Item?
var context: NSManagedObjectContext!

//MARK: - Outlets

@IBOutlet weak var headerContainer: UIView!
@IBOutlet weak var headerTitle: UILabel!
@IBOutlet weak var noteView: UIView!
@IBOutlet weak var noteTitleTextField: UITextField!
@IBOutlet weak var noteContentTextView: UITextView!
@IBOutlet weak var noteDataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    setupView()

}

override func viewWillDisappear(_ animated: Bool) {
    super .viewWillDisappear(animated)

    //Update note
    if let title = noteTitleTextField.text, !title.isEmpty {
        item?.notes?.title = title
        item?.notes?.contents = noteContentTextView.text
    }

    item?.notes?.updatedAt = Date()
    item?.notes?.contents = noteContentTextView.text

}
    private func setupView() {

    noteTitleTextField.text = item?.notes?.title
    noteContentTextView.text = item?.notes?.contents
    noteDataLabel.text = DateHelper.convertDate(date: Date())

}

//MARK: - Actions

@IBAction func doneButtonTapped(_ sender: UIButton) {

    item?.notes?.title = noteTitleTextField.text
    item?.notes?.contents = noteContentTextView.text
    item?.notes?.createdAt = Date()
    dismiss(animated: true)

}

}

MY PROBLEM
I'm having an issue creating the new note and assign it to that item and therefore populating the note details for editing. I was able to set the attributes for item.date, .category successfully to another modal view controller (so the passing of data is working), but to no avail with the Notes. Not sure if its because of the relationship or not. Again, I'm a n00b to Core Data so please forgive me for sounding simple.
Any help is appreciated.
Asking for a friend, =P
adrapp

A: Your problem seems to be that you are not creating a Note entity before trying to assign its properties.
The correct pattern to create a note and associate it with your item would be something like this:
if let note = NSEntityDescription.insertNewObject(forEntityName: "note", into: context) as? Note {

    //set note properties
    note.title = noteTitleTextField.text
    note.contents = noteContentTextView.text
    note.createdAt = Date()

    //set relationship to item
    item.note = note
}

Please verify the name of the entity ("note") and class ("Note") match what you defined in your project.
To allow updating an existing note, you need to check first if there is an existing note. You could modify the code above as follows:
// get the existing note, if any, or create a new one
let note = item.note ?? NSEntityDescription.insertNewObject(forEntityName: "note", into: context) as? Note

// if note existed or was successfully created...
if let note = note {
    //set note properties
    note.title = noteTitleTextField.text
    note.contents = noteContentTextView.text

    if item.note == nil {
        note.createdAt = Date()
    }
    else {
        note.updatedAt = Date()
    }

    //set relationship to item
    item.note = note
}


text:
Q: The social-media icon is not visible The social media icon "linkedin" does not show up but it correctly links to my linkedin page. The CSS effects also work correctly. I have tried every possibility but I'm unable to resolve it. How do I fix this? Is the icon that I am using incorrect?
Thanks for suggestions in advance.
Here is my HTML and CSS code :-

html {
  font-size: 20px;
}

body {
  background-color: #ccc;
  padding: 50px;
  text-align: center;
}

/* Wrapper */

.icon-button {
  background-color: white;
  border-radius: 50%;
  cursor: pointer;
  display: inline-block;
  font-size: 2.0rem;
  height: 3.6rem;
  line-height: 3.6rem;
  margin: 0 5px;
  position: relative;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: 3.6rem;
}

/* Circle */

.icon-button span {
  border-radius: 0;
  display: block;
  height: 0;
  left: 50%;
  margin: 0;
  position: absolute;
  top: 50%;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
  width: 0;
}

.icon-button:hover span {
  width: 3.6rem;
  height: 3.6rem;
  border-radius: 3.6rem;
  margin: -1.8rem;
}

.linkedin span {
  background-color: #0077B5;
}

/* Icons */

.icon-button i {
  background: none;
  color: white;
  height: 3.6rem;
  left: 0;
  line-height: 3.6rem;
  position: absolute;
  top: 0;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
  width: 3.6rem;
  z-index: 10;
}

.icon-button .icon-linkedin {
  color: #0077B5;
}

.icon-button:hover .icon-linkedin {
  color: white;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' type='text/css' media='all' />

A: For font-awesome, the class should be fa-linkedin.

html {
  font-size: 20px;
}

body {
  background-color: #ccc;
  padding: 50px;
  text-align: center;
}

/* Wrapper */

.icon-button {
  background-color: white;
  border-radius: 50%;
  cursor: pointer;
  display: inline-block;
  font-size: 2.0rem;
  height: 3.6rem;
  line-height: 3.6rem;
  margin: 0 5px;
  position: relative;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: 3.6rem;
}

/* Circle */

.icon-button span {
  border-radius: 0;
  display: block;
  height: 0;
  left: 50%;
  margin: 0;
  position: absolute;
  top: 50%;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
  width: 0;
}

.icon-button:hover span {
  width: 3.6rem;
  height: 3.6rem;
  border-radius: 3.6rem;
  margin: -1.8rem;
}

.linkedin span {
  background-color: #0077B5;
}

/* Icons */

.icon-button i {
  background: none;
  color: white;
  height: 3.6rem;
  left: 0;
  line-height: 3.6rem;
  position: absolute;
  top: 0;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
  width: 3.6rem;
  z-index: 10;
}

.icon-button .fa-linkedin {
  color: #0077B5;
}

.icon-button:hover .fa-linkedin {
  color: white;
}
<!DOCTYPE html>

  <title></title>
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' type='text/css' media='all' />
  <link rel="stylesheet" type="text/css" href="style.css">


text:
Q: How to delete a row if it is a unique entry in R? Hopefully I have a simple question. How to remove the rows that have a unique date, i.e. there is only one entry with that date in the whole dataset. I want to do this because I am analyzing within group differences. The tests will not run with groups that are less than 2.
I look forward to your insights.

A: Try:
set.seed(42)
df <- data.frame(Date= sample(seq(as.Date("2001-05-05"), by=2, length.out=5),7, replace=T))

df[duplicated(df$Date)|duplicated(df$Date, fromLast=T),,drop=F]
#         Date
 # 1 2001-05-13
 # 2 2001-05-13
 # 4 2001-05-13
 # 5 2001-05-11
 # 7 2001-05-11


text:
Q: Extension method to validate nullity when nullable reference are enabled I have the following method:
public static void NotNull<TException>([ValidatedNotNull] object? data, string? message = null) where TException : Exception, new()

Basically, I use it to ensure that data is not null. It works well, however, when I enable nullable reference, Visual Studio continues to underline in green the object I pass to this method because it considers that I didn't check whether it's null or not although I use the ValidatedNotNull attribute.
Is there a way to tell Visual Studio that I validated the nullity of the object using my custom method?
Thanks

A: Use NotNullAttribute (see the attributes for null-state static analysis interpreted by the C# compiler docs):

A nullable parameter, field, property, or return value will never be null.

static void NotNull<TException>([NotNull]object? data, string? message = null) where TException : Exception, new()
{
   ...
}


text:
Q: Android sectioned listview with complex view I  want to use Jeff S. example for sectioned listview with headers.
But I want to use more complex item view.
Can you suggest me which approach is best to do this. I found two ways

*

*Put information in   Map<String,String> item = new HashMap<String,String>();  using item.put() - example here
2.Using getView on ArrayAdapter (without overriding other methods ) - example here
Which way is better?
Thanks

A: Depending on the complexity of your listitems it might be better to write your own adapter by extending BaseAdapter.
This link has a nice tutorial on how to write your own adapters.


text:
Q: How can I create one large partiton over two drives in CentOS? I've got a new dedicated server that I want to use purely for backup purposes.
[root@dedi ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        20G  942M   18G   6% /
tmpfs           7.8G     0  7.8G   0% /dev/shm
/dev/sda1       283M   32M  236M  12% /boot
/dev/sda2       1.8T   68M  1.7T   1% /data
[root@dedi ~]# cat /proc/partitions
major minor  #blocks  name

   8        0 1953481816 sda
   8        1     307200 sda1
   8        2 1932167168 sda2
   8        3   20480000 sda3
   8        4     524288 sda4
   8       16 1953481816 sdb

I'd like to keep the tmpfs and /boot as they are, and create one big ~4TB partition out of the rest.
I know this is relatively straightforward stuff, but I'd really appreciate hand walking through it, as I've never done any linux partitioning stuff before, and don't want to make a mess of the brand new box...
Many thanks

A: I personally feel LVM is overkill for this simple task, I would suggest setting up mdadm to create a RAID array.
Now you have two options:

*

*either a linear array, which will literally produce a concatenated partition based on two source partitions

*or RAID-0, which has the additional limitation that the source partitions must be of the same size but provides a substantial performance boost to reading and writing.

However beware, if either disk fails at least half and possibly all of your data will be lost. If you use a linear array some may be recoverable, with RAID-0 it will all almost certainly be destroyed, decide which of these trade-offs you want when deciding the type of array you choose.
Next, you need to create a large partition on each disk, you can do this with fdisk or any other tool, and I wont go into detail here as there are better guides elsewhere.
Then you run mdadm in the form of:
# for a RAID-0 Array
mdadm --create --verbose /dev/md0 --level=stripe /dev/sda1 /dev/sdb2

# for a linear Array
mdadm --create --verbose /dev/md0 --level=linear /dev/sda1 /dev/sdb2

Where /dev/sda1 and /dev/sdb2 are replaced with the partitions we created in the previous step. I then suggest taking a quick browse of the mdadm man page to learn how you may need to maintain this array.
You may choose to use LVM instead as Max has suggested and that may well serve you better if you end up with an extremely complex configuration but I do not feel it is really needed for a simple case like yours, raid may also provide substantial performance improvements over LVM if configured correctly, however that goes beyond the scope of this answer.

A: You need to use LVM   (Logical Volume Manager)
First of all , you must be aware that if any of the physical disk fail , the Big 4TB volume will fail too.  Backup your data first!
Basically , all you need to do is to partition your data (/dev/sda2 and /dev/sdb1) partition in lvm format then :

*

*create two physical volumes   (pvcreate /dev/sda2 /dev/sdb1)

*create one volume group with the two physical volumes (vgcreate VG_DATA /dev/sda2 /dev/sdb1)

*create one logical volume ( lvcreate -l 100%FREE -n DATA VG_DATA )

*create the filesystem on your new volume (mkfs.ext3 /dev/VG_DATA/DATA)

*mount the volume (mount /dev/VG_DATA/DATA /data )

There are dozen of sites with howtos lvm like this one.
Lvm is a lot more than these 4 commands , read the fine manual if you want advanced configuration.
I hope it will help you

A: Should point out that the above will wipe any data you have on /data.
You'll also have to create a new file system on the new RAID0 partition (as per LVM example) and update your fstab so it is mounted as /data (or whatever)


text:
Q: export quality images from Paraview I would like to export quality vector graphics from paraview however all the vector graphics formats exported seem to be a bit blurry except svg(svg is also not perfect but better that ps and eps). Are there any workarounds for this problem that I can get publication quality images?

A: The vector graphics output only affects the non-3D rendered elements such as texts, cube axes etc. (as discussed on in this post: http://www.kitware.com/blog/home/post/508). If you are referring to the blurriness of the 3D rendered scene itself, you may want to try saving higher resolution pngs instead.


text:
Q: How to divide an MVC application I need to provide a brand new interface to an already existing MVC app.  A lot of it will be the same, a lot will be different.  I've thought of four ways to do this, but I don't really like any them.
Can someone provide a good basis for choosing an option?

*

*Two applications: We create an entirely new MVC app, new domain (or subdomain), new everything.  We might use the same data access library, but in terms of the web interface they are completely independent.

*MVC Areas: We use the same application but create a Employees area and a Customers area.  We use some type of Role based routing to decide which area a request belongs to.

*Conditional Controller Statements: We examine the request inside each controller method and decide what data to return.

*Partial Views: One app, one area.  We put conditional checks inside the views to decide which partial to render (either the customer one or the employee one).
 More Details
We use a working MVC 3 app in our business for all of our office management needs.  It includes features for employee time, purchase orders, customer management and history, etc.  There's a wealth of customer information in there that our customers would love to see like their purchase history, reports on how much they spent, etc.  We obviously do not want to just open our system up to them.  It has a lot of internal data we do not want them to see, and we do not want them to be able to modify anything.

A: Why don't you split your solutions in different projects ?
I like to use the proxy pattern.
In my solution I have three projects:

*

*MVC (Has a reference to Proxy project)

*Proxy (It is a class library, hold's a reference to a WCF project)

*WCF (This project knows the database, my Entity Framework is here)

I guess this image could be helpful:

With this approach you can have different repositories in your proxy project, you can swap between them. It is extremely helpful when we are unit testing, or when we need to use cached repositories.
public abstract class Repository<T>
{
    public abstract T GetById(int id);
}

Use this one for unit testing
public class CustomerRepository : Repository<CustomerEntity>
{
    public override CustomerEntity GetById(int id)
    {
        return new CustomerEntity()
                    {
                       Id = id,
                       Name = "Customer " + id
                   };
    }
}

Use this one when you need to access external services
public class RemoteOrderRepository : Repository<OrderEntity>
{
    public override OrderEntity GetById(int id)
    {
        // You can access your external service here
    }
}

Use this one to take advantage of caching
public class CachedOrderRepository : RemoteOrderRepository
{
    public override OrderEntity GetById(int id)
    {
        string cacheKey = "Order" + id;
        var entity = MemoryCache.Default[cacheKey] as OrderEntity;
        if(entity == null)
        {
            entity = base.GetById(id);
            var cacheItem = new CacheItem(cacheKey, entity);
            var policy = new CacheItemPolicy();
            MemoryCache.Default.Add(cacheItem, policy);
        }
        return entity;
    }
}


text:
Q: OpenLDAP migrate from 2.3 to 2.4 ldapsearch ldap_bind: Invalid credentials (49) I am migrating a working OpenLDAP 2.3.43 setup to OpenLDAP 2.4.44 on a new RHEL server.  I have copied the data using slapcat and successfully imported using slapadd.  A ldapsearch that works on 2.3 does not work on 2.4 and produces a ldap_bind: Invalid credentials (49).  Here is the relevent parts of the slapd.conf:
access to dn.base="" by * read
access to dn.base="cn=Subschema" by * read
access to *
    by self write
by users read
by anonymous read

database    bdb
cachesize       10000
suffix          "o=itsso"
checkpoint      128 5

rootdn         "cn=admin,o=itsso"
rootpw          {CRYPT}55qEg16ldm0Bo

index objectClass                       eq,pres
index ou,cn,mail,surname,givenname      eq,pres,sub
index uidNumber,gidNumber,loginShell    eq,pres
index uid,memberUid                     eq,pres,sub
index nisMapName,nisMapEntry            eq,pres,sub

Here is the ldapsearch command:
ldapsearch -h localhost -D "cn=admin,o=itsso" -W -b o=itsso -s sub mail="first.last@xyz.org"

A: I found the answer at https://ltb-project.org/documentation/general/migrate_slapd_conf_cn_config
Even though I had /etc/openldap/slapd.conf openldap 2.4 starts using /etc/openldap/slapd.d.
I found a work around if I deleted /etc/openldap/slapd.d and then the slapd.conf file gets used when starting slapd.  However, I decided to convert slapd.conf to cn=config.
Here is what I did:
service slapd stop
mv /etc/openldap/slapd.d/ /etc/openldap/slapd.d.bak
mkdir /etc/openldap/slapd.d
slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d -d 256
chown -R ldap.ldap /etc/openldap/slapd.d
service slapd start


text:
Q: PyQt: splash screen while loading "heavy" libraries My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows).
I'm wondering whether it's feasible to show a splash screen while the matplotlib library is being loaded. Where does the actual loading take place - is it when the from line is executed? If so, how can I make this line execute during the splash screen and still be able to use the module throughout the code?
A related dilemma is how to test this - can I ask Windows to load the DLLs for every execution and not cache them?

A: Yes, loading the module takes place at the line where the import statement is. If you create your QApplication and show your splash screen before that, you should be able to do what you want -- also you need  to call QApplication.processEvents() whenever you need the splash screen to update with a new message.


text:
Q: fmt.Println vs os.Stdout.Write I had this code where I convert a string into a []byte slice using json.Marshal. When printing, why does fmt.Println() write numbers to stdout while os.Stdout.Write writes the string.
My question is how does fmt.Println parse the []byte.
package main

import (
        "encoding/json"
        "fmt"
        "os"
    )

func main(){
    str := "My string"
    dat,_:= json.Marshal(str)
    fmt.Println(dat)
    os.Stdout.Write(dat)
}

I get the following Output
[34 77 121 32 115 116 114 105 110 103 34]
"My string"

A: fmt.Println generates the friendly format for a byte slice. Because byte slices can contain anything at all (and not just printable characters), it shows you the individual byte values. Per the docs: a byte slice is printed out as:

the uninterpreted bytes of the string or slice

On the other hand, os.Stdout.Write writes the byte slice to standard out. Because they are printable characters, your terminal renders them properly.
Try it with non-printable characters, and the reason for fmt.Println's behavior will become clear:
func main() {
    dat := []byte{0, 1, 2, 3, 4}
    fmt.Println(dat)
    os.Stdout.Write(dat)
}

Outputs:
[0 1 2 3 4]
XXXX // four non-printable character placeholders (based on your terminal)

As for json, its output is a byte slice since this is the most useful format to be passed to a writer (network, disk, storage, etc...).


text:
Q: Why does the Lyapunov criterion only gives sufficient conditions for stability? I am studying stability for control systems, and I have written in the notes of my professor that the Lyapunov Criterion only gives sufficient conditions for stability, and not necessary and sufficient.
Can someone explain to me why?

A: The reason why the conditions are only sufficient is that failure OF A GIVEN FUNCTION to be a Lyapunov function for a system does not mean that no other Lyapunov function exists. This is valid for both linear and nonlinear systems.
There exist converse Lyapunov theorems (the original ones due to Massera, if memory serves me right) establishing that, if a system is stable, then a Lyapunov function exists. The proof in the nonlinear case is neither trivial not completely constructive.
In the case of linear system, there exists a recipe for constructing a Lyapunov function, which consists in solving the Lyapunov matrix equation. Thus if the equation does not provide a Lyapunov function, none exists, and the system is not stable. Apart from existence of the constructive method, the situations for linear and nonlinear systems are quite similar, technicalities aside.

A: For a linear system it does provide necessary and sufficient conditions for stability, for a general non-linear system it's not the case because failure of a chosen Lyapunov function to satisfy all the conditions for stability does not mean that the corresponding equilibrium point is not stable. It (may) just indicate that the chosen Lyapunov function is not good enough. For example take this dynamical system $$\ddot{x}(t)=-\sin x-a \dot{x}(t)~~,~~a\in \mathbb{R}_{>0}$$ Which is $$\begin{align}\dot{x}_1&=x_2 \\ \dot{x}_2&=-\sin x_1-ax_2 \end{align}$$ Choose two different Lyapunov function $$\mathbb{R} \times \mathbb{R} \ni (x_1,x_2) \mapsto V_1(x_1,x_2):=\left( 1-\cos x_1 \right)+x_2^2 \in \mathbb{R} \tag{L.1}$$
$$\mathbb{R} \times \mathbb{R} \ni (x_1,x_2) \mapsto V_2(x_1,x_2):=\left( 1-\cos x_1 \right)+\frac{x_2^2}{2} \in \mathbb{R} \tag{L.2}$$
See what you get using these two different Lyapunov functions


text:
Q: How to access user-context data set on epoll when calling epoll_wait Below I add sockets to epoll and set an application-context index within epoll_event.data.u32.
When receiving packets, recv() requires the socket file descriptor. In all the examples  events[i].data.fd is used.
However, events[i].data.fd and events[i].data.u32 are in a union, so how do I also access my user-context index events[i].data.u32? It looks like it is overwritten with the socket file descriptor?
// Initially
int epollFd = epoll_create1(0);

// Adding each socket, along with a user-context index for callbacks
struct epoll_event event;
event.events = EPOLLIN;
event.data.u32 = callbackIndex; // Here is the user-defined index
int sock = createSocket(port, address);
assert(epoll_ctl(epollFd, EPOLL_CTL_ADD, sock, &event));

// Later when receiving packets

struct epoll_event events[MAX_EVENTS];

while (true)
{
    int event_count = epoll_wait(epollFd, events, MAX_EVENTS, 30000);

    for (i = 0; i < event_count; i++)
    {
        int n = recv(events[i].data.fd, &buffer[0], sizeof(buffer), flags);
        // How do I access the user-context index I set when adding the socket to epoll?
    }
}

A: You tell epoll_ctl() which socket descriptor you want to listen for events for, and provide an epoll_event struct to associate with that listen operation.
Whenever epoll_wait() detects a registered event on a socket, it gives you back only the epoll_event struct that you had provided for that event, exactly as you had provided it. It does not tell you which socket triggered the event.
So, if you want to discover the socket, you have to either:

*

*store the socket descriptor itself in the epoll_event, but then you can't use any other user-defined data.

*store the socket descriptor somewhere else (ie, in an array, an object pool, etc) and then put identifying information needed to get back to the socket descriptor as user-defined data in the epoll_event (ie, array index, object pointer, etc).
Whatever you put in the epoll_event when calling epoll_ctl() is what you will get back from epoll_wait(). No more, no less.

A: Design of epoll is beautifully simple. The role of epoll_data_t is to provide lightweight mapping rather than storage. Notice that it has a void* ptr member, which allows you to map from fd (passed to epoll_ctl) to anything.
In your particular case, you could allocate a struct Context { int fd; uint32_t index; /*...*/ }; on the heap and point to that structure on EPOLL_CTL_ADD. You would have to also deallocate it after calling EPOLL_CTL_DEL by some object (e.g. container) which owns that context.
Since you are using C++, you could store a pointer to an abstract EventListener base class, reinterpret_cast from void* after epoll_wait to that class and dispatch event to an arbitrary derived handler.


text:
Q: android phonegap non compiled project I need to modify some classes of phonegap 2.2 for android but supplied sdk contains only .jar file. Is there an available full project in order to rebuild it?

A: Well the full Android source code for PhoneGap is always available at:
https://git-wip-us.apache.org/repos/asf?p=cordova-android.git;a=summary


text:
Q: Connecting to Cloud MySQL Instance I am fairly new at web development; I am currently trying to create a website that allows users to Submit information and have it stored in a database. I have GoDaddy for my domain name and Hosting, and I use Google Cloud Platform for the cloud database storage.
I have successfully figured out how to store HTML form data into a local database (PhpMyAdmin); I have also successfully connected my Google Cloud instance with another local database using MySQL Workbench.
I cannot figure out how to get everything connected; do I need to connect my Google Cloud instance with GoDaddy? Should I just use GoDaddy's Database offering? I tried putting the IPv4 address of my instance as the 'hostname' in my PHP connection code, which I uploaded to GoDaddy, but it is not connecting and I don't know why. I don't even know if this is what you are supposed to do?
I've read about having to allow permissions for particular IP addresses to store information, but that makes no sense to me as in the real world, I can simply go to a website, fill out a form, and my information is then sent to that company's' remote database somewhere. That's what I'm trying to accomplish for my website. Thank you.
PS: I'm using PHP as my server-side language.

A: Here is a general function that you can use to connect to a Google Cloud SQL instance:
function connectSQL( $dbProject, $dbRegion, $dbInstance, $dbIP, $dbName, $dbUsername, $dbPassword, $ssl = TRUE, $persistent = FALSE, $appEngine = FALSE ) {
  // $dbProject is the project that owns the database, which may differ from the project using the database

  // Create a connection
  $db = NULL;
  if ( $appEngine ) {
    // Connect from App Engine
    if ( $persistent ) {
      try {
        $db = new pdo( "mysql:unix_socket=/cloudsql/$dbProject:$dbRegion:$dbInstance;dbname=$dbName", $dbUsername, $dbPassword, array( PDO::ATTR_PERSISTENT => TRUE ) );
      } catch(PDOException $ex) {
        echoArr( $ex );
        return FALSE;
      }
    } else {
      try {
        $db = new pdo( "mysql:unix_socket=/cloudsql/$dbProject:$dbRegion:$dbInstance;dbname=$dbName", $dbUsername, $dbPassword );
      } catch(PDOException $ex) {
        echoArr( $ex );
        return FALSE;
      }
    }
  } else {
    // Connect from a non-App Engine environment (localhost, other hosting, etc.)
    if ( $persistent ) {
      if ( !$ssl ) {
        try{
            $db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array( PDO::ATTR_PERSISTENT => TRUE ) );
          $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $ex) {
          echoArr( $ex );
          return FALSE;
        }
      } else {
        try{
            $db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array(
              PDO::MYSQL_ATTR_SSL_KEY=>'/path/to/client-key.pem',
              PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
              PDO::MYSQL_ATTR_SSL_CA=>'/path/to/server-ca.pem',
              PDO::ATTR_PERSISTENT => TRUE
              )
          );
          $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $ex) {
          echoArr( $ex );
          return FALSE;
        }
      }
    } else {
      if ( !$ssl ) {
        try{
          $db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword );
          $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $ex) {
          echoArr( $ex );
          return FALSE;
        }
      } else {
        try{
            $db = new pdo( 'mysql:host='.$dbIP.':3306;dbname='.$dbName, $dbUsername, $dbPassword, array(
              PDO::MYSQL_ATTR_SSL_KEY=>'/path/to/client-key.pem',
              PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
              PDO::MYSQL_ATTR_SSL_CA=>'/path/to/server-ca.pem'
              )
          );
          $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $ex) {
          echoArr( $ex );
          return FALSE;
        }
      }
    }
  }

  return $db;

}

You can use this regardless of where your script is hosted.


text:
Q: Logical error displaying randomized array so im pretty new to the whole JAVA gang and im just working on a project for my class. Im finished with all the backbone work but for the past 3 days ive been stuck on this issue.
So, lets say i have an array of,
1a, 2b, 3c, 4d. and i wish to randomize it buy changing the indexes (already done). but when i print the array out, it comes up as a variant of this.
1a, 1a, 4d, 3c. (yet again this is randomized but the point is the first object thats printed is always duplicated but in reality there are no duplicates in the array, just the displaying method.)
this is the code i have for this program. Consists of 3 classes.
import java.util.Scanner;
public class Deck
{
public static void main(String [] args)
{
    Scanner s = new Scanner(System.in);
    DeckOfCards d = new DeckOfCards();
    int in;
    d.createNewDeck();
    System.out.println("Shuffling Deck...");
    do {
        System.out.println("Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the deck. Enter 2 to view the array in its current form. Enter 3 to force shuffle the array. 9 to exit");
        in = s.nextInt();

        if (in == 0) {
            System.out.println(d.deal());
        } else if (in == 1) {
            System.out.println(d.cardsLeft());
        } else if (in == 2) {
            System.out.println(d.toString());
        } else if (in == 3) {
            d.shuffle();
        }
    } while (in != 9);
}
}

import java.util.Random;
public class DeckOfCards
{
public Random r = new Random();
public Card [] deck;
public int current;
public int temp;
public int index;
public DeckOfCards() {
    deck = new Card[52];
    current = 0;
    createNewDeck();
}
public void createNewDeck() {
    deck[0] = new Card("A","C");
    deck[1] = new Card("2","C");
    deck[2] = new Card("3","C");
    deck[3] = new Card("4","C");
    deck[4] = new Card("5","C");
    deck[5] = new Card("6","C");
    deck[6] = new Card("7","C");
    deck[7] = new Card("8","C");
    deck[8] = new Card("9","C");
    deck[9] = new Card("10","C");
    deck[10] = new Card("J","C");
    deck[11] = new Card("Q","C");
    deck[12] = new Card("K","C");
    deck[13] = new Card("A","D");
    deck[14] = new Card("2","D");
    deck[15] = new Card("3","D");
    deck[16] = new Card("4","D");
    deck[17] = new Card("5","D");
    deck[18] = new Card("6","D");
    deck[19] = new Card("7","D");
    deck[20] = new Card("8","D");
    deck[21] = new Card("9","D");
    deck[22] = new Card("10","D");
    deck[23] = new Card("J","D");
    deck[24] = new Card("Q","D");
    deck[25] = new Card("K","D");
    deck[26] = new Card("A","S");
    deck[27] = new Card("2","S");
    deck[28] = new Card("3","S");
    deck[29] = new Card("4","S");
    deck[30] = new Card("5","S");
    deck[31] = new Card("6","S");
    deck[32] = new Card("7","S");
    deck[33] = new Card("8","S");
    deck[34] = new Card("9","S");
    deck[35] = new Card("10","S");
    deck[36] = new Card("J","S");
    deck[37] = new Card("Q","S");
    deck[38] = new Card("K","S");
    deck[39] = new Card("A","H");
    deck[40] = new Card("2","H");
    deck[41] = new Card("3","H");
    deck[42] = new Card("4","H");
    deck[43] = new Card("5","H");
    deck[44] = new Card("6","H");
    deck[45] = new Card("7","H");
    deck[46] = new Card("8","H");
    deck[47] = new Card("9","H");
    deck[48] = new Card("10","H");
    deck[49] = new Card("J","H");
    deck[50] = new Card("Q","H");
    deck[51] = new Card("K","H");
    current = 0;
}
public void shuffle() {
    for (int i = deck.length - 1; i >= 0; i--)
    {
        index = r.nextInt(i + 1);
        deck[temp] = deck[index];
        deck[index] = deck[i];
        deck[i] = deck[temp];
    }
    current = 0;
}
public Card deal() {
    current++;
    return deck[current-1];
}
public int cardsLeft() {
    return deck.length - current;
}
public String getCurrentSuit() {
    return deck[current].getSuit();
}
public String getCurrent() {
    return deck[current].toString();
}
public String toString() {
    String s = "";
    for (int i = 0; i < 52; i++) {
        s = s + deck[i] + " ";
    }
    return s;
}
}

import java.util.Random;
public class Card
{
private String suit;
private String face;

public Card() {
    suit = "S";
    face = "A";
}
public Card(String f, String s) {
    face = f;
    suit = s;
}
public String getSuit() {
    return suit;
}
public String toString() {
    return face + suit;
}
}

A bit of explanation for the code is that the DeckOfCards class is the array along with the methods used to "shuffle" and "deal" the card. The array stores 52 objects of the "Card" class and the main driver is the "Deck" class.
Here is one of the tests i did to show the issue in action,
Shuffling Deck...
Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the
deck. 9 to exit
1
52
Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the deck. 9 to exit
2
AC 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AD 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AS 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AH 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH
Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the deck. 9 to exit
3
Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the deck. 9 to exit
2
JC JC KH AH 5S 2C 3S 6S JS JD KC 4S 9H 10H 6D 9D 7C 5H QD 4D 2H 8C 10C 7H 10S 9S AS KS 6C 7D 5D QH 3H 8D 3D 2S 4H 6H 2D QS 8S JH 4C 9C KD 8H QC 10D 5C 3C AD 7S
Enter 0 to deal a card. Enter 1 to get the ammount of remaining cards in the deck. 9 to exit

Thanks a million to anyone who can help!

A: As mentioned in comments, there are standard libraries to shuffle.
Your shuffle has a defect; you use the deck array as a means of storing a temporary value.  You probably meant to do this:
public void shuffle() {
    for (int i = deck.length - 1; i >= 0; i--)
    {
        index = r.nextInt(i + 1);
        Card temp = deck[index];
        deck[index] = deck[i];
        deck[i] = temp;
    }
    current = 0;
}


text:
Q: Get Current Working Directory With Python C Extension I am building a Python C Extension that can load images.
To load a certain image, the user has to write the file path for that image.
The problem is that the user has to type the whole file path, even if the image is in the same directory as their module.
Python itself has some useful tools like os.path and pathlib that can help you to find the path of the current module.
I have searched the Python C API and I cannot seem to find any tools that relate to finding the current working directory in C.
What can I do - in C - to get the path to the directory of the user's module?
Are there any Python.h functions?
Am I taking the wrong approach?

A: The python c api can interact with lots of things you can do in Python.
How would you do this in Python? You would import os and call os.getcwd(), right?
Turns out you can do the same in the c api.
PyObject *os_module = PyImport_ImportModule("os");
if (os_module == NULL) { //error handling
    return NULL;
}

PyObject* cwd = PyObject_CallMethod(os_module, "getcwd", NULL);
if (cwd == NULL) { //error handling
    return NULL;
}

char* result = PyUnicode_AsUTF8(cwd);

And then when you're done with the module, or any pyobject in general, remember to call Py_DECREF() on it.


text:
Q: Passing conditional arguments to kivy from python The idea is pretty simple: I have a slider which affects the speed of a gif.  However, I can't figure out how to trigger the image to get the updated "anim_delay" value from python (or for python to push it to kivy?).
The main file:
class BottomRightPart(BoxLayout):

    imgdelay=-1

    def OnFanSpeedSliderValueChange(self,slider,value):
        if value == 0:
            imgdelay = -1
        elif value == 1:
            imgdelay= 1
        elif value == 2:
            imgdelay = 0.6
        elif value == 3:
            imgdelay = 0.3
        elif value == 4:
            imgdelay = 0

The .kv code
<BottomRightPart>
    BoxLayout:
        Image:
            id:FanImg
            source: 'fan.gif'
            anim_delay: root.imgdelay

        Label:
            text: str(int(FanSpeed.value))

        Slider:
            id:FanSpeed
            min:0
            max:4
            step:1
            on_value: root.OnFanSpeedSliderValueChange(*args)

Where's the missing link?  Any pointers is appreciated!

A: You are missing self.
Also set imgdelay to a NumericProperty.
Try this:
from kivy.properties import NumericProperty

class BottomRightPart(BoxLayout):

    imgdelay = NumericProperty(-1)

    def OnFanSpeedSliderValueChange(self,slider,value):
        if value == 0:
            self.imgdelay = -1
        elif value == 1:
            self.imgdelay= 1
        elif value == 2:
            self.imgdelay = 0.6
        elif value == 3:
            self.imgdelay = 0.3
        elif value == 4:
            self.imgdelay = 0

Personally I would create my method something like this:
def OnFanSpeedSliderValueChange(self,slider,value):
    values = [-1, 1, 0.6, 0.3, 0]
    self.imgdelay = values[int(value)]


text:
Q: When to use ExceptionFilter vs BaseExceptionFilter in NestJS? What is the diff b/w both types of filters. And when to use what? Please explain with any example
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {

}

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {

}

A: ExceptionFilter is an interface that defines that the current class should implement the catch method with the signature (exception: unknown, host: ArgumentHost).
BaseExceptionFilter is a class already made in NestJS with a working catch method. By using extend you can add your own logic to catch and then in the end of the implementation call super.catch(exception, host) and let Nest take care of the rest from there.
The main difference of the two is how much of the logic do you want to write vs how much do you want to add in. If you are happy with how Nest already handles errors, and just want to add in the ability to log your errors, say to a database, then extends BaseExceptionFilter is a good fit. However, if you don't care or how Nest's exception filter works by default, then implements ExceptionFilter and writing your own custom logic is the way to go.


text:
Q: I want to insert and retrieve data under one button event in vb.net with sql database Here i am trying to register student's detail. and at the same time i want to retrieve  a unique user id from connected SQL server and that's where i got stuck!
I want to know what i am doing wrong here!
Everything stored in the SQL server is correct and i have make an auto increment code in SQL!
so why its not inserting and retrieving the data simultaneously

Imports MySql.Data.MySqlClient

Public Class Form3
    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New MySqlConnection("server=localhost;user id=root;password=root;persistsecurityinfo=True;database=bcaproject")
        Dim cmd As New MySqlCommand

        If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Then
         MessageBox.Show("Information shouldn't be empty...")
        Else
            con.Open()
            cmd.Connection = con
            cmd.CommandText = "insert into student(F_name,L_name,Email,Phoneno,Username,Password) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "')"
            cmd.ExecuteNonQuery()
            MessageBox.Show("successfully Registered")
            TextBox1.Text = ""
            TextBox2.Text = ""
            TextBox3.Text = ""
            TextBox4.Text = ""
            TextBox5.Text = ""
            TextBox6.Text = ""
            Form2.Show()
            Me.Hide()
        End If
    End Sub

    Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Form2.Show()
        Me.Hide()
    End Sub

    Private Sub TextBox4_KeyPress1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If Not IsNumeric(e.KeyChar) Then
                tipvalidation.Show("Numeric input required", sender, 5000)
                e.KeyChar = Nothing
            End If
        End If
    End Sub
End Class


text:
Q: Tensorflow steps/sec gradually drops Hi Tensorflow experts:
I have noticed that steps/sec of my training job with multiple workers and parameter servers tend to stabilize to a lower value than initially. Is there any explanation for that? I don't think it has to do with evaluators since I configured them to start after 1000 seconds. Also I am using tensorflow 1.12 with estimator and dataset API. Thanks!


text:
Q: Probability of Playing Darts We have a dartboard with radius $1$, the dart will always hit the dartboard. The hitting point of the dart is uniformly distributed, with a stochastic vector $(X,Y)$. Now I want to determine the probability mass and density function.
Say $A=\{(x,y): x^2 + y^2 \leq 1\}$. So $f_{X,Y}(x,y) = 0$ if $(x,y) \notin A$ and $f_{X,Y}(x,y) = c $ if $(x,y) \in A$. Now:
\begin{align}
\int \int f_{X,Y}(x,y) dx dy = \int\int\limits_A = \text{area } A \cdot c = 1.
\end{align}
So $1=2\pi \cdot c$ and $c=\frac{1}{2\pi}$. We found that $f_{X,Y}(x,y)=\frac{1}{2\pi}$. Now I am interested in $f_X(x)$ and $F_X(x)$. For the first one we can say that:
\begin{align}
f_X(x) = \int\limits_{-1}^1 \frac{1}{2\pi} dy = \frac{1}{\pi}.
\end{align}
But how to find $F_X(x)$? We have to integrate over $x$ and $y$ but how to deal with the restrictions of $A$?

A: To find $f_X(x)$, your idea is correct but the limits should be the range of $y$ at any given $x$, so should be from $-\sqrt{1-x^2}$ to $\sqrt{1-x^2}$  As you are integrating along $y$ it just becomes $f_X(x)=\frac 2\pi\sqrt{1-x^2}$ (correcting your $c$). Then for $F_X(x)$ you integrate $\int_{-1}^x f_X(t)dt=\int_{-1}^x\frac 2\pi\sqrt{1-t^2}dt$


text:
Q: Show that $\inf\{t>0: X_t(\omega)\in G\}$ is an optional time.
Let $E$ be a finite dimensional Euclidean space. We take $X:=(X_t)_{t\geq 0}$ to be an $\Bbb{F}:=(\mathcal{F}_t)_{t\geq 0}$ adapted process with values in $E$. Let $G\subset E$ be open and assume that $X$ has either right- or left-continuous trajectories. Now define $T_{X,G}:=\inf\{t>0: X_t(\omega)\in G\}$. I want to show that this is an $\Bbb{F}$-optional time.

By definition $T$ is an $\Bbb{F}$-optional time if for all $k>0$, $\{T<k\}\in \mathcal{F}_k$. As I understood the part

assume that $X$ has either right- or left-continuous trajectories

they mean that for a fixed $\omega\in \Omega$, $t\mapsto X_t(\omega)$ is right- or left-continuous.
But now if I fix an arbitrary $k\geq 0$ and consider $$\{T_{X,G}<k\}=\{\inf\{t>0: X_t(\omega)\in G\}<k\}$$ then I don't know how to continue. So I mean if we would work in the discrete case then $\{\inf\{t>0: X_t(\omega)\in G\}<k\}=\bigcup_{1\leq n\leq k-1}\{\inf\{t>0: X_t(\omega)\in G\}=k\}$ but in our case we are not in the discrete one. I think therefore we need this assumption of right- or left-continuous trajectories, but I don't see how this is useful in the proof.
Can maybe someone help me?

A: $$\inf\{t>0\mid X_t\in G\}<k\iff\exists t\in(0,k),\ X_t\in G,$$
and because $G$ is open and $X_t$ is either left- or right-continuous, the latter is equivalent to
$$
\exists q\in(0,k)\cap\mathbb Q,\ X_q\in G.
$$
Hence
$$
\{T_{X,G}<k\}=\bigcup_{q\in(0,k)\cap\mathbb Q}\{X_q\in G\}\in\mathcal F_k.
$$


text:
Q: Induction proof for a stochastic process. Let $(X_n)_{n\in\mathbb{N}}$ be a Markovchain. How can I then show following equation for all $ n \in \mathbb{N}$,
$ \displaystyle\bigcup_{k=1}^n \lbrace X_k = j \rbrace = \biguplus_{k=1}^n \lbrace X_1 \neq j, \dots, X_{k-1} \neq j, X_k =j \rbrace$ ?
Best regards!

A: This doesn't have anything to do with Markov chains; it is a matter of set operations. If $$\omega\in\bigcup_{k=1}^n\{X_k=j\},$$ let $k^\star$ be the smallest positive integer such that $\omega\in\{X_{k^\star}=j\}$. Then $$\omega\in\bigcap_{k=1}^{k^\star-1}\{X_k\ne j\}\cap\{X_{k^\star}=j\}\subset\bigcup_{k^\star=1}^n\bigcap_{k=1}^{k^\star-1}\{X_k\ne j\}\cap\{X_{k^\star}=j\}. $$
Conversely, if $$\omega\in\bigcup_{k^\star=1}^n\bigcap_{k=1}^{k^\star-1}\{X_k\ne j\}\cap\{X_{k^\star}=j\} $$ then $$\omega\in \{X_{k^\star}=j\}\subset\bigcup_{k=1}^n\{X_k=j\}. $$


text:
Q: How does one simplify (x^2 - 4)(x-3)? I am currently studying for my College Algebra final exam and one of the questions I have to do is the following:
x^3 - 3x^2 - 4x + 12

I was able to simplify down to this:
(x^2 - 4)(x-3)

My question is, can you simplify this further?
All the online math calculators seem to suggest that it isn't possible but I found that I could factor (x^2 - 4) to this:
(x-2)(x+2)

So, if I were to simplify the original problem fully, would it look like this:
[(x-2)(x+2)](x-3)

Or this:
(x^2 - 4)(x-3)


text:
Q: Need help for xsl:template I have this in my xml
<GROUP>
    <ELEM_1/>
    <ELEM_1/>
    <ELEM_1/>
    <ELEM_1/>
</GROUP>
<GROUP>
    <TAB>
        <LEFT>
            <ELEM_1/>
            <ELEM_1/>
            <ELEM_2/>
        </LEFT>
        <RIGHT>
            <ELEM_1/>
            <ELEM_2/>
            <ELEM_2/>
            <ELEM_1/>
        </RIGHT>
    </TAB>
</GROUP>
<GROUP>
    <ELEM_1/>
    <ELEM_1/>
    <ELEM_1/>
    <ELEM_1/>
</GROUP>

I have and xsl which transform this xml to display it.
I want that the node TAB is display like a table with two columns LEFT and RIGHT and with one row each that display a list with ELEM_1 and ELEM_2.
I have a xsl:template how display ELEM_1 and ELEM_2 how I want.
I have this xsl:template for the TAB that does what I want
<xsl:template match="TAB">

            <xsl:apply-templates select="LEFT"/>
            <xsl:apply-templates select="RIGHT"/>

</xsl:template>

But the xsl:templatefor RIGHT and LEFT doesn't work how I want
<xsl:template match="LEFT">

Left title

        <xsl:if test="ELEM_1">
            <xsl:apply-templates select="ELEM_1"/>
        </xsl:if>
        <xsl:if test="ELEM_2">
            <xsl:apply-templates select="ELEM_2"/>
        </xsl:if>

</xsl:template>

<xsl:template match="RIGHT">

Right title

            <xsl:if test="ELEM_1">
                <xsl:apply-templates select="ELEM_1"/>
            </xsl:if>
            <xsl:if test="ELEM_2">
                <xsl:apply-templates select="ELEM_2"/>
            </xsl:if>

</xsl:template>

How to do it right?
Thanks

A: I'm not certain why your tests are failing. In the solution below, you don't need to test anyway, the beauty of XSLT being a declarative language. Here you go:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:php="http://php.net/xsl">

<xsl:template match="/">
    <xsl:apply-templates select="/ROOT/GROUP/TAB" />
</xsl:template>

<xsl:template match="TAB">

            <xsl:apply-templates select="LEFT | RIGHT "/>

</xsl:template>

<xsl:template match="LEFT">

Left title

                <xsl:apply-templates select="ELEM_1"/>
                <xsl:apply-templates select="ELEM_2"/>

</xsl:template>

<xsl:template match="RIGHT">

Right title

                    <xsl:apply-templates select="ELEM_1"/>
                    <xsl:apply-templates select="ELEM_2"/>

</xsl:template>

<xsl:template match="ELEM_1">

ELEM 1 OUTPUT

</xsl:template>
<xsl:template match="ELEM_2">

ELEM 2 OUTPUT

</xsl:template>

</xsl:stylesheet>

A: I'm not sure what example the result you going to achieve (probably enumerate ELEM_1, ELEM_2 nodes):
<xsl:template match="TAB">

            <xsl:apply-templates select="LEFT"/>
            <xsl:apply-templates select="RIGHT"/>

</xsl:template>

<xsl:template match="LEFT">

Left title

    <xsl:apply-templates />

</xsl:template>

<xsl:template match="RIGHT">

Right title

    <xsl:apply-templates />

</xsl:template>

<xsl:template match="LEFT/* | RIGHT/*">

    <xsl:copy/>
</xsl:template>


text:
Q: Strange behavior of Visual Studio I have a Microsoft Management Console 3 Project built in .Net 2.0, Currently I am Using Visual Studio 2010 to build this project and every thing is working fine,
For future I am planning it to move my projects in Visual studio 2013 but I am unable to build project in visual studio 2013
The type or namespace name 'ManagementConsole' does not exists in the namespace 'Microsoft' (are you missing an assembly reference?)

Note: I did not do any other change in the project

A: Build the solution in VS 2013, by setting framework 4.0 or framework 4.5.
its work in my case.


text:
Q: Find same values in two huge datasets i have a list with roughly 2 000 rows [UnixTimestamp, Value01, Value02](it comes as a JSON) and i have another list which has a few million rows [UnixTimestamp, Value01, Value02] (it comes as a .csv) I want to figure out if each element in the smaller list has an element in the second list with the same values.
Both the lists are sorted by the timestamp
The simplest way is obviously something like that:
for x in small_List:
    if x in big_list:
        return True
    return False

But does that make sense or is there a more efficient way?
Thanks

A: If they are just lists, you can try something like this.
set(small_list) & set(big_list)
Converting to set will remove the duplicate values and you can use & operator to compare and result back the same values of the two sets.

A: Both are already sorted by timestamp, so use that to your advantage:
big_list_index = 0
for x in small_list:
    y = big_list[big_list_index]
    while big_list_index < len(big_list) and y.timestamp < x.timestamp:
        big_list_index += 1
        y = big_list[big_list_index]
    while big_list_index < len(big_list) and y.timestamp == x.timestamp:
        if y.timestamp == x.timestamp and y.value01 == x.value01 and y.value02 == x.value02:
            return True
        else:
            big_list_index += 1
            y = big_list[big_list_index]

If timestamps are unique, complexity is O(len(big_list) + len(small_List))


text:
Q: Events Calendar Multisite 404 for events I haven't seen any solutions that work for me or apply to my use case.
but, I have a url like
https://www.example.com/site1/event/some-event-2017-01-17/2018-08-30/
this will throw a 404 page not found (the default 404 for my WP install)
but https://www.example.com/site1/event/other-event-4-2017-10-28-2018-03-03-2018-09-01/
will load the event. I don't really know what may be causing the 404, but:

*

*is it because i don't have a Multisite license for Events Calendar Pro?

*the htaccess rules don't cover that many segments in the URI?

this is the htaccess i am using:
# BEGIN WordPress Multi-Site
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?([_0-9a-zA-Z-]+/)?([_0-9a-zA-Z-]+/) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
# END WordPress Multi-Site