问:
How to send some list to another class and how to connect it
Im doing my HW to school, making some game.. i took blackjack bcs i thought its easy, but now i know that isnt easy for me.. So i need help with solution.

I tried to connect somehow the lists "cards", but idk if it is connected or not.

Here is shuffle

```<code>public class Shuffle
{
    public List<Card>cards;
    public void Michani()
    {
        Random ran = new Random();
        int r = cards.Count;
        while (r > 1)
        {
            int n = ran.Next();
            Card card = cards[n];
            cards[n] = cards[r];
            cards[r] = card;
        }
    }
}

public class Card
{
    public CardValue Value { get; set; }
    public CardSuit Suit { get; set; }
    public int Weight { get; set; }
}

public enum CardValue : int
{
    Eso = 1,
    Dvojka = 2,
    Trojka = 3,
    Ctyrka = 4,
    Petka = 5,
    Sestka = 6,
    Sedmicka = 7,
    Osmicka = 8,
    Devitka = 9,
    Desitka = 10,
    Jack = 11,
    Queen = 12,
    King = 13,
}

public enum CardSuit : int
{
    Hearts = 1,
    Spades = 2,
    Clubs = 3,
    Diamons = 4
}
</code>```

Here is ending card:

```<code>public class DeckGen
{
    public List<Card> cards;

    public void Deck()
    {
        for (int v = 0; v < 13; v++)
        {
            for (int s = 0; s < 4; s++)
            {
                cards.Add(new Card() { Suit = (CardSuit)s, Value = (CardValue)v });
                if (s <= 8)
                {
                    cards[cards.Count - 1].Weight = s + 1;
                }
                else
                {
                    cards[cards.Count - 1].Weight = 10;
                }

            };
        }

    }
}
</code>```

Here is creating the deck:

```<code>public class DrawCard
{
    public List<Card> cards { get; }

    public Card Lizani()
    {
        if (cards.Count <= 0)
        {
            DeckGen();
            Shuffle();
        }
        Card returnedcard = cards[cards.Count - 1];
        cards.RemoveAt(cards.Count - 1);
        return returnedcard;
    }

    public void Shuffle()
    {

    }

    public void DeckGen()
    {

    }
}
</code>```

Here is drawing a card:

答:
I don't know I did get the question truely or not but I think making the class and list static will do the trick and then you can call the list like</p>

```<code>  DeckGen.CardList;
</code>```

Body:
Im doing my HW to school, making some game.. i took blackjack bcs i thought its easy, but now i know that isnt easy for me.. So i need help with solution.

I tried to connect somehow the lists "cards", but idk if it is connected or not.

Here is shuffle

public class Shuffle
{
    public List<Card>cards;
    public void Michani()
    {
        Random ran = new Random();
        int r = cards.Count;
        while (r > 1)
        {
            int n = ran.Next();
            Card card = cards[n];
            cards[n] = cards[r];
            cards[r] = card;
        }
    }
}

public class Card
{
    public CardValue Value { get; set; }
    public CardSuit Suit { get; set; }
    public int Weight { get; set; }
}

public enum CardValue : int
{
    Eso = 1,
    Dvojka = 2,
    Trojka = 3,
    Ctyrka = 4,
    Petka = 5,
    Sestka = 6,
    Sedmicka = 7,
    Osmicka = 8,
    Devitka = 9,
    Desitka = 10,
    Jack = 11,
    Queen = 12,
    King = 13,
}

public enum CardSuit : int
{
    Hearts = 1,
    Spades = 2,
    Clubs = 3,
    Diamons = 4
}

Here is ending card:

public class DeckGen
{
    public List<Card> cards;

    public void Deck()
    {
        for (int v = 0; v < 13; v++)
        {
            for (int s = 0; s < 4; s++)
            {
                cards.Add(new Card() { Suit = (CardSuit)s, Value = (CardValue)v });
                if (s <= 8)
                {
                    cards[cards.Count - 1].Weight = s + 1;
                }
                else
                {
                    cards[cards.Count - 1].Weight = 10;
                }

            };
        }

    }
}

Here is creating the deck:

public class DrawCard
{
    public List<Card> cards { get; }

    public Card Lizani()
    {
        if (cards.Count <= 0)
        {
            DeckGen();
            Shuffle();
        }
        Card returnedcard = cards[cards.Count - 1];
        cards.RemoveAt(cards.Count - 1);
        return returnedcard;
    }

    public void Shuffle()
    {

    }

    public void DeckGen()
    {

    }
}

Here is drawing a card:

Body:
I don't know I did get the question truely or not but I think making the class and list static will do the trick and then you can call the list like

  DeckGen.CardList;


来源: stackexchange

问:
Find "path" in 2D array where path cells sum equals to "sum"
Given 2D array of positive integers. A "path" is a collection of adjacent cells. Two cells are adjacent only from right/left/top/bottom (no diagonal).

The task is to write a function that receives a 2D array mat, an integer sum and a 2D array path (with same size as mat-empty array all zeros).

The function should check if path exist where the sum of cells equal to sum, should return true if exist and false otherwise.

The array path will mark the path (if exist with 1).

For example if mat is:

and sum=4

then path can be one of these three:

My code:

```<code>public static void main(String[] args)
{
    int[][] mat={{2,41,3,14},
                 {2,1,24,7},
                 {2,15,10,54},
                 {63,22,2,4}};

    int[][] path={{0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0}};
    findSum(mat,4,path);
    //print(mat);
    print(path);
}
public static boolean findSum (int mat[][], int sum, int path[][])
{
    return findSum(mat,sum,path,0,0);
}

public static boolean findSum (int mat[][], int sum, int path[][],int i,int j)
{
    if(sum==0)
        return true;

    if(i==mat[0].length||j==mat[1].length)
        return false;
    boolean result=findSum(mat,sum-mat[i][j],path,i,j+1)||findSum(mat,sum-mat[i][j],path,i+1,j);

    if(result)
        path[i][j]=1;
    return result;

}
private static void print(int[][] arr)
{
    for(int i=0;i<arr[0].length;i++)
    {
        for(int j=0;j<arr[0].length;j++)
        {
            System.out.print(arr[i][j]+" ");
        }
        System.out.println();
    }
}
</code>```

My code works fine only if the path starts at (0,0) but does't work for other pathes, for example it doesn't work(path array is all zero) for sum=16 even that there is such path.

Note:

The function must be recursive- no loops at all.

Global variables are not allowed (printing the array is not part of the question- only for test therefore there is a loop)

答:
Nice question... Here is the answer. It was a fun code challenge ;)

```<code>public static void main(String[] args)
{
    int[][] mat={{2,41,3,14},
                 {2,1,24,7},
                 {2,15,10,54},
                 {63,22,2,4}};

    int[][] path={{0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0}};

    if ( findSum(mat,22,path) ) print(path);
    else System.out.println("No path found");
}
public static boolean findSum (int mat[][], int sum, int path[][])
{
    return startPath(mat, sum, path, -1, 0);
}

// Recursively check every possible starting point
public static boolean startPath(int mat[][], int sum, int path[][], int y, int x)
{
    // Iterate y, goto next column if necessary
    if (++y == mat.length) {
        y = 0;
        ++x;
    }

    if (x == mat[0].length) // Bounds check
        return false;

    if (findSum(mat, sum, path, y, x)) // We've found a successful start point!
    {
        System.out.println("A successful path starts at " + x + ", " + y);
        return true;
    }

    return startPath(mat, sum, path, y, x); // We'll have to keep looking
}

public static boolean findSum (int mat[][], int sum, int path[][], int i, int j)
{
    if(i==mat[0].length || j==mat[1].length || i<0 || j<0) // Bounds check
        return false;

    if (path[i][j] == 1) // Backtracking check
        return false;

    sum -= mat[i][j]; // Decrement sum

    if (sum >= 0) { // More to go? look around
        path[i][j] = 1;

        if (sum == 0) return true; // We made it!

         // If any path finds the end, don't try other paths
        boolean result = findSum(mat, sum, path, i+1, j);
        if (result) return true;
        result = findSum(mat, sum, path, i, j+1);
        if (result) return true;
        result = findSum(mat, sum, path, i-1, j);
        if (result) return true;
        result = findSum(mat, sum, path, i, j-1);

         // There was no successful paths, this is a dead end
        if (!result) path[i][j] = 0;
        return result;
    } else { // We're negative, overshot it
        return false;
    }
}

private static void print(int[][] arr)
{
    for(int i=0;i<arr[0].length;i++)
    {
        for(int j=0;j<arr[0].length;j++)
        {
            System.out.print(arr[i][j]+" ");
        }
        System.out.println();
    }
}
</code>```

By the way when checking multidimensional array dimensions you are meaning to do arr.length and arr[0].length but instead you are doing arr[0].length and arr[1].length which would get the same dimension twice and cause an error if the array was not a square.

I've also allowed moving in any direction, by using the intended path to prevent re-checking the same node again. This could probably be a boolean array. Sorry if my x/y recursion is rough looking... I really prefer loops or .forEach or => or .map for that...

The -1, 0 can be cleaned up perhaps with optional parameters and not iterating on the first pass.

Let me know if there are any errors or edge cases you may find.

ContentLicense: CC BY-SA 4.0

Body:
Given 2D array of positive integers. A "path" is a collection of adjacent cells. Two cells are adjacent only from right/left/top/bottom (no diagonal).

The task is to write a function that receives a 2D array mat, an integer sum and a 2D array path (with same size as mat-empty array all zeros).

The function should check if path exist where the sum of cells equal to sum, should return true if exist and false otherwise.

The array path will mark the path (if exist with 1).

For example if mat is:

and sum=4

then path can be one of these three:

My code:

public static void main(String[] args)
{
    int[][] mat={{2,41,3,14},
                 {2,1,24,7},
                 {2,15,10,54},
                 {63,22,2,4}};

    int[][] path={{0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0}};
    findSum(mat,4,path);
    //print(mat);
    print(path);
}
public static boolean findSum (int mat[][], int sum, int path[][])
{
    return findSum(mat,sum,path,0,0);
}

public static boolean findSum (int mat[][], int sum, int path[][],int i,int j)
{
    if(sum==0)
        return true;

    if(i==mat[0].length||j==mat[1].length)
        return false;
    boolean result=findSum(mat,sum-mat[i][j],path,i,j+1)||findSum(mat,sum-mat[i][j],path,i+1,j);

    if(result)
        path[i][j]=1;
    return result;

}
private static void print(int[][] arr)
{
    for(int i=0;i<arr[0].length;i++)
    {
        for(int j=0;j<arr[0].length;j++)
        {
            System.out.print(arr[i][j]+" ");
        }
        System.out.println();
    }
}

My code works fine only if the path starts at (0,0) but does't work for other pathes, for example it doesn't work(path array is all zero) for sum=16 even that there is such path.

Note:

The function must be recursive- no loops at all.

Global variables are not allowed (printing the array is not part of the question- only for test therefore there is a loop)

Body:
Nice question... Here is the answer. It was a fun code challenge ;)

public static void main(String[] args)
{
    int[][] mat={{2,41,3,14},
                 {2,1,24,7},
                 {2,15,10,54},
                 {63,22,2,4}};

    int[][] path={{0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0},
                  {0,0,0,0}};

    if ( findSum(mat,22,path) ) print(path);
    else System.out.println("No path found");
}
public static boolean findSum (int mat[][], int sum, int path[][])
{
    return startPath(mat, sum, path, -1, 0);
}

// Recursively check every possible starting point
public static boolean startPath(int mat[][], int sum, int path[][], int y, int x)
{
    // Iterate y, goto next column if necessary
    if (++y == mat.length) {
        y = 0;
        ++x;
    }

    if (x == mat[0].length) // Bounds check
        return false;

    if (findSum(mat, sum, path, y, x)) // We've found a successful start point!
    {
        System.out.println("A successful path starts at " + x + ", " + y);
        return true;
    }

    return startPath(mat, sum, path, y, x); // We'll have to keep looking
}

public static boolean findSum (int mat[][], int sum, int path[][], int i, int j)
{
    if(i==mat[0].length || j==mat[1].length || i<0 || j<0) // Bounds check
        return false;

    if (path[i][j] == 1) // Backtracking check
        return false;

    sum -= mat[i][j]; // Decrement sum

    if (sum >= 0) { // More to go? look around
        path[i][j] = 1;

        if (sum == 0) return true; // We made it!

         // If any path finds the end, don't try other paths
        boolean result = findSum(mat, sum, path, i+1, j);
        if (result) return true;
        result = findSum(mat, sum, path, i, j+1);
        if (result) return true;
        result = findSum(mat, sum, path, i-1, j);
        if (result) return true;
        result = findSum(mat, sum, path, i, j-1);

         // There was no successful paths, this is a dead end
        if (!result) path[i][j] = 0;
        return result;
    } else { // We're negative, overshot it
        return false;
    }
}

private static void print(int[][] arr)
{
    for(int i=0;i<arr[0].length;i++)
    {
        for(int j=0;j<arr[0].length;j++)
        {
            System.out.print(arr[i][j]+" ");
        }
        System.out.println();
    }
}

By the way when checking multidimensional array dimensions you are meaning to do arr.length and arr[0].length but instead you are doing arr[0].length and arr[1].length which would get the same dimension twice and cause an error if the array was not a square.

I've also allowed moving in any direction, by using the intended path to prevent re-checking the same node again. This could probably be a boolean array. Sorry if my x/y recursion is rough looking... I really prefer loops or .forEach or => or .map for that...

The -1, 0 can be cleaned up perhaps with optional parameters and not iterating on the first pass.

Let me know if there are any errors or edge cases you may find.


问:
In Java when one interface extends another, why would one redeclare a method in a subinterface?
I've been looking at the JMS API from J2EE and found a strange behavior where certain methods that are declared in an interface (e.g., createQueue in Session) are declared again in the subinterfaces such as QueueSession, and with identical documentation.

Since an subinterface "inherits" all the method declarations of the interface it inherits, and since the JavaDoc tool has no problem sorting out the JavaDocs of the subinterface and creating an "inherited operations" list, I can't figure out what this achieves.

The only think of is that initially the call was in Session, and then moved to QueueSession when the specific subclass was created, though then I would have expected to see something in the documentation of the upperclass. But this is just conjecture.

So the question is:
Is there a convincing reason to redeclare a method in a subinterface?

答: the only reason i know of is to widen the visibility of a method (i.e. clone from protected to public), but that does not seem to be the case here.</p>

OwnerDisplayName: Uri

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ray Tayek


问:
Override Vuetify Icon component
I have created a component which wraps the default  component to make it behave better with font-awesome.

Since font-awesome icons are not square it leads to inconsistent sizing and alignment issues. I resolved this by creating a wrapper which forces the element to be square and by using "font-size: 100%;" it ensure the irregularly shaped icon is contained.

Problem is that all of the vuetify components which have the "prepend-icon" / "append-icon" still appears badly when using font-awesome.

I would like to know if there is a way to import v-icon under a different name, use it in my wrapper component then define my wrapper as the rightful v-icon. Which in theory would resolve the alignment/sizing of all the vuetify components using prepend/append icon.

Does anyone have any knowledge how I could override a library component like this?

Thanks

答:
I've done a very similar thing, where I had to replace the default icons (in an older version of Vuetify) with SVG ones throughout the project while still wanting to use the v-icon component.

I ended up creating a custom icon component, called let's say, SVGIcon.vue. Then I defined some icon names like so:

```<code>Vue.use(Vuetify, {
  icons: {
    // reusable custom icon
    'vuejs': {
      component: FontAwesomeIcon,
      props: {
        icon: ['fab', 'vuejs']
      }
    }
  }
})
</code>```

(Example taken from the Vuetify documentation.)

You could also pass customized 'props' to each icon that you define.

Finally, you can use it like this:

<v-icon>$vuetify.icons.vuejs</v-icon> (vuejs being the name of the icon.)

This is what I ended up doing at least. For you, this might be too long-winded. In any case, do let me know what you think of this approach.

Title: Override Vuetify Icon component

Body:
I've done a very similar thing, where I had to replace the default icons (in an older version of Vuetify) with SVG ones throughout the project while still wanting to use the v-icon component.

I ended up creating a custom icon component, called let's say, SVGIcon.vue. Then I defined some icon names like so:

Vue.use(Vuetify, {
  icons: {
    // reusable custom icon
    'vuejs': {
      component: FontAwesomeIcon,
      props: {
        icon: ['fab', 'vuejs']
      }
    }
  }
})

(Example taken from the Vuetify documentation.)

You could also pass customized 'props' to each icon that you define.

Finally, you can use it like this:

<v-icon>$vuetify.icons.vuejs</v-icon> (vuejs being the name of the icon.)

This is what I ended up doing at least. For you, this might be too long-winded. In any case, do let me know what you think of this approach.


问:
Apache 2.4 with SSL config - Have 403 Forbidden
I have an issue with my apache config.
I just set a new windows server with Apache2.4 and SSL certificate but when i want to access to my https://localhost, i have a 403 Forbidden error.

This is my vhost-myproject.conf

```<code><VirtualHost *:443>
  DocumentRoot "D:/www/myproject/public"
  SetEnv APPLICATION_ENV "production"
  SetEnv ZF2_PATH D:/zend/ZendFramework-2.4.13/library
  ServerName myproject.fr
  <Directory "D:/www/myproject/public">
      Options +ExecCGI +FollowSymLinks
      DirectoryIndex index.php
      AllowOverride All
      Require all granted
  </Directory>

  SSLEngine on
  SSLCertificateFile "D:/mycertificate.crt"
  SSLCertificateKeyFile "D:/mykey.key"
</VirtualHost>
</code>```

And this is my .htaccess

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

</IfModule>
</code>```

And my hosts

```<code>127.0.0.1       localhost myprojet.fr
ip_server       myprojet.fr localhost
</code>```

Thank you for your help.

答: Check your httpd.conf file, and make sure that parameters "Listen" and "ServerName" are configured like "Listen 80" and "ServerName localhost:80".

Body:
I have an issue with my apache config.
I just set a new windows server with Apache2.4 and SSL certificate but when i want to access to my https://localhost, i have a 403 Forbidden error.

This is my vhost-myproject.conf

<VirtualHost *:443>
  DocumentRoot "D:/www/myproject/public"
  SetEnv APPLICATION_ENV "production"
  SetEnv ZF2_PATH D:/zend/ZendFramework-2.4.13/library
  ServerName myproject.fr
  <Directory "D:/www/myproject/public">
      Options +ExecCGI +FollowSymLinks
      DirectoryIndex index.php
      AllowOverride All
      Require all granted
  </Directory>

  SSLEngine on
  SSLCertificateFile "D:/mycertificate.crt"
  SSLCertificateKeyFile "D:/mykey.key"
</VirtualHost>

And this is my .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

</IfModule>

And my hosts

127.0.0.1       localhost myprojet.fr
ip_server       myprojet.fr localhost

Thank you for your help.


问:
What is wrong with my Factorial Function logic?
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

```<code>var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};
</code>```

答:
Where you said var newX = x * i;, that declares a new variable. Remove var.

x * i will return the square of x because lastly i is x.

function factorial(x) {
    var newX = 1;
    if(x > 0){
        for(var i = 1;i <= x;i++){
            newX = newX * i;
        }
        return newX;
    } else {
        return 1;
    }
};
console.log(factorial(5));
console.log(factorial(4));
console.log(factorial(0));```

Body:
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};


问:
Hide a list except the selected list option
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

```<code><ul class="links">
  <li class="us">United States</li>
  <li class="canada">Canada</li>
  <li class="france">France</li>
  <li class="china">China</li>
  <li class="englande">England</li>
</code>```

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

答:
```<code>$(function(){
  $('ul.links > li').click(function(){
      $('ul.links > li').fadeOut();
      $(this).fadeIn();
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

United States

Canada

France

China

England

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.


问:
Scroll a div under another div
I amd doing a small test about how the create a single web page with smooth scroll with html + css but I have a problem:
When I scroll down, the phone is supposed to go under the header, but instead it goes above it. How can I fix this?

the code css

```<code>section {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  section:nth-child(odd)
  {
      background: #ccc;
  }

/*inicia smartphone*/

.smartphone {
    position: relative;
    width: 360px;
    height: 640px;
    margin: auto;
    border: 16px blue solid;
    border-top-width: 60px;
    border-bottom-width: 60px;
    border-radius: 36px;
  }

  /* The horizontal line on the top of the device */
  .smartphone:before {
    content: '';
    display: block;
    width: 60px;
    height: 5px;
    position: absolute;
    top: -30px;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #333;
    border-radius: 10px;
  }

  /* The circle on the bottom of the device */
  .smartphone:after {
    content: '';
    display: block;
    width: 35px;
    height: 35px;
    position: absolute;
    left: 50%;
    bottom: -65px;
    transform: translate(-50%, -50%);
    background: #333;
    border-radius: 50%;
  }

  /* The screen (or content) of the device */
  .smartphone .content {
      position: inherit;
    height: 100%;
    background: red;
  }

/*acaba smartphone*/

/*inicia navbar*/

ul{
    width: 100%;
    background: #000;
    height: 50px;
    margin: 0px;
    padding: 0;
    position: fixed;
    top: 0;
    letter-spacing: 0;
    display: flex;
    justify-content: space-around;
}

ul li{
    list-style: none;
}

ul li a {
    color: white;
    line-height: 50px;
    box-sizing: border-box;
    font-weight: bold;
    text-transform: uppercase;
    text-decoration: none;
    font-size: 100%;
}

@media (max-width: 576px) {
    ul li a {
        font-size:12px;
    }
 }

 @media (max-width: 375px) {
    ul li a {
        font-size:10px;
    }
 }
 /*acaba navbar*/
</code>```

the html code

```<code>     <ul>
        <li><a href="#Inicio">Inicio</a></li>
        <li><a href="#AcercaDeX">Acerca de x</a></li>
        <li><a href="#QuienesSomos">Quienes Somos</a></li>
        <li><a href="#Contactanos">Contactanos</a></li>
      </ul>

<!--Logotipo y Nombre-->
<section class="section1" id="Inicio">
  <div class="smartphone">
    <div class="content">

    </div>
  </div>
</section>

<!--Que es la app-->
<section class="section2" id="AcercaDeX">
  <P>acerca de x </P>

</section>

<!--Quienes Somos-->
<section  class="section1" id="QuienesSomos">
  <P>quienes somos</P>

</section>

<!--Contactanos-->
<section class="section2" id="Contactanos">
  <P>contactanos</P>

</section>
</code>```

I tough it was aboutpositions, but honestly I do not know how to fix this

答:
Both your header (ul) and the smartphone element have positioning, so easy fix is to add z-index property to both. Then make sure the header has higher value than the smartphone and you are there.

section {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

section:nth-child(odd) {
  background: #ccc;
}

/*inicia smartphone*/

.smartphone {
  position: relative;
  width: 360px;
  height: 640px;
  margin: auto;
  border: 16px blue solid;
  border-top-width: 60px;
  border-bottom-width: 60px;
  border-radius: 36px;
  z-index: 99;
}

/* The horizontal line on the top of the device */

.smartphone:before {
  content: '';
  display: block;
  width: 60px;
  height: 5px;
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #333;
  border-radius: 10px;
}

/* The circle on the bottom of the device */

.smartphone:after {
  content: '';
  display: block;
  width: 35px;
  height: 35px;
  position: absolute;
  left: 50%;
  bottom: -65px;
  transform: translate(-50%, -50%);
  background: #333;
  border-radius: 50%;
}

/* The screen (or content) of the device */

.smartphone .content {
  position: inherit;
  height: 100%;
  background: red;
}

/*acaba smartphone*/

/*inicia navbar*/

ul {
  width: 100%;
  background: #000;
  height: 50px;
  margin: 0px;
  padding: 0;
  position: fixed;
  top: 0;
  letter-spacing: 0;
  display: flex;
  justify-content: space-around;
  z-index: 100;
}

ul li {
  list-style: none;
}

ul li a {
  color: white;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: bold;
  text-transform: uppercase;
  text-decoration: none;
  font-size: 100%;
}

@media (max-width: 576px) {
  ul li a {
    font-size: 12px;
  }
}

@media (max-width: 375px) {
  ul li a {
    font-size: 10px;
  }
}

/*acaba navbar*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Inicio</li>
  <li>Acerca de x</li>
  <li>Quienes Somos</li>
  <li>Contactanos</li>
</ul>

<!--Logotipo y Nombre-->
<section class="section1" id="Inicio">
  <div class="smartphone">
    <div class="content">

    </div>
  </div>
</section>

<!--Que es la app-->
<section class="section2" id="AcercaDeX">
  <P>acerca de x </P>

</section>

<!--Quienes Somos-->
<section class="section1" id="QuienesSomos">
  <P>quienes somos</P>

</section>

<!--Contactanos-->
<section class="section2" id="Contactanos">
  <P>contactanos</P>

</section></code>```

Title: Scroll a div under another div

Body:
I amd doing a small test about how the create a single web page with smooth scroll with html + css but I have a problem:
When I scroll down, the phone is supposed to go under the header, but instead it goes above it. How can I fix this?

the code css

section {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  section:nth-child(odd)
  {
      background: #ccc;
  }

/*inicia smartphone*/

.smartphone {
    position: relative;
    width: 360px;
    height: 640px;
    margin: auto;
    border: 16px blue solid;
    border-top-width: 60px;
    border-bottom-width: 60px;
    border-radius: 36px;
  }

  /* The horizontal line on the top of the device */
  .smartphone:before {
    content: '';
    display: block;
    width: 60px;
    height: 5px;
    position: absolute;
    top: -30px;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #333;
    border-radius: 10px;
  }

  /* The circle on the bottom of the device */
  .smartphone:after {
    content: '';
    display: block;
    width: 35px;
    height: 35px;
    position: absolute;
    left: 50%;
    bottom: -65px;
    transform: translate(-50%, -50%);
    background: #333;
    border-radius: 50%;
  }

  /* The screen (or content) of the device */
  .smartphone .content {
      position: inherit;
    height: 100%;
    background: red;
  }

/*acaba smartphone*/

/*inicia navbar*/

ul{
    width: 100%;
    background: #000;
    height: 50px;
    margin: 0px;
    padding: 0;
    position: fixed;
    top: 0;
    letter-spacing: 0;
    display: flex;
    justify-content: space-around;
}

ul li{
    list-style: none;
}

ul li a {
    color: white;
    line-height: 50px;
    box-sizing: border-box;
    font-weight: bold;
    text-transform: uppercase;
    text-decoration: none;
    font-size: 100%;
}

@media (max-width: 576px) {
    ul li a {
        font-size:12px;
    }
 }

 @media (max-width: 375px) {
    ul li a {
        font-size:10px;
    }
 }
 /*acaba navbar*/

the html code

Inicio

Acerca de x

Quienes Somos

Contactanos

acerca de x

quienes somos

contactanos

I tough it was aboutpositions, but honestly I do not know how to fix this

Body:
Both your header (ul) and the smartphone element have positioning, so easy fix is to add z-index property to both. Then make sure the header has higher value than the smartphone and you are there.

section {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

section:nth-child(odd) {
  background: #ccc;
}

/*inicia smartphone*/

.smartphone {
  position: relative;
  width: 360px;
  height: 640px;
  margin: auto;
  border: 16px blue solid;
  border-top-width: 60px;
  border-bottom-width: 60px;
  border-radius: 36px;
  z-index: 99;
}

/* The horizontal line on the top of the device */

.smartphone:before {
  content: '';
  display: block;
  width: 60px;
  height: 5px;
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #333;
  border-radius: 10px;
}

/* The circle on the bottom of the device */

.smartphone:after {
  content: '';
  display: block;
  width: 35px;
  height: 35px;
  position: absolute;
  left: 50%;
  bottom: -65px;
  transform: translate(-50%, -50%);
  background: #333;
  border-radius: 50%;
}

/* The screen (or content) of the device */

.smartphone .content {
  position: inherit;
  height: 100%;
  background: red;
}

/*acaba smartphone*/

/*inicia navbar*/

ul {
  width: 100%;
  background: #000;
  height: 50px;
  margin: 0px;
  padding: 0;
  position: fixed;
  top: 0;
  letter-spacing: 0;
  display: flex;
  justify-content: space-around;
  z-index: 100;
}

ul li {
  list-style: none;
}

ul li a {
  color: white;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: bold;
  text-transform: uppercase;
  text-decoration: none;
  font-size: 100%;
}

@media (max-width: 576px) {
  ul li a {
    font-size: 12px;
  }
}

@media (max-width: 375px) {
  ul li a {
    font-size: 10px;
  }
}

/*acaba navbar*/

<ul>
  <li><a href="#Inicio">Inicio</a></li>
  <li><a href="#AcercaDeX">Acerca de x</a></li>
  <li><a href="#QuienesSomos">Quienes Somos</a></li>
  <li><a href="#Contactanos">Contactanos</a></li>
</ul>

<!--Logotipo y Nombre-->
<section class="section1" id="Inicio">
  <div class="smartphone">
    <div class="content">

    </div>
  </div>
</section>

<!--Que es la app-->
<section class="section2" id="AcercaDeX">
  <P>acerca de x </P>

</section>

<!--Quienes Somos-->
<section class="section1" id="QuienesSomos">
  <P>quienes somos</P>

</section>

<!--Contactanos-->
<section class="section2" id="Contactanos">
  <P>contactanos</P>

</section>


问:
SmtpJs API not working! is there any way to send emails using SMTP server with JavaScript or JQuery
I have an application with JS , Jquery and NoSQL DB . I don't have any backend technology such as Node or C# . my web UI directly interacts with DataBase.

Now after submitting data to DB, I want to send email notifications to users.
I searched on internet and there are some articles which say we can't send emails with client side code as we deal with SMTP server.

the fallowing is from smtpjs.com

```<code><script src="js/smtp.js"></script>
<script>
     Email.send("vkxyz@abc.com",
                "vk@nyu.edu",
                "This is a subject",
                "this is the body",
                "smtp.qwe.io",
                "vkxyz@abc.com",
                "abcq4#");
</script>
</code>```

the above snippet is not working. tried some other snippets available on internet but nothing works.

By the way my SMTP server has firewall and accepts from local network only.
I din't get any connection error log  with above code.

so is it possible to send email with JavaScript Jquery , if so please kindly suggest the best practice

Thanks in Advance

答: Try using Elastic Email. It works with Smtp.js. I have used it before, and it has, for the most part, worked. Also, make sure you are using the latest versions of both.</p>

Body:
I have an application with JS , Jquery and NoSQL DB . I don't have any backend technology such as Node or C# . my web UI directly interacts with DataBase.

Now after submitting data to DB, I want to send email notifications to users.
I searched on internet and there are some articles which say we can't send emails with client side code as we deal with SMTP server.

the fallowing is from smtpjs.com

the above snippet is not working. tried some other snippets available on internet but nothing works.

By the way my SMTP server has firewall and accepts from local network only.
I din't get any connection error log  with above code.

so is it possible to send email with JavaScript Jquery , if so please kindly suggest the best practice

Thanks in Advance


问:
Sequel Pro and MySQL connection failed
I just installed mysql on mac from Homebrew

```<code>brew install mysql

mysql -V

mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)
</code>```

from terminal it works and I can login to mysql but from Sequel Pro it says

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary
  privileges, or try increasing the connection timeout (currently 10
  seconds).

MySQL said: Authentication plugin 'caching_sha2_password' cannot be
  loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):
  image not found

can't figure out what I am missing

答:
TL;DR: Sequel Pro is dead since 2016.  Don't downgrade your DB because of a tool. Move on to an alternative tool.

Update 2020: Sequel Pro is officially dead but unofficially alive!  You can find the "nightly" builds that don't have this issue (i.e. support Mysql 8 auth) in here: https://sequelpro.com/test-builds

Update 2021: Sequel Ace is a good similar alive alternative: https://github.com/Sequel-Ace/Sequel-Ace#installation (Credits to Maciej Kwas's answer)

All the other solutions here are recommending changing your DB settings (making it less secure, as advertised by MySQL) for the tool you are using.  That's not acceptable to me.

I have always been a huge fan of Sequel Pro, even donated to it.  But, with all my passion and love, I am sorry if the tool doesn't have any release since 2016.  YOLO, and I need to move on!

The alternative I found (from https://stackoverflow.com/a/55235533/2321594, thanks to @arcseldon) is DBeaver which supports MySQL 8's new authentication (non-legacy) method.

PS. The only trick in the tool side, not the DB side is when you are creating a MySQL 8 connection you might need to go to "Driver Properties" (later can be found in Edit Connection) and turn the value of allowPublicKeyRetrieval to true.

I needed this to connect to my MySQL container created using Docker.  To have the IP of MySQL be visible to the outside, for any other application in your ecosystem (not just this tool), you should either create a new user in MySQL, or pass -e MYSQL_ROOT_HOST=% in the run-time or as an ENV.

Title: Sequel Pro and MySQL connection failed

Body:
I just installed mysql on mac from Homebrew

brew install mysql

mysql -V

mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)

from terminal it works and I can login to mysql but from Sequel Pro it says

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary
  privileges, or try increasing the connection timeout (currently 10
  seconds).

MySQL said: Authentication plugin 'caching_sha2_password' cannot be
  loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):
  image not found

can't figure out what I am missing


问:
How to make my gvimrc file use my vimrc file (VIM)
TDLR; I am unable to edit gvim using the _vimrc file

Basically, I want to change some default settings (like background color) in the GUI version of vim (gvim). However, when I make changes to my .vimrc file, my gvim does not react to the changes.

I already have

if has("gui_number")
set number
colorscheme desert
endif

in my .vimrc file, and from what I've read that should make changes in my GVIM, but it doesn't.

I even tried to type some random stuff in the .vimrc file to see if GVIM would display an error, which it did not.

So i think the problem may be my gvim isn't reading my .vimrc file at all. So this may be a pathing problem?

This below is my .vimrc file

```<code>source $VIMRUNTIME/vimrc_example.vim
jhgfjhgjhg (This here was to test for an error)

if has('gui_running')
    set number
    colorscheme desert
endif

set diffexpr=MyDiff()
function MyDiff()
  let opt = '-a --binary '
  if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
  if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
  let arg1 = v:fname_in
  if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
  let arg1 = substitute(arg1, '!', '\!', 'g')
  let arg2 = v:fname_new
  if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
  let arg2 = substitute(arg2, '!', '\!', 'g')
  let arg3 = v:fname_out
  if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
  let arg3 = substitute(arg3, '!', '\!', 'g')
  if $VIMRUNTIME =~ ' '
    if &sh =~ '\<cmd'
      if empty(&shellxquote)
        let l:shxq_sav = ''
        set shellxquote&
      endif
      let cmd = '"' . $VIMRUNTIME . '\diff"'
    else
      let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
    endif
  else
    let cmd = $VIMRUNTIME . '\diff'
  endif
  let cmd = substitute(cmd, '!', '\!', 'g')
  silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3
  if exists('l:shxq_sav')
    let &shellxquote=l:shxq_sav
  endif

endfunction

Here is my .GVIMRC file

version 6.0
if &cp | set nocp | endif
let s:cpo_save=&cpo
set cpo&vim
map! <S-Insert> *
vmap  "*d
map Q gq
vmap [% [%m'gv``
vmap ]% ]%m'gv``
vmap a% [%v]%
vmap gx <Plug>NetrwBrowseXVis
nmap gx <Plug>NetrwBrowseX
vnoremap <silent> <Plug>NetrwBrowseXVis :call netrw#BrowseXVis()

nnoremap <silent> <Plug>NetrwBrowseX :call netrw#BrowseX(expand((exists("g:netrw_gx")? g:netrw_gx : '<cfile>')),netrw#CheckIfRemote())

vmap <C-Del> "*d
vmap <S-Del> "*d
vmap <C-Insert> "*y
vmap <S-Insert> "-d"*P
nmap <S-Insert> "*P
inoremap  u
let &cpo=s:cpo_save
unlet s:cpo_save
set backspace=indent,eol,start
set backup
set diffexpr=MyDiff()
set display=truncate
set guioptions=egmrLT
set helplang=En
set history=200
set hlsearch
set incsearch
set langnoremap
set nolangremap
set nrformats=bin,hex
set ruler
set runtimepath=~/vimfiles,C:\\Program\ Files\ (x86)\\Vim/vimfiles,C:\\Program\ Files\ (x86)\\Vim\\vim81,C:\\Program\ Files\ (x86)\\Vim\\vim81\\pack\\dist\\opt\\matchit,C:\\Program\ Files\ (x86)\\Vim/vimfiles/after,~/vimfiles/after
set scrolloff=5
set ttimeout
set ttimeoutlen=100
set undofile
set wildmenu
" vim: set ft=vim :
</code>```

I would hope that my gvim would display lines and a different background, but nothing happens.

edit: should my _vimrc file look exactly like my gvimrc?

答:
I figured it out guys.
So apparently I was supposed to create a _vimrc file in my home directory.

If you are on windows 7 and having the problem where you cant edit your _vimrc file in your VIM directory to change gvimrc, then its because you are trying to edit the wrong _vimrc!! You need to make a different user one in your home directory!

Windows 7:

Open vim, type in :e $HOME/_vimrc
And then put the new settings and save (then reopen GVIM)

Body:
TDLR; I am unable to edit gvim using the _vimrc file

Basically, I want to change some default settings (like background color) in the GUI version of vim (gvim). However, when I make changes to my .vimrc file, my gvim does not react to the changes.

I already have

if has("gui_number")
set number
colorscheme desert
endif

in my .vimrc file, and from what I've read that should make changes in my GVIM, but it doesn't.

I even tried to type some random stuff in the .vimrc file to see if GVIM would display an error, which it did not.

So i think the problem may be my gvim isn't reading my .vimrc file at all. So this may be a pathing problem?

This below is my .vimrc file

source $VIMRUNTIME/vimrc_example.vim
jhgfjhgjhg (This here was to test for an error)

if has('gui_running')
    set number
    colorscheme desert
endif

set diffexpr=MyDiff()
function MyDiff()
  let opt = '-a --binary '
  if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
  if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
  let arg1 = v:fname_in
  if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
  let arg1 = substitute(arg1, '!', '\!', 'g')
  let arg2 = v:fname_new
  if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
  let arg2 = substitute(arg2, '!', '\!', 'g')
  let arg3 = v:fname_out
  if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
  let arg3 = substitute(arg3, '!', '\!', 'g')
  if $VIMRUNTIME =~ ' '
    if &sh =~ '\<cmd'
      if empty(&shellxquote)
        let l:shxq_sav = ''
        set shellxquote&
      endif
      let cmd = '"' . $VIMRUNTIME . '\diff"'
    else
      let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
    endif
  else
    let cmd = $VIMRUNTIME . '\diff'
  endif
  let cmd = substitute(cmd, '!', '\!', 'g')
  silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3
  if exists('l:shxq_sav')
    let &shellxquote=l:shxq_sav
  endif

endfunction

Here is my .GVIMRC file

version 6.0
if &cp | set nocp | endif
let s:cpo_save=&cpo
set cpo&vim
map! <S-Insert> *
vmap  "*d
map Q gq
vmap [% [%m'gv``
vmap ]% ]%m'gv``
vmap a% [%v]%
vmap gx <Plug>NetrwBrowseXVis
nmap gx <Plug>NetrwBrowseX
vnoremap <silent> <Plug>NetrwBrowseXVis :call netrw#BrowseXVis()

nnoremap <silent> <Plug>NetrwBrowseX :call netrw#BrowseX(expand((exists("g:netrw_gx")? g:netrw_gx : '<cfile>')),netrw#CheckIfRemote())

vmap <C-Del> "*d
vmap <S-Del> "*d
vmap <C-Insert> "*y
vmap <S-Insert> "-d"*P
nmap <S-Insert> "*P
inoremap  u
let &cpo=s:cpo_save
unlet s:cpo_save
set backspace=indent,eol,start
set backup
set diffexpr=MyDiff()
set display=truncate
set guioptions=egmrLT
set helplang=En
set history=200
set hlsearch
set incsearch
set langnoremap
set nolangremap
set nrformats=bin,hex
set ruler
set runtimepath=~/vimfiles,C:\\Program\ Files\ (x86)\\Vim/vimfiles,C:\\Program\ Files\ (x86)\\Vim\\vim81,C:\\Program\ Files\ (x86)\\Vim\\vim81\\pack\\dist\\opt\\matchit,C:\\Program\ Files\ (x86)\\Vim/vimfiles/after,~/vimfiles/after
set scrolloff=5
set ttimeout
set ttimeoutlen=100
set undofile
set wildmenu
" vim: set ft=vim :

I would hope that my gvim would display lines and a different background, but nothing happens.

edit: should my _vimrc file look exactly like my gvimrc?


问:
Delete a json inside another in React
Imagine that I have this kind of JSON object on my react state:

```<code>this.state={
   parent:{
      childs:[
      child1:{
      },
      child2:{
      },
      child3:null,
       (...)
      ]

   }
}
</code>```

to delete the child1 I did the following method:

```<code>deleteChild1  = (index,test) => {

    const childs= [...this.state.parent.childs];

    childs[index] = {
        ...childs[index],
        child1: null
    }

    this.setState(prevState => ({
        ...prevState,
        parent: {
            ...prevState.parent,
            childs: [
                ...childs,
            ]
        }
    }))

}
</code>```

This works with no problem, but imagine that I have 100 childs, I have to do 100 methods like this but instead putting the child1 to null I have to put the child100, child99, you get the idea.

My question is that is another way to put the variable null.

Thanks!

答:
Currently your data structure isn't valid so its hard to write up a solution. If I try to create that exact state object it raises an exception Uncaught SyntaxError: Unexpected token : This is because you have an array written like an object. So first thing to do is adjust your state model to be valid syntax

```<code>this.state = {
  parent: {
    childs: {
      child1: {
      },
      child2: {
      },
      child3: null,
      ...
    }
  }
}
</code>```

Now, what you are describing / what you want to do is a dynamic key reference.
You can do this like so

```<code>const childTarget = 'child1'
childs = {
    ...childs,
   [childTarget]: null
}
</code>```

so to abstract that concept a little more. make it a function parameter

```<code>deleteChild = (childTarget) => {
</code>```

then when you want to remove any particular child you can let them pass their value to this function

```<code><Child onRemove={this.deleteChild} name={name} />
// name here would be like 'child1'
// assuming you are looping over state and rendering a child component for each item
</code>```

and when the child calls this function

```<code>this.props.onRemove(this.props.name)
</code>```

Title: Delete a json inside another in React

Body:
Imagine that I have this kind of JSON object on my react state:

this.state={
   parent:{
      childs:[
      child1:{
      },
      child2:{
      },
      child3:null,
       (...)
      ]

   }
}

to delete the child1 I did the following method:

deleteChild1  = (index,test) => {

    const childs= [...this.state.parent.childs];

    childs[index] = {
        ...childs[index],
        child1: null
    }

    this.setState(prevState => ({
        ...prevState,
        parent: {
            ...prevState.parent,
            childs: [
                ...childs,
            ]
        }
    }))

}

This works with no problem, but imagine that I have 100 childs, I have to do 100 methods like this but instead putting the child1 to null I have to put the child100, child99, you get the idea.

My question is that is another way to put the variable null.

Thanks!

Body:
Currently your data structure isn't valid so its hard to write up a solution. If I try to create that exact state object it raises an exception Uncaught SyntaxError: Unexpected token : This is because you have an array written like an object. So first thing to do is adjust your state model to be valid syntax

this.state = {
  parent: {
    childs: {
      child1: {
      },
      child2: {
      },
      child3: null,
      ...
    }
  }
}

Now, what you are describing / what you want to do is a dynamic key reference.
You can do this like so

const childTarget = 'child1'
childs = {
    ...childs,
   [childTarget]: null
}

so to abstract that concept a little more. make it a function parameter

deleteChild = (childTarget) => {

then when you want to remove any particular child you can let them pass their value to this function

<Child onRemove={this.deleteChild} name={name} />
// name here would be like 'child1'
// assuming you are looping over state and rendering a child component for each item

and when the child calls this function

this.props.onRemove(this.props.name)


问:
Is there an r function to produce excel 3d plot?
Is there any way to produce excel 3d plot in r?

I have a matrix and I would like to plot it in 3d surface format using R.
I managed to do it in excel and it gives me this plot https://drive.google.com/open?id=1hNqCguPX_ar8ueSK-u-yHTUYZxdyT_cE

I would like to produce same plot but with R
this plot is produced with this data

```<code>m<-matrix(c(7,73,195,195,416,625,120,52,178,178,349,454,6,83,164,164,244,0,3,52,150,150,329,330),nrow = 4, ncol = 6, byrow = T)
</code>```

答:
Unfortunately the dataset in use is not available, so there is no way to faithfully reproduce the image and expand the details.

To create the contour surface, it is interesting to use the ggplot2 package with the geom_raster function. But this will return a continuous surface.

```<code>library(ggplot2)
library(dplyr)

x <- seq(1, 6, 1)
y <- seq(0, 3, 1)
grid <- expand.grid(x = x,
                    y = y)
m <- matrix(c(7,73,195,195,416,625,120,52,178,178,349,454,6,
            83,164,164,244,0,3,52,150,150,329,330),
            nrow = 4, ncol = 6, byrow = T)
m2 <- m %>%
  t %>% as.data.frame()
grid <- grid %>%
  dplyr::mutate(response = c(m2$V1, m2$V2, m2$V3, m2$V4))

Palet <- c("royalblue2", "orangered3", "lavenderblush3", "gold3")

ggplot2::ggplot(grid, aes(x, y, z = response)) +
  geom_raster(aes(fill = response)) +
  scale_fill_gradientn(colours = Palet, limits = c(0, 800)) +
  theme_void() +
  theme(legend.position = "bottom")
</code>```

In addition, it is possible to perform data manipulation and work with the discrete fill. Where for each interval, a color will be assigned.

```<code>grid2 <- grid %>%
  dplyr::mutate(cor = ifelse(response >= 0 & response < 200, 1,
                             ifelse(response >= 200 & response < 400, 2,
                                    ifelse(response >= 400 & response < 600, 3,
                                           ifelse(response >= 600, 4, "error")))))

ggplot2::ggplot(grid2, aes(x, y, z = response)) +
  geom_raster(aes(fill = cor)) +
  scale_fill_manual(values = Palet, labels = c("0-200", "200-400",
                                               "400-600", "600-800"),
                    name = "") +
  theme_void() +
  theme(legend.position = "bottom")
</code>```

However, if it is considered that in matrix m each cell is intensity, it is possible to generate a 3D plot.

```<code>library(plot3D)
persp3D(z = m, theta = 60)
</code>```

3D surface plot from 2D matrix

Plot 3D data in R

Impressive package for 3D and 4D graph - R software and data visualization

Body:
Is there any way to produce excel 3d plot in r?

I have a matrix and I would like to plot it in 3d surface format using R.
I managed to do it in excel and it gives me this plot https://drive.google.com/open?id=1hNqCguPX_ar8ueSK-u-yHTUYZxdyT_cE

I would like to produce same plot but with R
this plot is produced with this data

m<-matrix(c(7,73,195,195,416,625,120,52,178,178,349,454,6,83,164,164,244,0,3,52,150,150,329,330),nrow = 4, ncol = 6, byrow = T)

Body:
Unfortunately the dataset in use is not available, so there is no way to faithfully reproduce the image and expand the details.

To create the contour surface, it is interesting to use the ggplot2 package with the geom_raster function. But this will return a continuous surface.

library(ggplot2)
library(dplyr)

x <- seq(1, 6, 1)
y <- seq(0, 3, 1)
grid <- expand.grid(x = x,
                    y = y)
m <- matrix(c(7,73,195,195,416,625,120,52,178,178,349,454,6,
            83,164,164,244,0,3,52,150,150,329,330),
            nrow = 4, ncol = 6, byrow = T)
m2 <- m %>%
  t %>% as.data.frame()
grid <- grid %>%
  dplyr::mutate(response = c(m2$V1, m2$V2, m2$V3, m2$V4))

Palet <- c("royalblue2", "orangered3", "lavenderblush3", "gold3")

ggplot2::ggplot(grid, aes(x, y, z = response)) +
  geom_raster(aes(fill = response)) +
  scale_fill_gradientn(colours = Palet, limits = c(0, 800)) +
  theme_void() +
  theme(legend.position = "bottom")

In addition, it is possible to perform data manipulation and work with the discrete fill. Where for each interval, a color will be assigned.

grid2 <- grid %>%
  dplyr::mutate(cor = ifelse(response >= 0 & response < 200, 1,
                             ifelse(response >= 200 & response < 400, 2,
                                    ifelse(response >= 400 & response < 600, 3,
                                           ifelse(response >= 600, 4, "error")))))

ggplot2::ggplot(grid2, aes(x, y, z = response)) +
  geom_raster(aes(fill = cor)) +
  scale_fill_manual(values = Palet, labels = c("0-200", "200-400",
                                               "400-600", "600-800"),
                    name = "") +
  theme_void() +
  theme(legend.position = "bottom")

However, if it is considered that in matrix m each cell is intensity, it is possible to generate a 3D plot.

library(plot3D)
persp3D(z = m, theta = 60)

3D surface plot from 2D matrix

Plot 3D data in R

Impressive package for 3D and 4D graph - R software and data visualization


问:
How to redirect to a certain URL if a
 tag appears
I have a problem in Blogger's contact form, when submitted, it just apprehends a message saying that it was sent over and does not allow redirects.

So, I had an idea that when the

 tag appears on the screen, some script could redirect to a url , only when the message appears.

Any idea my dears of how I can achieve this?, please?

```<code><form name='contact-form'>
<div>
<b>your Name:</b> *</div>
<input class='contact-form-name' id='ContactForm1_contact-form-name' name='name' size='60' type='text' value=''/>

<div>
<b> valid E-mail:</b> *</div>
<input class='contact-form-email' id='ContactForm1_contact-form-email' name='email' size='60' type='text' value=''/>

<div>
<b>your message:</b> *</div>
<textarea class='contact-form-email-message' id='ContactForm1_contact-form-email-message' name='email-message' rows='5'></textarea>
<p>
</p>
<div style='text-align: center; max-width: 450px; width: 100%'>
<p class='contact-form-error-message' id='ContactForm1_contact-form-error-message'>
</p>
<p class='contact-form-success-message' id='ContactForm1_contact-form-success-message'>
</p>
</div>
<input class='contact-form-button contact-form-button-submit' onClick="window.location='https://google.com';" id='ContactForm1_contact-form-submit' type='button' value='Send'/>
</form>
</div>
</code>```

答:
if the page refreshes after the contact form is sent then you can use JS to redirect on the condition that the page contains your specific element

```<code> if (document.getElementById('ContactForm1_contact-form-success-message') ) {
    window.location.href = #yourRedirect;
}
</code>```

I hope this helps!

Title: How to redirect to a certain URL if a <p> tag appears

Body:
I have a problem in Blogger's contact form, when submitted, it just apprehends a message saying that it was sent over and does not allow redirects.

So, I had an idea that when the

 tag appears on the screen, some script could redirect to a url , only when the message appears.

Any idea my dears of how I can achieve this?, please?

<form name='contact-form'>

your Name: *

<input class='contact-form-name' id='ContactForm1_contact-form-name' name='name' size='60' type='text' value=''/>

 valid E-mail: *

<input class='contact-form-email' id='ContactForm1_contact-form-email' name='email' size='60' type='text' value=''/>

your message: *

<textarea class='contact-form-email-message' id='ContactForm1_contact-form-email-message' name='email-message' rows='5'></textarea>

<input class='contact-form-button contact-form-button-submit' onClick="window.location='https://google.com';" id='ContactForm1_contact-form-submit' type='button' value='Send'/>
</form>

Body:
if the page refreshes after the contact form is sent then you can use JS to redirect on the condition that the page contains your specific element

 if (document.getElementById('ContactForm1_contact-form-success-message') ) {
    window.location.href = #yourRedirect;
}

I hope this helps!


问:
Sending Bearer Token with HttpPost in Android
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

```<code>HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
</code>```

The error I get is 401 Unauthorized on every attempt.

答:
Why don't you use OK Http for networking requests? Then you can do something like this:</p>

```<code>        val request = Request.Builder()
                .url(yourUrl)
                .header("Authorization", "Bearer $yourToken")
                .post(yourBody)
                .build()
</code>```

Body:
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));

The error I get is 401 Unauthorized on every attempt.

Body:
Why don't you use OK Http for networking requests? Then you can do something like this:

        val request = Request.Builder()
                .url(yourUrl)
                .header("Authorization", "Bearer $yourToken")
                .post(yourBody)
                .build()


问:
how to scan for keys whose values got updated since last SCAN
I'd like to periodically scan thru a redis instance for keys that changed since the last scan. in between the scans i don't want to process the keys.

eg one key could get a thousand updates between scans. i care for the most recent value only when doing the next periodic scan.

答:
There is no built-in way in Redis to achieve that (yet).

You could, for example, recode your app and add some sort of a way to track updates. For example, wherever you're calling SET foo bar, also call ZADD updated <timestamp> foo. Then, you can use the 'updated' Sorted Set to retrieve updated keys.

Alternatively, you can try using RedisGears to automate the tracking part (for starters). Assuming that you have RedisGears running (i.e. docker run -it -p 6379:6379 redislabs/redisgears), you can do something like the following:

```<code>$ cat gear.py
def addToUpdatedZset(x):
    import time
    now = time.time()
    execute('ZADD', 'updated', now, x['key'])
    return x

GB().filter(lambda x: x['key'] != 'updated').foreach(addToUpdatedZset).register('*')

$ redis-cli RG.PYEXECUTE "$(cat gear.py)"
OK
$ redis-cli
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> KEYS *
1) "updated"
2) "foo"
127.0.0.1:6379> ZRANGE updated 0 -1 WITHSCORES
1) "foo"
2) "1559339877.1392548"
127.0.0.1:6379> SET baz qux
OK
127.0.0.1:6379> KEYS *
1) "updated"
2) "baz"
3) "foo"
127.0.0.1:6379> ZRANGE updated 0 -1 WITHSCORES
1) "foo"
2) "1559339877.1392548"
3) "baz"
4) "1559339911.5493586"
</code>```

Body:
There is no built-in way in Redis to achieve that (yet).

You could, for example, recode your app and add some sort of a way to track updates. For example, wherever you're calling SET foo bar, also call ZADD updated <timestamp> foo. Then, you can use the 'updated' Sorted Set to retrieve updated keys.

Alternatively, you can try using RedisGears to automate the tracking part (for starters). Assuming that you have RedisGears running (i.e. docker run -it -p 6379:6379 redislabs/redisgears), you can do something like the following:

$ cat gear.py
def addToUpdatedZset(x):
    import time
    now = time.time()
    execute('ZADD', 'updated', now, x['key'])
    return x

GB().filter(lambda x: x['key'] != 'updated').foreach(addToUpdatedZset).register('*')

$ redis-cli RG.PYEXECUTE "$(cat gear.py)"
OK
$ redis-cli
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> KEYS *
1) "updated"
2) "foo"
127.0.0.1:6379> ZRANGE updated 0 -1 WITHSCORES
1) "foo"
2) "1559339877.1392548"
127.0.0.1:6379> SET baz qux
OK
127.0.0.1:6379> KEYS *
1) "updated"
2) "baz"
3) "foo"
127.0.0.1:6379> ZRANGE updated 0 -1 WITHSCORES
1) "foo"
2) "1559339877.1392548"
3) "baz"
4) "1559339911.5493586"


问:
Change dynamically type of the Model in asp.net MVC
I want to change the type of my Model, from ObjectType1 to ObjectType2, when I call the View. I am using MVC 4. Can somebody tell me if this is possible at all and if yes, how?

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Master1.Master" Inherits="System.Web.Mvc.ViewPage<Path.Path.Path.ObjectType1>" %>
</code>```

Scenario:
I have an Action that sends an ObjectType1 to a strongly-typed View. Also I send another ObjectType2 in TempData. In the View I display information from the first Model and the Second Model. But I want to edit and submit ObjectType1. Now I have second View, in which I'm doing the other way around. The problem is that I have two Views with almost the same code and I have to reload the page if I want to swith from one to another. I submit the object with Post method, if it matters.

答:
Generally a view is bound to one model. but in case you are curious about that? then you can do by using this simple trick. I apply this trick several times and it worked for me.

From your Action Method.

You have to return a dynamic value type from
Action method.

For Example:

In first Case: you have to return List

In second Case: you have to return List

So you can write code something list this:

Action Method

```<code>public ActionResult foo(int? productId = null, int? customerId = null)
{
    // if ProductId has Value:
    if(productId != null)
    {
        Viewbag.ModelType = "Product";
        //... Logic
        return View((dynamic)(productsList))
    }

    // if CustomerId has Value:
    if(CustomerId != null)
    {
        Viewbag.ModelType = "Customer";
        //... Logic
        return View((dynamic)(CustomerList))
    }
}
</code>```

View

```<code>@model IEnumerable(dynamic)
//...

if(Viewbag.ModelType == "Customer")
{ // do this.. }

if(Viewbag.ModelType == "Product")
{ // do this.. }

etc...
</code>```

I hope you get the idea...

Body:
I want to change the type of my Model, from ObjectType1 to ObjectType2, when I call the View. I am using MVC 4. Can somebody tell me if this is possible at all and if yes, how?

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Master1.Master" Inherits="System.Web.Mvc.ViewPage<Path.Path.Path.ObjectType1>" %>

Scenario:
I have an Action that sends an ObjectType1 to a strongly-typed View. Also I send another ObjectType2 in TempData. In the View I display information from the first Model and the Second Model. But I want to edit and submit ObjectType1. Now I have second View, in which I'm doing the other way around. The problem is that I have two Views with almost the same code and I have to reload the page if I want to swith from one to another. I submit the object with Post method, if it matters.

Body:
Generally a view is bound to one model. but in case you are curious about that? then you can do by using this simple trick. I apply this trick several times and it worked for me.

From your Action Method.

You have to return a dynamic value type from
Action method.

For Example:

In first Case: you have to return List

In second Case: you have to return List

So you can write code something list this:

Action Method

public ActionResult foo(int? productId = null, int? customerId = null)
{
    // if ProductId has Value:
    if(productId != null)
    {
        Viewbag.ModelType = "Product";
        //... Logic
        return View((dynamic)(productsList))
    }

    // if CustomerId has Value:
    if(CustomerId != null)
    {
        Viewbag.ModelType = "Customer";
        //... Logic
        return View((dynamic)(CustomerList))
    }
}

View

@model IEnumerable(dynamic)
//...

if(Viewbag.ModelType == "Customer")
{ // do this.. }

if(Viewbag.ModelType == "Product")
{ // do this.. }

etc...

I hope you get the idea...


问:
MySQL Database connects, but says the name is incorrect
I am trying to install Pligg on my linux server, but am having difficulties.  I am at the point where I need to point Pligg to a SQL server, and setup the server on using these instructions:

http://codelikezell.com/setting-up-rails-mysql-php-apache-and-git-on-ec2/

Pligg asks for:

Database Name

Database Username

Database Password

Database Server
Table Prefix

For Database Name, I use mysqld - which Putty confirms is running.  I login as root and the password I assigned, set the Server to localhost.

I get this error, however: Error: Connected to the database, but the database name is incorrect.

How can it connect to the DB if the name is not correct?  Am I doing something to point Pligg to the wrong DB?

Thanks!

答: Database name is not the same as process name(mysqld). Leave it blank or enter 'test' as db name; as far as I remember mysql always creates test database by default.


答:
We can do it in dplyr by keeping only dates that have entries equal to number of sensors;

df %>% group_by(Datetime) %>%  filter(n()==n_distinct(.$Sensor))

#> # A tibble: 4 x 3
#> # Groups:   Datetime [1]
#>   Datetime                X Sensor
#>   <dttm>              <dbl>  <dbl>
#> 1 2018-08-13 17:40:00 0.741      1
#> 2 2018-08-13 17:40:00 0.760      2
#> 3 2018-08-13 17:40:00 0.744      3
#> 4 2018-08-13 17:40:00 0.553      4
```

<hr>

<hr>

<p>Another method in <code>base</code> would be converting the data from long to wide and keeping only completed cases (the ones with data for all <code>Sensors</code>) and then convert the results back to long format;</p>

<pre class="lang-r prettyprint-override"><code>wide <- reshape(df, idvar = "Datetime", timevar = "Sensor", direction = "wide")

reshape(na.omit(wide), direction = "long", varying = list(names(wide)[-1]), v.names = "X",
        idvar = "Datetime", timevar = "Sensor", times = unique(df$Sensor)); rm(wide)
#>                                  Datetime Sensor          X
#> 2018-08-13 17:40:00.1 2018-08-13 17:40:00      1  0.7410448
#> 2018-08-13 17:40:00.2 2018-08-13 17:40:00      2  0.7602078
#> 2018-08-13 17:40:00.3 2018-08-13 17:40:00      3  0.7441643
#> 2018-08-13 17:40:00.4 2018-08-13 17:40:00      4  0.5529621
</code>```

Created on 2019-05-31 by the reprex package (v0.3.0)

Title: Subsetting data frame based on max number of instances of another column

Body:
I have some data in the following format, where multiple sensors have data with timestamps.  The is some overlap on timestamps between each sensor, however there are gaps in some of the sensors where no data is present at all.  I am looking to subset the data in a way where I only pull timestamps/rows where there is a record for each sensor.  Here is a small example:

library(lubridate)
set.seed(88)

start_date = as.POSIXct("2018-08-13 17:30:00 GMT")
datetime = seq(start_date, start_date + minutes(20), by = "5 min")

df <- data.frame(Datetime = datetime, X = runif(15), Sensor =
c(rep(1,5),rep(2,3),rep(3,4),rep(4,3)))
df$Datetime[12] <- df$Datetime[12] + minutes(5)
df

              Datetime          X Sensor
1  2018-08-13 17:30:00 0.71008793      1
2  2018-08-13 17:35:00 0.23754185      1
3  2018-08-13 17:40:00 0.43144271      1
4  2018-08-13 17:45:00 0.06922129      1
5  2018-08-13 17:50:00 0.78754994      1
6  2018-08-13 17:30:00 0.74219767      2
7  2018-08-13 17:35:00 0.49680693      2
8  2018-08-13 17:40:00 0.28491360      2
9  2018-08-13 17:45:00 0.62937634      3
10 2018-08-13 17:50:00 0.28642922      3
11 2018-08-13 17:30:00 0.44928292      3
12 2018-08-13 17:40:00 0.97428628      3
13 2018-08-13 17:40:00 0.10112843      4
14 2018-08-13 17:45:00 0.89788230      4
15 2018-08-13 17:50:00 0.53922885      4

Desired output here would be:

                  Datetime         X Sensor
3  2018-08-13 17:40:00 0.4314427      1
8  2018-08-13 17:40:00 0.2849136      2
12 2018-08-13 17:40:00 0.9742863      3
13 2018-08-13 17:40:00 0.1011284      4

Body:
We can do it in dplyr by keeping only dates that have entries equal to number of sensors;

df %>% group_by(Datetime) %>%  filter(n()==n_distinct(.$Sensor))

#> # A tibble: 4 x 3
#> # Groups:   Datetime [1]
#>   Datetime                X Sensor
#>   <dttm>              <dbl>  <dbl>
#> 1 2018-08-13 17:40:00 0.741      1
#> 2 2018-08-13 17:40:00 0.760      2
#> 3 2018-08-13 17:40:00 0.744      3
#> 4 2018-08-13 17:40:00 0.553      4

Another method in base would be converting the data from long to wide and keeping only completed cases (the ones with data for all Sensors) and then convert the results back to long format;

wide <- reshape(df, idvar = "Datetime", timevar = "Sensor", direction = "wide")

reshape(na.omit(wide), direction = "long", varying = list(names(wide)[-1]), v.names = "X",
        idvar = "Datetime", timevar = "Sensor", times = unique(df$Sensor)); rm(wide)
#>                                  Datetime Sensor          X
#> 2018-08-13 17:40:00.1 2018-08-13 17:40:00      1  0.7410448
#> 2018-08-13 17:40:00.2 2018-08-13 17:40:00      2  0.7602078
#> 2018-08-13 17:40:00.3 2018-08-13 17:40:00      3  0.7441643
#> 2018-08-13 17:40:00.4 2018-08-13 17:40:00      4  0.5529621

Created on 2019-05-31 by the reprex package (v0.3.0)


问:
How to send some list to another class and how to connect it
Im doing my HW to school, making some game.. i took blackjack bcs i thought its easy, but now i know that isnt easy for me.. So i need help with solution.

I tried to connect somehow the lists "cards", but idk if it is connected or not.

Here is shuffle

```<code>public class Shuffle
{
    public List<Card>cards;
    public void Michani()
    {
        Random ran = new Random();
        int r = cards.Count;
        while (r > 1)
        {
            int n = ran.Next();
            Card card = cards[n];
            cards[n] = cards[r];
            cards[r] = card;
        }
    }
}

public class Card
{
    public CardValue Value { get; set; }
    public CardSuit Suit { get; set; }
    public int Weight { get; set; }
}

public enum CardValue : int
{
    Eso = 1,
    Dvojka = 2,
    Trojka = 3,
    Ctyrka = 4,
    Petka = 5,
    Sestka = 6,
    Sedmicka = 7,
    Osmicka = 8,
    Devitka = 9,
    Desitka = 10,
    Jack = 11,
    Queen = 12,
    King = 13,
}

public enum CardSuit : int
{
    Hearts = 1,
    Spades = 2,
    Clubs = 3,
    Diamons = 4
}
</code>```

Here is ending card:

```<code>public class DeckGen
{
    public List<Card> cards;

    public void Deck()
    {
        for (int v = 0; v < 13; v++)
        {
            for (int s = 0; s < 4; s++)
            {
                cards.Add(new Card() { Suit = (CardSuit)s, Value = (CardValue)v });
                if (s <= 8)
                {
                    cards[cards.Count - 1].Weight = s + 1;
                }
                else
                {
                    cards[cards.Count - 1].Weight = 10;
                }

            };
        }

    }
}
</code>```

Here is creating the deck:

```<code>public class DrawCard
{
    public List<Card> cards { get; }

    public Card Lizani()
    {
        if (cards.Count <= 0)
        {
            DeckGen();
            Shuffle();
        }
        Card returnedcard = cards[cards.Count - 1];
        cards.RemoveAt(cards.Count - 1);
        return returnedcard;
    }

    public void Shuffle()
    {

    }

    public void DeckGen()
    {

    }
}
</code>```

Here is drawing a card:

答:
There is a bunch of problems here, and a blog worthy of the best way to do this. But may i suggest and old fashioned (debatable) approach of just using and extension method

Note i fixed bunch of mistakes

```<code>public static class CardUtils
{
   private static Random ran = new Random();
   public static void Shuffle(this List<Card> cards)
   {
      var n = cards.Count;
      while (n > 1)
      {
         n--;
         var k = ran.Next(n + 1);
         Card value = cards[k];
         cards[k] = cards[n];
         cards[n] = value;
      }
   }
}
</code>```

Usage

```<code>chards.Shuffle();
</code>```

Note i say old fashioned as we tend not to use static classes like this these days for test-ability , and DI service. However, i think this is a nice simple solution and accessible everywhere you need it

Also Note There are better randomization techniques, your players might get angsty because the shuffler isn't working that good

Body:
Im doing my HW to school, making some game.. i took blackjack bcs i thought its easy, but now i know that isnt easy for me.. So i need help with solution.

I tried to connect somehow the lists "cards", but idk if it is connected or not.

Here is shuffle

public class Shuffle
{
    public List<Card>cards;
    public void Michani()
    {
        Random ran = new Random();
        int r = cards.Count;
        while (r > 1)
        {
            int n = ran.Next();
            Card card = cards[n];
            cards[n] = cards[r];
            cards[r] = card;
        }
    }
}

public class Card
{
    public CardValue Value { get; set; }
    public CardSuit Suit { get; set; }
    public int Weight { get; set; }
}

public enum CardValue : int
{
    Eso = 1,
    Dvojka = 2,
    Trojka = 3,
    Ctyrka = 4,
    Petka = 5,
    Sestka = 6,
    Sedmicka = 7,
    Osmicka = 8,
    Devitka = 9,
    Desitka = 10,
    Jack = 11,
    Queen = 12,
    King = 13,
}

public enum CardSuit : int
{
    Hearts = 1,
    Spades = 2,
    Clubs = 3,
    Diamons = 4
}

Here is ending card:

public class DeckGen
{
    public List<Card> cards;

    public void Deck()
    {
        for (int v = 0; v < 13; v++)
        {
            for (int s = 0; s < 4; s++)
            {
                cards.Add(new Card() { Suit = (CardSuit)s, Value = (CardValue)v });
                if (s <= 8)
                {
                    cards[cards.Count - 1].Weight = s + 1;
                }
                else
                {
                    cards[cards.Count - 1].Weight = 10;
                }

            };
        }

    }
}

Here is creating the deck:

public class DrawCard
{
    public List<Card> cards { get; }

    public Card Lizani()
    {
        if (cards.Count <= 0)
        {
            DeckGen();
            Shuffle();
        }
        Card returnedcard = cards[cards.Count - 1];
        cards.RemoveAt(cards.Count - 1);
        return returnedcard;
    }

    public void Shuffle()
    {

    }

    public void DeckGen()
    {

    }
}

Here is drawing a card:

Body:
There is a bunch of problems here, and a blog worthy of the best way to do this. But may i suggest and old fashioned (debatable) approach of just using and extension method

Note i fixed bunch of mistakes

public static class CardUtils
{
   private static Random ran = new Random();
   public static void Shuffle(this List<Card> cards)
   {
      var n = cards.Count;
      while (n > 1)
      {
         n--;
         var k = ran.Next(n + 1);
         Card value = cards[k];
         cards[k] = cards[n];
         cards[n] = value;
      }
   }
}

Usage

chards.Shuffle();

Note i say old fashioned as we tend not to use static classes like this these days for test-ability , and DI service. However, i think this is a nice simple solution and accessible everywhere you need it

Also Note There are better randomization techniques, your players might get angsty because the shuffler isn't working that good


问:
Bootstrap generated HTML files not rendering CSS in PDF using wkhtmltopdf
I am trying to convert HTML file to PDF file using wkhtmltopdf and it is creating file correctly but missing all bootstrap related styles.

BELOW IS LINUX COMMAND TO CONVERT HTML TO PDF:

```<code>xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf $htmlFile $pdfFile
</code>```

The application is HTTPS enabled and all HTML files are SOURCING as HTTPS as BELOW:

```<code>https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css
https://code.jquery.com/jquery-2.2.4.js
https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
https://code.jquery.com/ui/1.11.4/jquery-ui.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css
</code>```

Any help is appreciated since i am stuck and not sure why bootstrap style is not loading correctly.

答:
wkhtmltopdf does not work well with Bootstrap. If you search the internet you will find that some suggest to explicitly set the viewport size (this seems to fix it for some versions). Add this to your command:

--viewport-size 1024x768

In your case you would get:

xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf --viewport-size 1024x768 $htmlFile $pdfFile

Another (the best I found) explanation is that Bootstrap has all col-xx-n classes inside media queries except for the col-xs-n class. Add the col-xs-n class to all elements might solve your problems. For me that solved the problems except for dynamically generated content (using jQuery).

Body:
I am trying to convert HTML file to PDF file using wkhtmltopdf and it is creating file correctly but missing all bootstrap related styles.

BELOW IS LINUX COMMAND TO CONVERT HTML TO PDF:

xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf $htmlFile $pdfFile

The application is HTTPS enabled and all HTML files are SOURCING as HTTPS as BELOW:

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css
https://code.jquery.com/jquery-2.2.4.js
https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
https://code.jquery.com/ui/1.11.4/jquery-ui.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css

Any help is appreciated since i am stuck and not sure why bootstrap style is not loading correctly.


问:
Finding duplicates in an array using C
I came across a problem in this link https://leetcode.com/problems/contains-duplicate/. There is an input array of integers. Find out if there any repeating integers, then return true else false.

How can I optimize this code?

Can I improve the logic further?

In my code below,there is an if condition if(hPtr && hPtr->key == *(nums+i)). I am using the array elements as keys. If so, each key can't be unique if the same element is repeated twice right? So can I modify the if condition as if(hPtr->key == *(nums + i))?

If any other mistakes, please feel free to point out.

There is already a hashtable library available in C http://troydhanson.github.io/uthash/userguide.html and wrote the below code.

```<code>struct hash {
        int key;
        int value;
        UT_hash_handle hh;
};

    struct hash *hashtable = NULL;

    void addToHash(int key, int value)
    {
      struct hash *map;
      //I am using the array elements as hash keys
      HASH_FIND_INT(hashtable, &key, map);

      if(map == NULL)
      {
        map = (struct hash*)malloc(sizeof(struct hash));
        map->key = key;
        HASH_ADD_INT(hashtable, key, map);
      }
      map->value = value;
    }

    struct hash *findInHash(int key)
    {
        struct hash *h;
        HASH_FIND_INT(hashtable, &key, h);
        return h;
    }

    bool containsDuplicate(int* nums, int numsSize) {
        struct hash *hPtr;
        int target = 0;
        hashtable = NULL;
        if((numsSize <= 1) || (nums == 0)) return false;

        int i, index1 = 0;

        for(i = 0; i < numsSize; i++)
        {
            /*The below statement will look if the key is already present in
              the hashtable*/
            hPtr = findInHash(*(nums + i) - target);
            /*If the key is found already, then it look for the value of that
            key. If the value and the current array element is same, then a
            duplicate exist*/
            if(hPtr && hPtr->key == *(nums+i))
               return true;
            addToHash(*(nums + i), i);
        }
        struct hash *temp;
        HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);}
        return false;
    }
</code>```

答:
I think the solution is simpler than what you think:

```<code>typedef struct {
  int capacity;
  int len;
  int **keys;
  int *values;
} Map;
</code>```

My struct has keys as arrays of two integers, one for the identifier and the other is the index of the values array, that's how hash maps works indeed.

```<code>void initMap(Map *map) {
  map -> capacity = 5;
  map -> len = 0;
  map -> keys = malloc(map -> capacity * sizeof(int));
  map -> values = malloc(map -> capacity * sizeof(int));
}
</code>```

Then we have a function to initialize the map, easy...

```<code>void add(Map *map, int k, int v) {
  if (map -> len == map -> capacity - 1) resize(map);
  map -> values[map -> len] = v;
  map -> keys[map -> len] = malloc(sizeof(int) * 2);
  map -> keys[map -> len][0] = k;
  map -> keys[map -> len][1] = map -> len;
  map -> len++;
}
</code>```

a function to put elements in the map

```<code>void resize(Map *map) {
  map -> capacity *= 2;
  map -> keys = realloc(map -> keys, map -> capacity * sizeof(int) * 2);
  map -> values = realloc(map -> keys, map -> capacity * sizeof(int));
}
</code>```

and a function to resize the map if the limit is reached

By decoupling the key index and the index on the values array you can have the keys sorted, making your live much easier.
the values will be in their array in the same order as they come but the index will be sorted from 0 to N.
To do this i'll use a simple selsort algorithm, it's not the best but the easiest...

```<code>void sort(Map *map) {
  int i, j;
  int min, tmp;
  for (i = 0; i < map -> len - 1; i++) {
    min = i;
    for (j = i + 1; j < map -> len; j++) {
      if(map -> keys[j][0] < map -> keys[min][0] ) min = j;
    }

    tmp = map -> keys[min][0];
    map -> keys[min][0] = map -> keys[i][0];
    map -> keys[i][0] = tmp;
  }
}
</code>```

with this you will have your index shorted. I'd execute it right after adding a new entry to the map, inside the add() function, it's out here now just for testing.

Once you have your index sorted you can write a binary search algorithm, eeeasy. Now you can now if a key is already in the map.

```<code>int find_recursive(Map *map, int start, int end, int key) {
   if (end >= start) {
        int mid = start + (end - start) / 2;

        if (map -> keys[mid][0] == key)
            return mid;

        if (map -> keys[mid][0] > key)
            return find_recursive(map, start, mid - 1, key);

        return find_recursive(map, mid + 1, end, key);
    }
    return -1;
}

int find(Map *map, int key) {
    return find_recursive(map, 0, map -> len, key);
}
</code>```

Sooo

```<code>  Map map;
  initMap(&map);

  add(&map, 3, 12);
  add(&map, 12, 1);
  add(&map, 1, 2);

  printf("%d %d %d\n",
      map.keys[0][0],
      map.keys[1][0],
      map.keys[2][0]
      );
  // Should print 3 12 1

  sort(&map);

  printf("%d %d %d\n",
      map.keys[0][0],
      map.keys[1][0],
      map.keys[2][0]
      );
  // Should print 1 3 12

  printf("%d\n", find(&map, 12));
  // Should print 2 (the index, 3rd entry)
</code>```

I can't do a working example now, i cant compile with my machine, maybe later at home... sorry :(

EDIT: forgot to say... to get the value you have to do map.values[map.keys[find(&map, key)][1]].

Of course this should be a function:

```<code>int get(Map *map, key) {
  int keyindex = find(map, key);
  int valueindex = map -> keys[index][1];
  return map -> values[valueindex];
}
</code>```

Forgot to say that, by decoupling the keys from the values you can use as value any type you want, even whole structures...

enjoy

Title: Finding duplicates in an array using C

Body:
I came across a problem in this link https://leetcode.com/problems/contains-duplicate/. There is an input array of integers. Find out if there any repeating integers, then return true else false.

How can I optimize this code?

Can I improve the logic further?

In my code below,there is an if condition if(hPtr && hPtr->key == *(nums+i)). I am using the array elements as keys. If so, each key can't be unique if the same element is repeated twice right? So can I modify the if condition as if(hPtr->key == *(nums + i))?

If any other mistakes, please feel free to point out.

There is already a hashtable library available in C http://troydhanson.github.io/uthash/userguide.html and wrote the below code.

struct hash {
        int key;
        int value;
        UT_hash_handle hh;
};

    struct hash *hashtable = NULL;

    void addToHash(int key, int value)
    {
      struct hash *map;
      //I am using the array elements as hash keys
      HASH_FIND_INT(hashtable, &key, map);

      if(map == NULL)
      {
        map = (struct hash*)malloc(sizeof(struct hash));
        map->key = key;
        HASH_ADD_INT(hashtable, key, map);
      }
      map->value = value;
    }

    struct hash *findInHash(int key)
    {
        struct hash *h;
        HASH_FIND_INT(hashtable, &key, h);
        return h;
    }

    bool containsDuplicate(int* nums, int numsSize) {
        struct hash *hPtr;
        int target = 0;
        hashtable = NULL;
        if((numsSize <= 1) || (nums == 0)) return false;

        int i, index1 = 0;

        for(i = 0; i < numsSize; i++)
        {
            /*The below statement will look if the key is already present in
              the hashtable*/
            hPtr = findInHash(*(nums + i) - target);
            /*If the key is found already, then it look for the value of that
            key. If the value and the current array element is same, then a
            duplicate exist*/
            if(hPtr && hPtr->key == *(nums+i))
               return true;
            addToHash(*(nums + i), i);
        }
        struct hash *temp;
        HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);}
        return false;
    }

Body:
I think the solution is simpler than what you think:

typedef struct {
  int capacity;
  int len;
  int **keys;
  int *values;
} Map;

My struct has keys as arrays of two integers, one for the identifier and the other is the index of the values array, that's how hash maps works indeed.

void initMap(Map *map) {
  map -> capacity = 5;
  map -> len = 0;
  map -> keys = malloc(map -> capacity * sizeof(int));
  map -> values = malloc(map -> capacity * sizeof(int));
}

Then we have a function to initialize the map, easy...

void add(Map *map, int k, int v) {
  if (map -> len == map -> capacity - 1) resize(map);
  map -> values[map -> len] = v;
  map -> keys[map -> len] = malloc(sizeof(int) * 2);
  map -> keys[map -> len][0] = k;
  map -> keys[map -> len][1] = map -> len;
  map -> len++;
}

a function to put elements in the map

void resize(Map *map) {
  map -> capacity *= 2;
  map -> keys = realloc(map -> keys, map -> capacity * sizeof(int) * 2);
  map -> values = realloc(map -> keys, map -> capacity * sizeof(int));
}

and a function to resize the map if the limit is reached

By decoupling the key index and the index on the values array you can have the keys sorted, making your live much easier.
the values will be in their array in the same order as they come but the index will be sorted from 0 to N.
To do this i'll use a simple selsort algorithm, it's not the best but the easiest...

void sort(Map *map) {
  int i, j;
  int min, tmp;
  for (i = 0; i < map -> len - 1; i++) {
    min = i;
    for (j = i + 1; j < map -> len; j++) {
      if(map -> keys[j][0] < map -> keys[min][0] ) min = j;
    }

    tmp = map -> keys[min][0];
    map -> keys[min][0] = map -> keys[i][0];
    map -> keys[i][0] = tmp;
  }
}

with this you will have your index shorted. I'd execute it right after adding a new entry to the map, inside the add() function, it's out here now just for testing.

Once you have your index sorted you can write a binary search algorithm, eeeasy. Now you can now if a key is already in the map.

int find_recursive(Map *map, int start, int end, int key) {
   if (end >= start) {
        int mid = start + (end - start) / 2;

        if (map -> keys[mid][0] == key)
            return mid;

        if (map -> keys[mid][0] > key)
            return find_recursive(map, start, mid - 1, key);

        return find_recursive(map, mid + 1, end, key);
    }
    return -1;
}

int find(Map *map, int key) {
    return find_recursive(map, 0, map -> len, key);
}

Sooo

  Map map;
  initMap(&map);

  add(&map, 3, 12);
  add(&map, 12, 1);
  add(&map, 1, 2);

  printf("%d %d %d\n",
      map.keys[0][0],
      map.keys[1][0],
      map.keys[2][0]
      );
  // Should print 3 12 1

  sort(&map);

  printf("%d %d %d\n",
      map.keys[0][0],
      map.keys[1][0],
      map.keys[2][0]
      );
  // Should print 1 3 12

  printf("%d\n", find(&map, 12));
  // Should print 2 (the index, 3rd entry)

I can't do a working example now, i cant compile with my machine, maybe later at home... sorry :(

EDIT: forgot to say... to get the value you have to do map.values[map.keys[find(&map, key)][1]].

Of course this should be a function:

int get(Map *map, key) {
  int keyindex = find(map, key);
  int valueindex = map -> keys[index][1];
  return map -> values[valueindex];
}

Forgot to say that, by decoupling the keys from the values you can use as value any type you want, even whole structures...

enjoy


问:
How to swap TRUE and FALSE in a dataframe with dplyr
I'm looking to change values into their opposite (T becomes F, and vice versa) in specific rows in a column in a datatable

I know that x <- !x works for T/F variables but how to finish this dplyr approach:

```<code>library(dplyr)
library(datatable)
library(magrittr)
mtcars$selected <- T
mtcars %>% select(selected) %>% slice(c(1,4,5)) %>% mutate(??)
</code>```

答:
Here's one way -</p>

```<code>mtcars %>%
  select(selected) %>%
  slice(c(1,4,5)) %>%
  mutate(
    selected = !selected # or as.logical(1 - selected)
  )
</code>```

Body:
I'm looking to change values into their opposite (T becomes F, and vice versa) in specific rows in a column in a datatable

I know that x <- !x works for T/F variables but how to finish this dplyr approach:

library(dplyr)
library(datatable)
library(magrittr)
mtcars$selected <- T
mtcars %>% select(selected) %>% slice(c(1,4,5)) %>% mutate(??)

Body:
Here's one way -

mtcars %>%
  select(selected) %>%
  slice(c(1,4,5)) %>%
  mutate(
    selected = !selected # or as.logical(1 - selected)
  )


问:
Parse 1 column into 3 columns using DB2 SQL
Using DB2 for z/OS 10, I'm have a column (ADDRESS3) in a table that contains city, state, and zipcode all in one column. But, the formatting is somewhat "free-form". (see code below)

I can successfully parse the city by taking everything before the comma. Using only DB2 SQL, how would I parse out the state and zipcode?

```<code>SELECT ADDRESS3,
       TRIM(SUBSTR(ADDRESS3,1,LOCATE(',', ADDRESS3)-1)) AS CITY
  FROM MYTABLE

ADDRESS3                            CITY
----------------------------------  -------------
GRANADA HILLS       ,CA 91344       GRANADA HILLS
SIMI VALLEY         ,CA 93065       SIMI VALLEY
BUENA PARK          ,CA 90621       BUENA PARK
SHERMAN OAKS        ,CA 91423       SHERMAN OAKS
GLENDALE            ,CA 91203-2089  GLENDALE
VENTURA             ,CA 93002       VENTURA
HAWTHORNE           ,CA 90250       HAWTHORNE
PASADENA            ,CA 91185-2594  PASADENA
BEVERLY HILLS       ,CA 90211       BEVERLY HILLS
ARCADIA             ,CA 91007       ARCADIA
WALNUT CREEK        ,CA 94596       WALNUT CREEK
INDEPENDANCE        ,CA 93526       INDEPENDANCE
LOS ANGELES         ,CA 90017       LOS ANGELES
</code>```

Ultimately, I'd like the query results to look like this:

```<code>CITY          STATE ZIP
------------- ----- -----
GRANADA HILLS CA    91344
SIMI VALLEY   CA    93065
BUENA PARK    CA    90621
SHERMAN OAKS  CA    91423
GLENDALE      CA    91203
VENTURA       CA    93002
HAWTHORNE     CA    90250
PASADENA      CA    91185
...
</code>```

Thanks!

答:
Based on your code, if the state is 2 chars and zip 5 chars:</p>

```<code>SELECT
  ADDRESS3,
  TRIM(SUBSTR(ADDRESS3, 1, LOCATE(',', ADDRESS3)-1)) AS CITY,
  TRIM(SUBSTR(ADDRESS3, LOCATE(',', ADDRESS3) + 1), 2) AS STATE,
  TRIM(SUBSTR(ADDRESS3, LOCATE(',', ADDRESS3) + 4), 5) AS ZIP
FROM MYTABLE
</code>```

Body:
Using DB2 for z/OS 10, I'm have a column (ADDRESS3) in a table that contains city, state, and zipcode all in one column. But, the formatting is somewhat "free-form". (see code below)

I can successfully parse the city by taking everything before the comma. Using only DB2 SQL, how would I parse out the state and zipcode?

SELECT ADDRESS3,
       TRIM(SUBSTR(ADDRESS3,1,LOCATE(',', ADDRESS3)-1)) AS CITY
  FROM MYTABLE

ADDRESS3                            CITY
----------------------------------  -------------
GRANADA HILLS       ,CA 91344       GRANADA HILLS
SIMI VALLEY         ,CA 93065       SIMI VALLEY
BUENA PARK          ,CA 90621       BUENA PARK
SHERMAN OAKS        ,CA 91423       SHERMAN OAKS
GLENDALE            ,CA 91203-2089  GLENDALE
VENTURA             ,CA 93002       VENTURA
HAWTHORNE           ,CA 90250       HAWTHORNE
PASADENA            ,CA 91185-2594  PASADENA
BEVERLY HILLS       ,CA 90211       BEVERLY HILLS
ARCADIA             ,CA 91007       ARCADIA
WALNUT CREEK        ,CA 94596       WALNUT CREEK
INDEPENDANCE        ,CA 93526       INDEPENDANCE
LOS ANGELES         ,CA 90017       LOS ANGELES

Ultimately, I'd like the query results to look like this:

CITY          STATE ZIP
------------- ----- -----
GRANADA HILLS CA    91344
SIMI VALLEY   CA    93065
BUENA PARK    CA    90621
SHERMAN OAKS  CA    91423
GLENDALE      CA    91203
VENTURA       CA    93002
HAWTHORNE     CA    90250
PASADENA      CA    91185
...

Thanks!

Body:
Based on your code, if the state is 2 chars and zip 5 chars:

SELECT
  ADDRESS3,
  TRIM(SUBSTR(ADDRESS3, 1, LOCATE(',', ADDRESS3)-1)) AS CITY,
  TRIM(SUBSTR(ADDRESS3, LOCATE(',', ADDRESS3) + 1), 2) AS STATE,
  TRIM(SUBSTR(ADDRESS3, LOCATE(',', ADDRESS3) + 4), 5) AS ZIP
FROM MYTABLE