text:
Q: Make dummy variables from multiple columns and create new dataframe I need to make a dataframe of dummies from survey data where respondents have stated words in several columns in a dataframe. Here is a simplified example to illustrate what I need to do? A single word is here represented by a letter.
id <- c(1:6)
v.1 <- c("a","b","d","e","a","c")
v.2 <- c("b","a","a","a","b","a")
v.3 <- c("e","c","b","b","e","b")

df <- data.frame(id,v.1,v.2,v.3)

> df
  id v.1 v.2 v.3
1  1   a   b   e
2  2   b   a   c
3  3   d   a   b
4  4   e   a   b
5  5   a   b   e
6  6   c   a   b

Here is my wanted output?
> print(df.dummy)
   id  a b c d e
1:   1 1 1 0 0 1
2:   2 1 1 1 0 0
3:   3 1 1 0 1 0
4:   4 1 1 0 0 1
5:   5 1 1 0 0 1
6:   6 1 1 1 0 0

Any ideas?

A: You can use reshape2:
library(reshape2)
dcast( melt(df,id.var="id"), id ~ value, length)

which gives
  id a b c d e
1  1 1 1 0 0 1
2  2 1 1 1 0 0
3  3 1 1 0 1 0
4  4 1 1 0 0 1
5  5 1 1 0 0 1
6  6 1 1 1 0 0

Or use recast to "melt and cast in a single step":
recast(df, id ~ value, id.var = "id", length)

Without using a package, you could do table( rep(df$id,ncol(df)-1), unlist(df[-1]) ).


text:
Q: c# decimal to binary wrong output I'm a newbie in C# and I was trying to convert decimal numbers to binary but the output is wrong. I want to know what's wrong with it. For example, I gave input "69" value. The output was "11" instead of "1000101".
double input = Convert.ToDouble(Console.Readline());
double i;
double newNumber = 0;

for (i = Int32.MaxValue; i >= 0; i--)
{
    if (input >= Math.Pow(2, i))
    {
        newNumber = input - Math.Pow(2, i);
        Console.Write("1");
        break;
    }
}

for (i -= i; i >= 0; i--)
{
    if (newNumber >= Math.Pow(2, i))
    {
        newNumber = newNumber - Math.Pow(2, i);
        Console.Write("1");
    }
    else
    {
        Console.Write("0");
    }
}

Console.ReadKey();

A: Your code almost works, just replace i -= i with i -= 1 on your second loop, since you already processed i, you want to start 1 position lower.
Note:
Although it works, this strategy is a bit off, since it loops through int.MaxValue. I would suggest to find another way to get the most significant bit. You could use Log2(input) to get your starting index.
Here is a bit shortened version of yours.
double input = Convert.ToDouble(Console.ReadLine());

if (input == 0)
{
    Console.Write("0");
    return;
}

for (int i = (int)Math.Log2(input); i >= 0; i--)
{
    if (input >= Math.Pow(2, i))
    {
        input -= Math.Pow(2, i);
        Console.Write("1");
    }
    else
    {
        Console.Write("0");
    }
}

Console.ReadKey();

A: There is a short way... You can use

Convert.ToString(numberInBase10, targetBase)

Here is an example:
int[] numbersBase10 = { 7, 10, 23, 45, 69, 99 };

foreach (int number in numbersBase10)
{
    string numberBase2 = Convert.ToString(number, 2);
    Console.WriteLine($"{number} => {numberBase2}");
}

The output is:
7 => 111
10 => 1010
23 => 10111
45 => 101101
69 => 1000101
99 => 1100011

redpajama_set_name: RedPajamaStackExchange


text:
Q: please help me in using inheritance of object I tried using inheritance in all my object class. below are my example
public class Member : Order
{
   private string _employeeId;
   private string _employeeName;

   public string EmployeeId
   {
       get { return _employeeId; }
       set { _employeeId = value; }
   }

   public string EmployeeName
   {
       get { return _employeeName; }
       set { _employeeName = value; }
   }

}

public class Order
{
    private int _id;
   private string _itemName;

   public string ID
   {
       get { return _id; }
       set { _id = value; }
   }

   public string ItemName
   {
       get { return _itemName; }
       set { _itemName= value; }
   }

}

A: Inheritance makes  an "IS A" relation between classes.
It is highly unlikely that "a Member is an Order", so you're not using it correctly.
Without further information it's hard to give you better advice.
A more plausible model would be :

*

*An Employee is a Person

*A Member is an Employee (doubt here)

*A Member has 0 or more  Orders

class Person { }
class Employee: Person { }
class Member : Employee
{
    public IList<Order> Orders { get; private set; }
}

class Order
{
   public int MemberId { get; private set; }
}

A: Since you are using C#, you could shorten your example by using automatic properties:
public class Order
{
    public string Id { get; set; }
    public string ItemName { get; set; }
}

public class Member : Order
{
    public string EmployeeId { get; set; }
    public string EmployeeName { get; set; }
}

Now, is the problem that you want to use the same Name and Id properties on Order and Member? Then you would do this instead:
public class Order
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Member : Order
{
}

But, could you give more detail about what you want these two classes to be used for? Why does a Member inherit from Order?

A: Yes, that looks fine. I can't say if it makes sense to use inheritance that way for those specific classes, but if that is what you want, you did it correctly.
In C# version 3 and later you can use shorthand to create properties:
public class Member : Order  {

  public string EmployeeId { get; set; }
  public string EmployeeName { get; set; }

}

public class Order {

   public string ID { get; set; }
   public string ItemName { get; set; }

}


text:
Q: User gets logged in but still shows error message in magento 2.3.3 My customer gets logged in successfully into their account but still magento shows error message.
https://nimb.ws/GicM2b
How to resolve this?

A: From the login page , somehow your code reaches to this controller page (file: /vendor/magento/module-customer/Controller/Account/LoginPost.php), here you will see that message , then you can edit here or in your custom module.
EditI checked your case , so in your case this file will be present in your custom module, override is given already by you , you need to recognize/ find your modified controller file, it will be very similar to above mentioned file and you can further edit that custom controller file.
Edit 2 - Image is added for your reference

Thanks
Vibhore


text:
Q: Excel Addin is not showing up if i protect my macro in Excel add-in  by password then i can't add it to a "New tab" through customize ribbon option
Is there any option where can i add it to a customize ribbon as i don't want to send it unprotected

A: You can password protect the code module in the VBE editor. Whether this solution works for you depends on the type of add-in ofcourse.

VBE>Project Explorer>WBAProject (right click)>VBA Project
  Properties>Protection>Lock Project for Viewing and set Password


text:
Q: ICMP spoofing won't flood Victim [Python Scapy] I have been trying to perform a smurf attack on my phone, I have been using scapy in python to create spoofed ICMP pakcets with the spoofed source as my phone. I then sent these packets to all computers on the network (IPs are present the list send_icmp) repeatedly. However, my phone kept on connecting to the internet fine. What's wrong? Here's my code:
def smurf(victim):

    for ip in send_icmp:
        t = threading.Thread(target = __send_spoofed_icmp, args = (ip,victim))
        t.daemon = True
        t.start()
        icmp_threads.append(t)

    for t in icmp_threads:
        t.join()

def __send_spoofed_icmp(ip,victim):
    print("[+] Sending packets to "+ip)
    packet = IP(src=victim,dst=ip)/ICMP()
    while 1:
        send(packet,verbose = 0)


text:
Q: How to give all permisions on a self-signed applet I need to know how set, when user accepts to run the applet, all permissions.
This is about an application where my user trusts absolutely on the application, so he will give all permissions.
The issue is we always have problems with permissions and the applet cannot sign and send the XML it is supposed to.
Sometimes we have to restart computer to permissions work.
I don't want to change the java.policy file, I want to put all permissions inside the applet.
Any help would be very very appreciated.


text:
Q: how to create a team leaderboard with info from 4 tables? This is tricky, I have been tasked with creating an team leader board where individuals complete tasks for a score. The score is defined in the table "station" and every time a user completes a task- a post is created in the posts table with the id of the station and their RFID (radio frequency ID). There is a team table which defines the team name.
i need a way to get the sum of all the post scores (joined points from stations table) a teams members have participated in.
The result should be sorted be team score and look something like if we have 4 teams with 4 members who participated in 4 events- whats the total score for each team
Team name one (Teams.name) | score

Team name two (Teams.name) | score

Team name three (Teams.name) | score

The tables -
CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rfid` varchar(50) NOT NULL,
  `station_id` int(11) NOT NULL,
  `updated_at` datetime NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

-- --------------------------------------------------------

Table structure for table stations
CREATE TABLE `stations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` text NOT NULL,
  `points` int(11) NOT NULL,
  `logic` varchar(200) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1023 ;

-- --------------------------------------------------------

Table structure for table teams
CREATE TABLE `teams` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

-- --------------------------------------------------------

Table structure for table users
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rfid` varchar(50) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `team` int(11) NOT NULL,
  `quiz_score` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

I have created an query for an individual leaderboard-
SELECT users.first_name, users.last_name, posts.rfid, sum(stations.points) score
FROM posts
JOIN users ON posts.rfid = users.rfid
JOIN stations ON posts.station_id = stations.id
GROUP BY posts.rfid
ORDER BY score DESC LIMIT 0 , 100

this is what i have got so far for the team one
SELECT name, (SELECT sum(stations.points) score FROM posts
      JOIN users ON posts.rfid = users.rfid
      JOIN stations ON posts.station_id = stations.id
  WHERE users.team = teams.id
      GROUP BY posts.rfid) team_score FROM teams

//subquery returns more than one row

I think this might be the correct answer
SELECT name,
    (SELECT sum(stations.points) score FROM posts
         JOIN users ON posts.rfid = users.rfid
         JOIN stations ON posts.station_id = stations.id
      WHERE users.team = teams.id ) team_score
  FROM teams


text:
Q: overflow:hidden not working with border-radius in Chrome I'm trying to make a circle-shaped image with an overlay that shows on hover. However, the "hitbox" of hovering (and clicking) is incorrect, as shown in the snippet below.
This issue seems to only occur in Chrome (not sure about Safari). I've found some fixes on the Internet, but none of them worked. JSFiddle for testing

$(document).ready(function() {
 $(".circle").click(function() {
  alert($(this).attr("id"));
 });
});
#canvas {
 width: 100%;
 padding-bottom: 75%;
 position: relative;
 overflow: hidden;
 background-color: #eee;
}
.circle {
 position: absolute;
 width: 25%;
 padding-bottom: 25%;
 border-radius: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 overflow: hidden;
 cursor: pointer;
 /*https://stackoverflow.com/a/32987370/5532169*/
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 /*https://stackoverflow.com/a/25206004/5532169*/
 z-index: 1;
 /*https://stackoverflow.com/a/10296258/5532169*/
 -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
 /*https://stackoverflow.com/a/16878347/5532169*/
 -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}
.mid {
 width: 100%;
 height: 100%;
 position: absolute;
}
.inner {
 width: 100%;
 height: 100%;
 position: relative;
}
.inner>* {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 100%;
 height: 100%;
}
.hover {
 background-color: rgba(255, 255, 255, 0.6);
 opacity: 0;
 transition: opacity 0.5s;
}
.hover:hover {
 opacity: 100;
 transition: opacity 0.5s;
}
span {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 width: 72%;
 text-align: center;
 font-family: monospace;
 font-size: 2em;
 font-weight: bold;
 color: #08f;
}

    Hello World!

Edit: Tested in Firefox 57, works without problem. IE and Edge were tested already, so it's a Chrome-/webkit-specific issue.

A: The blocks in HTML are square defined by position (x, y) and size (width, height) so the browser can have a simplified idea of what is on the page and interact with. So even with border-radius, mask-image, etc... your .circle div is still a square with coming drawn within.

To avoid that, you can't use a dynamic selector like :hover because it will use the shape of the div and that is a square. You need to use javascript to detect mouse position when hovering your block and with that execute an animation (with sinus and cosinus calculation).
You can get the mouse position with something like this :

I also found this topic talking about getting elements position on the page.

A: You can change only .circle class these properties:
width: 26%;
padding-bottom: 26%;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;


text:
Q: Unordered horizontal list switching to vertical on mobile I have an unordered vertical list as a navigation bar that is changing to a horizontal list on mobile devices. How do I prevent the list from switching to vertical and stay horizontal within the div element it's in.
Side note: the resulting code snippet is showing the list as vertical, but I suspect it's because the window is being perceived as mobile given it's width
Edit: there also appears to be a small scrollable gap to the right of the screen on mobile.

body {
    background-color: #E5E5E5;
}

#nav_bar {
    background-color: #2F2F2F;
    height: 60px;
    width: 100%;
    top: 0;
    left: 0;
    position: absolute;
}

#nav_logo {
    background-image: url('../img/nav_logo.png');
    width: 250px;
    height: 40px;
    top: 15%;
    left: 10%;
    position: absolute;
}

@media (max-width: 629px) {
    div#nav_logo {
      background-image: url('../img/nav_logo_mobile.png');
      width: 60px;
      height: 39px;
    }
}

ul.nav {
    list-style-type: none;
    left: 70%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    position: absolute;
}

li.nav {
    float: left;
}

li.nav a {
    font-family: 'Roboto Condensed', sans-serif;
    display: block;
    color: white;
    text-align: center;
    padding: 18px;
    text-decoration: none;
}

li.nav a:hover {
    text-decoration: underline;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title></title>

    <link rel="stylesheet" href="css/style.css" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Oswald|PT+Sans" rel="stylesheet">

HOME

CONTACT

ABOUT

A: I think the problem is with "left: 70%". On mobile devices the space is just not enough to keep the links in a line.
Give them more space on small screens. I would recommend to set the right value instead of left, btw. On small screens you could just set it to right: 0.

A: I found some code on w3schools and tried to implement it in your code. This is what I came up with:
ul.nav {
  position: relative;
  overflow: hidden;
  background-color: #333;
}

li.nav {
    float: left;
}

li.nav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}


text:
Q: How to Send response after for each loop completed Response.json should execute after foreach loop completes its execution

var todoarr = (req.body.data) ? req.body.data : undefined
    todoarr.forEach(function(element) {
         if(element.done == true) {
             TodoService.removeTodo(element, function(success) {
             });
         }
        });
        res.json("success");

A: You can try to use async.js http://caolan.github.io/async/ .
each method http://caolan.github.io/async/docs.html#each
Or you can try use Promise.all.
For example:
let promiseArr = [];
todoarr.forEach(function(element) {
     if(element.done == true) {
         promiseArr.push(somePromiseMethod(element));
     }
});
//now execute promise all
Promise.all(promiseArr)
.then((result) => res.send("success"))
.catch((err) => res.send(err));

More info here. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Some promise example:
function somePromiseMethod(element) {
   return new Promise((resolve,reject) => {
      TodoService.removeTodo(element, function(success) {
            resolve();
         });
   });
}

Hope this helps.

A: You can't send multiple responses on single request, the only thing you can do it's a single response with the array of results:
es with async:
const async = require('async')
// FIX ME: this isn't correctly handled!
const todoarr = (req.body.data) ? req.body.data : undefined

let results = []

async.each(todoarr, function(element, callback) {

  console.log('Processing todo ' + element)

  if(element.done == true) {
    TodoService.removeTodo(element, function(err, success) {
      if(err){
        callback(err)
      } else {
        results.push(success)
        callback(null, success)
      }
    })
  }
}, function(err) {
  if(err) {
    console.log('A element failed to process', err)
    res.status(500).json(err)
  } else {
    console.log('All elements have been processed successfully')
    // array with the results of each removeTodo job
    res.status(200).json(results)
  }
})

A: You can send the response inside the callback function of forEach.
Modify your function so that it will call res.json() on the last iteration only.
Example:
var todoarr = (req.body.data) ? req.body.data : undefined
todoarr.forEach(function(element,index) {

    if(element.done == true) {
        TodoService.removeTodo(element, function(success) {
        });
    }

    if(index==todoarr.length-1){
        res.json("success");
    }
});

However, it may not be according to coding standards but it can definitely solve the problem.


text:
Q: Kotlin Can't create @Autowired field in Class that are annotated with @Configuration @EnableWebMvc Autowired field is null when initializing the project:
package com.lynas.config

import org.springframework.stereotype.Component
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
open class InterceptorConfig : HandlerInterceptorAdapter() {

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any?): Boolean {

        return true
    }
}

package com.lynas.config

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter

@Configuration
@EnableWebMvc
@ComponentScan("com.lynas")
open class WebConfig() : WebMvcConfigurerAdapter() {

    // this field show null
    @Autowired
    lateinit var interceptorConfig: InterceptorConfig

    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(interceptorConfig)
    }

}

lateinit var interceptorConfig: InterceptorConfig is null when I run the application. How to fix this?
full code https://github.com/lynas/kotlinSpringBug

A: try @field:Autowired lateinit var interceptorConfig or @set:Autowired which will tell kotlin compiler to put annotations explicitly on field/setter. by default it places them on "property" which is kotlin-only construct and Java may have problems accessing it. refer to kotlin docs here


text:
Q: How to catch an empty Vuex Store state but have a computed property react to it when initialized I am working on a Project in Vue Storefront with Vuex.
I have the following element to sort products in my webshop
      <SfSelect
        class="navbar__select sort-by"
        ref="SortBy"
        :selected="selectedSorting"
        @change="setSortingAttribute"
      >
        <SfSelectOption
          v-for="attribute in getSortingAttributes"
          :key="attribute.id"
          :value="attribute.title"
          class="sort-by__option"
          @click="setSelectedSortingAttribute(attribute)"
        >
          {{ attribute.title }}
        </SfSelectOption>
      </SfSelect>

Where           v-for="attribute in getSortingAttributes" does a for-loop on all available filters.
These filters are called from the Vuex Store State via the following computed property:
getSortingAttributes: function () {
  if (store.state.tweakwise.tweakwiseLayeredNavigationAttributes
      .properties.sortfields
  ) {
    var tempSortAttributes =
      this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes
        .properties.sortfields;

    return tempSortAttributes;
  }
},

This array is in the Vuex Store (tweakwiseLayeredNavigationAttributes.properties.sortfields) where .poperties is an object in the array. The array is filled via an API call, this call is trigged via a Mount() in the same class as the SfSelect function, which I mentioned above.
Eventhough i added an if-statement to the getSortingAttributes to prevent it from calling undefined data and made it a computed property (to call it as soon as the data is available), I still get the following error:
Error during render : CategoryX/SubcategoryY/
TypeError: Cannot read property 'sortfields' of undefined

A: You should add safeguard(s) to your code - either using the new nullish coalescing operator or the old-school boolean OR:
getSortingAttributes()
{
  return this.$store.state.tweakwise?.tweakwiseLayeredNavigationAttributes?.properties?.sortfields || [];
},

getSortingAttributes()
{
  return (((this.$store.state.tweakwise || {}).tweakwiseLayeredNavigationAttributes || {}).properties || {}).sortfields || [];
},


text:
Q: When exploring a user, how can I view the url of the page they viewed? In user explorer, I see default page_view events but they don't show page paths when I click into them. New to GA4 and could use any advice. I was expecting the default parameters (page_location, page_referrer) to show up but I only see custom parameters.

One thought I had was to add a custom page_path to the gtag config but since I am running a SPA, this wasn't working as expected. I was thinking of setting up a custom page view event in the front end code and not use the default page_view.


text:
Q: Gitlab's CI docker in docker login and test containers I have a project that needs a TestContainers running to execute end2end tests.
The Containers 's image is another project which docker image is pushed to GitLab's Container Registry. This means that, whenever I want to do docker pull of this image, I need to do a docker login first.
Locally it works fine, I just do a login, run my tests and everything's ok.. on the pipeline is another story.
In GitLab's documentation, on the pipeline's configuration file .gitlab-ci.yml, they use image: docker:19.03.12. The problem with that is that I need to run ./gradlew, and said image doesn't have java for it to run. Otherwise, if I set the image to image: gradle:jdk14, even if I setup DockerInDocker, when I run docker login, it says docker is not recognized as a command.
I tried creating a custom image with Docker and Java14, but still get the following error:
com.github.dockerjava.api.exception.NotFoundException: {"message":"pull access denied for registry.gitlab.com/projects/projecta, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"}

As you can see in the gitlab-ci file, it's running docker login before executing the tests, and according to the pipeline's output is successful
.gitlab-ci.yml
image: gradle:jdk14

variables:
  GRADLE_OPTS: "-Dorg.gradle.daemon=false"

stages:
  - build
  - test

before_script:
  - export GRADLE_USER_HOME=`pwd`/.gradle

assemble:
  stage: build
  script:
    - ./gradlew assemble
  only:
    changes:
      - "**/*.gradle.kts"
      - gradle.properties
  cache:
    key: $CI_PROJECT_NAME
    paths:
      - .gradle/wrapper
      - .gradle/caches
    policy: push

cache:
  key: $CI_PROJECT_NAME
  paths:
    - .gradle/wrapper
    - .gradle/caches
  policy: pull

test:
  stage: test
  image: registry.gitlab.com/project/docker-jdk14:latest #<-- my custom image
  dependencies:
    - checkstyle
  services:
    - docker:dind
  variables:
    DOCKER_HOST: "tcp://docker:2375"
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  script:
    - docker login -u $CI_DEPLOY_USER -p $CI_DEPLOY_PASSWORD $CI_REGISTRY
    - ./gradlew test

I have the feeling that I'm missing something but so far the only explanation I can come up with is that the docker login the pipeline is executing doesn't set the credentials to the inner docker instance.
Is there anyway to call the login in the inner instance instead of the outer one?
I thought about doing the login call inside the test.. but that would be my last option.

A: If I'm reading your question correctly you're trying to run CI for project gitlab.com/projects/projectb, which uses image built in project gitlab.com/projects/projecta during tests.
You're attempting to pull image registry.gitlab.com/projects/projecta using username and password from predefined variables $CI_DEPLOY_USER and $CI_DEPLOY_PASSWORD.
It doesn't work, because that user has only permissions to access gitlab.com/projects/projectb. What you need to do is to create deploy token for project gitlab.com/projects/projecta with permissions to access the registry, supply it to your CI in gitlab.com/projects/projectb via custom variables and use those to login to $CI_REGISTRY.


text:
Q: BeautifulSoup Split Text from Tag I can find and print the tag:
name = soup.find("h1")
print(name)

gives:

CorianderHerb / Cilantro

But how can I return the different parts separately? i.e. Isolated as 3 separate data points?
Coriander
Herb
Cilantro

When I try:
name = soup.find("h1 span")
print(name)

I get:
None

So I'm stuck already.

A: One solution might be using .get_text() with custom separator and then .split():
from bs4 import BeautifulSoup

soup = BeautifulSoup(
    "
CorianderHerb / Cilantro
", "html.parser"
)

data = [t.strip() for t in soup.h1.get_text(separator="/").split("/")]
print(data)

Prints:
['Coriander', 'Herb', 'Cilantro']


text:
Q: How do you make a shape static while the camera moves C++ OpenGL? I want to make a maze game, with shapes in the form of a maze and a person walking through ( or a square or something) in 2d. I know how to make the camera move, but what I don't know is how to make the person/square move with the camera. I'm using C++ with OpenGL, and at the moment I'm using freeglut but I realize this isn't the best thing to be using. I'm still a beginner, so if I can do it in freeglut and not have to download anything that would be optimal. Thanks!

A: So, I figured out the answer to my own question. I have already built the quad that takes parameters quadx and quad y for the bottom left vertex. I have built a function that moves the camera based on the key that is pressed, and to have the quad appear to stay with the camera, just have it move the same amount as the camera does.
P.S. Make sure to have the thing you want to move with the camera in view at the starting location of the camera, else it will never be on the screen because it will move away just as much as you look for it.


text:
Q: Images not displaying from webview of epub in android I am using webview to display content from epub in android.But now i am able to display content but not able to show the images.Could any one help me to solve this issue?
The code i used to display is::
public class MainActivity extends Activity {
WebView webview;
String line, line1 = "", finalstr = "";
int i = 0;
Book book;
String linez;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webview = (WebView) findViewById(R.id.tv);
    AssetManager assetManager = getAssets();
   try {
        // find InputStream for book
        InputStream epubInputStream = assetManager
                .open("widget.epub");

        // Load Book from inputStream
        book = (new EpubReader()).readEpub(epubInputStream);

        // Log the book's authors
        Log.i("author", " : " + book.getMetadata().getAuthors());

        // Log the book's title
        Log.i("title", " : " + book.getTitle());

        /* Log the book's coverimage property */
         Bitmap coverImage =BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
        Log.i("epublib", "Coverimage is " + coverImage.getWidth() +  " by " + coverImage.getHeight() + " pixels");

        // Log the tale of contents

       logTableOfContents(book.getTableOfContents().getTocReferences(), 0);
    } catch (IOException e) {
        Log.e("epublib exception", e.getMessage());
    }
    Spine spine = book.getSpine();
    List<SpineReference> spineList = spine.getSpineReferences() ;
    int count = spineList.size();
    TextView tv=new TextView(getApplicationContext());
    tv.setText(Integer.toString(count));
    StringBuilder string = new StringBuilder();

    for (int i = 0; count > i; i++) {
        Resource res = spine.getResource(i);

        try {
            InputStream is = res.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            try {
                while ((line = reader.readLine()) != null) {
                    linez =   string.append(line + "\n").toString();
                }

            } catch (IOException e) {e.printStackTrace();}

            //do something with stream
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    webview.loadData(linez, "text/html", "utf-8");
}

@SuppressWarnings("unused")
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
    if (tocReferences == null) {

        return;
    }

    for (TOCReference tocReference : tocReferences) {
        StringBuilder tocString = new StringBuilder();
         for (int i = 0; i < depth; i++) {
         tocString.append("\t");
         }
         tocString.append(tocReference.getTitle());
         Log.i("TOC", tocString.toString());

        try {
            InputStream is = tocReference.getResource().getInputStream();
            BufferedReader r = new BufferedReader(new InputStreamReader(is));

            while ((line = r.readLine()) != null) {

                Log.v("line" + i, Html.fromHtml(line).toString());
                line1 = line1.concat(Html.fromHtml(line).toString());
            }
            finalstr = finalstr.concat("\n").concat(line1);

            i++;
        } catch (IOException e) {

        }

        logTableOfContents(tocReference.getChildren(), depth + 1);
    }

    webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
}

A: For displaying images and css in webview. You need to download css and images in a respective directory sdcard location. Some thing like below code
private void DownloadResource(String directory) {
    try {
        nl.siegmann.epublib.domain.Resources rst = book.getResources();
        Collection<Resource> clrst = rst.getAll();
        Iterator<Resource> itr = clrst.iterator();
        Log.d("Downlod path", directory);
        while (itr.hasNext()) {
            Resource rs = itr.next();
            if ((rs.getMediaType() == MediatypeService.JPG) || (rs.getMediaType() == MediatypeService.PNG) || (rs.getMediaType() == MediatypeService.GIF)
                    || (rs.getMediaType() == MediatypeService.CSS)) {
                File oppath1 = new File(directory + File.separator + rs.getHref());
                oppath1.getParentFile().mkdirs();

                Log.d("Resource Name - ", rs.getHref());
                oppath1.createNewFile();
                Log.d("Oppath - ", oppath1.getAbsolutePath());

                Log.d("File Checking - ", "Exists - " + oppath1.exists() + " & Write - " + oppath1.canWrite());
                FileOutputStream fos1 = new FileOutputStream(oppath1);
                fos1.write(rs.getData());
                fos1.close();

            }

        }
    } catch (IOException e) {
        Log.e("error", e.getMessage());
    }
}


text:
Q: NestJS SyntaxError: Cannot use import statement outside a module I have an error while migrating this migration:
import { MigrationInterface, QueryRunner } from "typeorm";

export class addIdColumnToBidProductsProductTable1626803008084 implements MigrationInterface {

public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('ALTER TABLE `bid_products_product` ADD id INT PRIMARY KEY AUTO_INCREMENT');
}

public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('ALTER TABLE `bid_products_product` DROP COLUMN `id`');
}

}

And this is my error:
> bid@0.0.1 migration:show
> typeorm migration:show

Error during migration show:
/home/antikon/Projects/bid/src/migrations/1626803008084-addIdColumnToBidProductsProductTable.ts:1
import { MigrationInterface, QueryRunner } from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1025:15)
    at Module._compile (node:internal/modules/cjs/loader:1059:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at /home/antikon/Projects/bid/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:39
    at Array.map (<anonymous>)

This is my typeorm connection:
TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'grish2003',
      database: 'biddb',
      entities: [User, Bid, Product, Bid_Product, Bet],
      synchronize: true,
      migrations: [
        join(__dirname, 'migrations/*{.ts}')
      ]
    })

This in a tsconfig.json file:
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

I wanted to add one column to the database through migration, but this error came out.I tried a lot of things but nothing came of it.
Please tell me why it gives this error. Thank you


text:
Q: Count variable PHP I have a list of holidays. If a holiday falls between my Week beginning date and week ending date then hours awarded would be 8.
Problem I am having is I can display 8 hours  ( this is include file and the value is being displayed on another PHP document ) however if I have multiple holidays for a week it still only displays 8. I would like to display
One Holiday would be 8 hours
Two Holidays would be 16 Hours
Three Holidays would be  32 hours
and so on and so forth
I was messing around with += it would work however it would display the total amount for every week
Here is my code
<?

//Holiday List for 2015

//Hours for Holiday

$TestHol = "2015-03-17";
$TestHol2 = "2015-03-16";
$TestHol3 = "2015-03-06";
$NY = "2015-01-01";
$Mem = "2015-05-26";
$V1 = "2015-06-27";
$V2 = "2015-06-30";
$V3 = "2015-07-01";
$V4 = "2015-07-02";
$V5 = "2015-07-03";
$In = "2015-07-04";
$Lab = "2015-09-01";
$Thx = "2015-11-27";
$ThxF = "2015-11-28";
$Chev = "2015-12-24";
$Ch = "2015-12-25";
$V6 = "2015-12-29";
$V7 = "2015-12-30";
$V8 = "2015-12-31";

$holhour = 0;

if(($TestHol>$WBDATE) && ($TestHol<$WEDATE)):
 $holhour = 8;
elseif(($TestHol2>$WBDATE) && ($TestHol2<$WEDATE)):
 $holhour = 8;
elseif(($TestHol3>$WBDATE) && ($TestHol3<$WEDATE)):
 $holhour = 8;
elseif(($NY>$WBDATE) && ($NY<$WEDATE)):
 $holhour = 8;
elseif(($Mem>$WBDATE) && ($Mem<$WEDATE)):
 $holhour = 8;
elseif(($V1>$WBDATE) && ($V2<$WEDATE)):
 $holhour = 8;
elseif(($V2>$WBDATE) && ($V2<$WEDATE)):
 $holhour = 8;
elseif(($V3>$WBDATE) && ($V3<$WEDATE)):
 $holhour = 8;
elseif(($V4>$WBDATE) && ($V4<$WEDATE)):
 $holhour = 8;
elseif(($V5>$WBDATE) && ($V5<$WEDATE)):
 $holhour = 8;
elseif(($In>$WBDATE) && ($In<$WEDATE)):
 $holhour = 8;
elseif(($Lab>$WBDATE) && ($Lab<$WEDATE)):
 $holhour = 8;
elseif(($Thx>$WBDATE) && ($Thx<$WEDATE)):
 $holhour = 8;
elseif(($ThxF>$WBDATE) && ($ThxF<$WEDATE)):
 $holhour = 8;
elseif(($Chev>$WBDATE) && ($Chev<$WEDATE)):
 $holhour = 8;
elseif(($Ch>$WBDATE) && ($Ch<$WEDATE)):
 $holhour = 8;
elseif(($V6>$WBDATE) && ($V6<$WEDATE)):
 $holhour = 8;
elseif(($V7l>$WBDATE) && ($V7<$WEDATE)):
 $holhour = 8;
elseif(($V8>$WBDATE) && ($V8<$WEDATE)):
 $holhour = 8;
else :
 $holhour = 0;
endif;

 ?>

A: Well, you are not incrementing $holhour value. You are just assigning 8 to it every time. modify it to $holhour = $holhour + 8; - whenever you want to add one more holiday. (in all of your if and elseif statements, but not in last else - that's what i guess)


text:
Q: ember js params is exists So I need to do so that clicking on the store would stop the page with the goods of this store. When passing the store's id through the link URL changes but in the product's route  model(params) the  params  is empty

Model name (product?)
import DS from 'ember-data';
import { empty } from '@ember/object/computed';

export default DS.Model.extend({
  name: DS.attr('string'),
  quantity: DS.attr('string'),
  price: DS.attr('string'),
  shops: DS.belongsTo('shop', {asynq: true}),
  isNotValid: empty('name'),
});

Model name (shop?)
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  address: DS.attr('string'),
  phone: DS.attr('string'),
  products: DS.hasMany('product',{asynq: true}),
});

Controller name (?)
import Controller from '@ember/controller';

export default Controller.extend({
  isNew: false,

  actions: {

    newProduct() {
      this.toggleProperty('isNew');
    },

    cancelNewProducts() {
      this.set('isNew', false);
    },

    addNewProduct() {
      const name = this.get('name');
      const quantity = this.get('quantity');
      const price = this.get('price');

      let shop = this.get('store').peekRecord('shop', );
      let product = this.get('store').createRecord('product', { name,quantity,price });
      shop.get('products').pushObject(product);
      product.save().then( function() {
        shop.save();
      });
      product.save().then( ()=> this.set('isNew',false));
    },

  },

});

Route name (?)
import Route from '@ember/routing/route';

export default Route.extend({

  model(params) {
    console.log(params.shop_id);
    return this.store.query('product', {shops:params.shop_id});
  },

  actions: {

    deleteProduct(product) {
      let confirmation = confirm('Are you sure?');

      if (confirmation) {
        product.destroyRecord();
      }
    },

    editProducts(product) {
      console.log(id)
      product.set('isEditing', true);
    },

    cancelProductsEdit(product) {
      product.set('isEditing', false);
      product.rollbackAttributes();
    },

    saveProducts(product) {
      if (product.get('isNotValid')) {
        return;
      }
      product.set('isEditing', false);
      product.save();
    },

  },
});

Router
import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('shops', function() {
  this.route('new');
  this.route('edit', { path: '/:shop_id/edit' });
});

  this.route('products', { path: '/:shop_id/products' }); // this should be in the map, right?

}); // ?
export default Router;

My problem is that I can not make a request to the server and get the goods only from the store with the available id.But when I click on any store displays all the goods. AND i can't access params(shop_id) from shops  in my controller,

A: I just did a pretty invasive reformatting of your program. Take note of the router. Looks like there are some mistakes in there. Also, you don't provide an id to 'peek' with. In your controller. We also don't know how those files are connected or what their names are. You should edit on top of my formatting to help clarify. {async: true} is spelled with a q in your program.
As far as your question... I'll try and reword it. The word 'store' is confusing... because of the data 'store' that we are used to talking about. I think you mean that you have a 'shop' resource and that you want to 'click' on the shop... (likely a component in an each loop) and then you say you want to 'stop' the page with the goods(products) - so... maybe you mean 'stock' or 'show' the products for that shop. This could be in the component (if only a few) - or you could shoot over to a 'detail' page for the shop - that displayed all of the products for that shop. Because you mention params and ID, I think you mean to go the detail route.
This is my best guess at your question: "I have resources for 'shop' and 'product.' I'm building a UI where shops are listed. I would like to make the shops clickable and when clicked, transition to the shop detail page - where I can list all associated products. My link-to helper(not shown here) takes in a shop ID - but the transition is not successful and the params isn't recognized. What am I doing wrong?"
For this question, you could likely create a more simplified version in an ember-twiddle to get to the bottom of things. We don't really need most of those actions to get to the source of the confusion.
It's admitedly hard to show these things / when you have a server - or a mirage server or whatever your setup is. Here's an example of the routing I would suggest - with some basic dummy data - in an embertwiddle. The data isn't real ember objects / but see the link-to and the shop detail route for what you'd likely use. Good luck!
Other notes:

*

*ember-data uses an attribute called isNew for records - so, you may want to think of a different name for what you're doing /


text:
Q: Kafka Streams API pushes old values to a topic only after a new event arrives I have surfed the internet for some time before writing the question, and it seems that this problem is not so much popular (not a mention of it anywhere). I use Kafka Streams API in my project for a calculation of something. I won't go into details of the algorithm, because it is not important here at all, what I have a problem with is that old values that are to be pushed to the topic are not pushed there until new values arrive. I guess it is because I use windowing and suspend the window, but I would like to somehow solve the problem (not with hacky solutions like pushing empty events). In this particular case, I need to wait till the end of the window before publishing the value to the output topic. The topology looks as follows:
firstStream.leftJoin(secondStream, ...)
    .leftJoin(thirdStream, ...)
    .filter(...)
    .groupByKey(...)
    .windowedBy(TimeWindows.of(Duration.ofSeconds(windowSeconds)).grace(Duration.ofSeconds(graceSeconds)))
    .aggregate(...)
    .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
    .toStream()
    .to(outputTopic)

So, whenever I push an event to the firstStream, I should receive an output of the transformations in the outputTopic after the window closes, but actually, I receive the output only when I push a new event after the window closes.
So, my question is whether there is a way to push output after the window closes without sending a new event?


text:
Q: How to pass props from child component to its parent of parent? Suppose I have three components, where SubMain2 is inside SubMain1 and SubMain1 is inside Main. How would I pass props from SubMain2 to Main component?
PROBLEM: TypeError: Cannot read property 'handleSubMain1' of undefined
Main
class Main extends Component {
  constructor(props) {
  super(props);
  this.handleSubMain1 = this.handleSubMain1.bind(this);
  }

 handleSubMain1() {
  console.log('received props from SubMain1 which is from SubMain2!');
 }

  render() {
     <SubMain1 handleSubMain1={this.handleSubMain1}/>
  }
}

SubMain1
class SubMain1 extends Component {

 constructor(props) {
 super(props);
 this.handleSubMain2 = this.handleSubMain2.bind(this);
 }

 handleSubMain2() {
  console.log('received props from SubMain2!');
 }

  render() {
     <SubMain2 handleSubMain2={this.handleSubMain2}/>
  }
}

SubMain2
Component SubMain2 extends Component {
   constructor(props) {
   super(props);
   }

   render() {
     this.props.handleSubMain2();
  }
}

I tried this approach, however I'm getting handleSubMain1 function is undefined. I even tried passing props from SubMain2 to Main component directly, however no luck.

A: You shouldn't use this.handSubMainX just use handleSumbmainX={this.handleSubmainX} and bind this in your constructor
here is the result would look like:
Main:
class Main extends Component {
  constructor(props) {
  super(props);
  this.handleSubMain1 = this.handleSubMain1.bind(this);
  }

 handleSubMain1() {
  console.log('received props from SubMain1 which is from SubMain2!');
 }

  render() {
     return <SubMain1 handleSubMain1={this.handleSubMain1}/> <-- 2 Change here
  }
}

SubMain1:
class SubMain1 extends Component {

 constructor(props) {
 super(props);
 this.handleSubMain2 = this.handleSubMain2.bind(this);
 }

 handleSubMain2() {
  console.log('received props from SubMain2!');
 }

  render() {
     return <SubMain2 handleSubMain2={this.handleSubMain2}/> <-- 2 Change here
  }
}

SubMain2:
Component SubMain2 extends Component {
   constructor(props) {
   super(props);
   }

   render() {
     return this.props.handleSubMain2(); // this function should return jsx
  }
}

A: Props are only passed down to children. Each child component down the line needs to call the callback that was passed to it.
class Main extends Component {
  mainCallback = val => console.log("mainCallback", val);

  render() {
    return <SubMain1 handleSubMain1={this.mainCallback} />;
  }
}

class SubMain1 extends Component {
  subMain1Callback = val => {
    console.log("subMain1Callback");
    this.props.handleSubMain1(val);
  };

  render() {
    return <SubMain2 handleSubMain2={this.subMain1Callback} />;
  }
}

class SubMain2 extends Component {
  subMain2Callback = val => {
    console.log("subMain2Callback");
    this.props.handleSubMain2(val);
  };

  render() {
    return (
      <button onClick={() => this.subMain2Callback(42)}>
        SubMain2 - click me?
      </button>
    );
  }
}

A: here is the sandbox I made so you can see the console log : https://codesandbox.io/s/funny-chebyshev-n5srl?file=/src/App.js:63-717
here is the code in case you need it here:

class Main extends Component {
  handleSubMain1(arg) {
    console.log('received props from SubMain1 which is from SubMain2!');
    console.log(arg);
 }

  render() {
     return <SubMain1 handleSubMain1={this.handleSubMain1}/>
  }
}

class SubMain1 extends Component {
  render() {
     return <SubMain2 handleSubMain2={this.props.handleSubMain1}/>
  }
}

class SubMain2 extends Component {
  handleClick(){
    this.props.handleSubMain2('any thing I pass as an argument I can access it in main');
  }

  render() {
     return (
       <button onClick={this.handleClick.bind(this)}>
         Click me to send data to Main
       </button>
     )
 }
}


text:
Q: neural network c++ code from matlab coder I trained a neural network in the Matlab "Neural Net Pattern Recognition" toolbox and generated a .m function from the toolbox. I also wrote my own function, which gets a dataset containing a inf x 5 matrix with datapoints as input, calls the NN function from the toolbox and returns a vector with the recognized pattern and a percent value. (the input matrix contains the pattern, which should be detected)
Because I need to run the code on an Arduino, I tried to use the Matlab Coder to generate C++ Code but it doesn't work. First, I get the warning that arrayfun is not supported for code generation (the call os arrayfun is in the generated function from the toolbox). After that, I defined the input of the function as " double(:7351 x 5)" (it's up to 7351 because my dataset for training is that big).
Now the coder builds an MEX file for checking for run-time issues and there some errors occur.
I don't know why the target build log is in german because the rest of Matlab is in English but in generally some brackets and semicolons are missing but why? How can brackets be missing in the matrix.h or amlrt.h???
  1   cl  /c /Zp8 /GR /W3 /EHs /nologo /MD /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0   /DMATLAB_MEX_FILE  /DMATLAB_MEX_FILE   /O2 /Oy- /DNDEBUG  /fp:strict  /I "C:\PROGRA~1\MATLAB\R2016a\simulink\include" /I "C:\PROGRA~1\MATLAB\R2016a\toolbox\shared\simtargets" /I "C:\Users\Kai\Desktop\YUN_SI~1" /I "C:\Users\Kai\Desktop\YUN_SI~1\codegen\mex\NeuralNetwork" /I ".\interface" /I "C:\PROGRA~1\MATLAB\R2016a\extern\include" /I "." "NeuralNetwork_data.c"
    2   NeuralNetwork_data.c
    3   c:\program files\matlab\r2016a\extern\include\matrix.h(260) : error C2061: Syntaxfehler: Bezeichner 'mxChar'
    4   c:\program files\matlab\r2016a\extern\include\matrix.h(260) : error C2059: Syntaxfehler: ';'
    5   c:\program files\matlab\r2016a\extern\include\matrix.h(605) : error C2143: Syntaxfehler: Es fehlt '{' vor '*'
    6   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(56) : error C2143: Syntaxfehler: Es fehlt ')' vor '*'
    7   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(56) : error C2143: Syntaxfehler: Es fehlt '{' vor '*'
    8   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(56) : error C2373: 'emlrtCTX': Neudefinition; unterschiedliche Modifizierer
    9           C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(50): Siehe Deklaration von 'emlrtCTX'
   10   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(56) : error C2146: Syntaxfehler: Fehlendes ';' vor Bezeichner 'aTLS'
   11   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(56) : error C2059: Syntaxfehler: ')'
   12   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(133) : error C2061: Syntaxfehler: Bezeichner 'EmlrtErrorFunction'
   13   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(139) : error C2059: Syntaxfehler: '}'
   14   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(194) : error C2061: Syntaxfehler: Bezeichner 'emlrtContextGlobal'
   15   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(194) : error C2059: Syntaxfehler: ';'
   16   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(808) : error C2143: Syntaxfehler: Es fehlt ')' vor '*'
   17   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(808) : error C2143: Syntaxfehler: Es fehlt '{' vor '*'
   18   C:\PROGRA~1\MATLAB\R2016a\extern\include\emlrt.h(808) : error C2059: Syntaxfehler: ')'
   19   c:\users\kai\desktop\yun_simulink\codegen\mex\neuralnetwork\NeuralNetwork_data.h(32) : error C2061: Syntaxfehler: Bezeichner 'emlrtContextGlobal'
   20   c:\users\kai\desktop\yun_simulink\codegen\mex\neuralnetwork\NeuralNetwork_data.h(32) : error C2059: Syntaxfehler: ';'
   21   NeuralNetwork_data.c(22) : error C2061: Syntaxfehler: Bezeichner 'emlrtContextGlobal'
   22   NeuralNetwork_data.c(22) : error C2059: Syntaxfehler: ';'
   23   NeuralNetwork_data.c(22) : error C2513: '/*global*/ ': Keine Variable vor '=' deklariert
   24   gmake: *** [NeuralNetwork_data.obj] Error 2

In general, it is possible to create C++ code from the NN toolbox but why doesn't it work in my case?
The function I want to translate in c++ is:
function [ activity, percent ] = NeuralNetwork( Data )
%NN for recogniton of activitys standing, sitting, walking from Accelerometer data, relative error
%is returned in percent
%   input Data contains 5 columns. 1. col -> time; 2-4.col ->
%   x,y,z-Acceleration; 5.col -> activity
%   VAR activity contains 1 for walking, 2 for sitting and 3 for standing

    Acceleration_data = Data(:,2:4);  %store acceleration data in a matrix
    Acceleration_data = Acceleration_data';     %NN input expects transposed matrix

    targets = Data(:,5);    %activity that should be detected from the NN
    targets = targets';     %output of NN is also transposed

    NNfit = myNeuralNetworkFunction(Acceleration_data); %call the trained NN
    NNfit = round(NNfit);                             %output can be e.g. 0.998 -> round to 1
    activity=zeros(1,length(NNfit));                   %allocate memory for cpp-code

for i=1:length(NNfit)               %NNfit is a 3D matrix, after round one
    [val pos] = max(NNfit(:,i));    %element is 1 the other are 0 the number of
                                    %the row represents the activity
    activity(i) = pos;              %vektor containing the activity
end

cnt=0;              %calc percent of correct recognized data points
for i=1:length(NNfit)
   if activity(i) == targets(i)
       cnt = cnt+1;         %amound of correct recognized data points
   end
end

percent = (cnt/length(targets))*100;   %calc percent

end

edit:
The file NeuralNetwork_data.c:
/* Include files */
#include "rt_nonfinite.h"
#include "NeuralNetwork.h"
#include "NeuralNetwork_data.h"
#include "blas.h"

/* Variable Definitions */
emlrtCTX emlrtRootTLSGlobal = NULL;
const volatile char_T *emlrtBreakCheckR2012bFlagVar = NULL;
covrtInstance emlrtCoverageInstance;
emlrtContext emlrtContextGlobal = { true, false, 131434U, NULL, "NeuralNetwork",
  NULL, false, { 2045744189U, 2170104910U, 2743257031U, 4284093946U }, NULL };

emlrtRSInfo f_emlrtRSI = { 68, "eml_mtimes_helper",
  "C:\\Program Files\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};

emlrtRSInfo g_emlrtRSI = { 85, "xgemm",
  "C:\\Program Files\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\+blas\\xgemm.m"
};

emlrtRSInfo n_emlrtRSI = { 214, "minOrMax",
  "C:\\Program Files\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\minOrMax.m"
};

emlrtRSInfo o_emlrtRSI = { 375, "minOrMax",
  "C:\\Program Files\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\minOrMax.m"
};

emlrtRSInfo p_emlrtRSI = { 347, "minOrMax",
  "C:\\Program Files\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\minOrMax.m"
};

/* End of code generation (NeuralNetwork_data.c) */


text:
Q: PHP - use array as class constant
Possible Duplicate:
Is it possible to declare an array as constant

Is it possible to use an array as a class constant in PHP?
I.e
const MYARRAY = array('123', '234');

If not why?

A: No, you can't.
But you could declare it as a static property.
public static $MYARRAY = array('123', '234');

---------------Update-----------------------------
Array const is available from PHP 5.6.
php.net/manual/en/migration56.new-features.php

A: UPDATE:
This is now available in PHP 5.6 https://php.net/manual/en/migration56.new-features.php

No you can't assign an Array to PHP constant.
In http://www.php.net/manual/en/language.constants.syntax.php

Constants may only evaluate to scalar values

This is the reason.
Scalar values for examples are int, float, string


text:
Q: Google API distance matrix with coordinates I am trying to write a code that would fetch destination between two physical points. My request string look like this:
"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+initial[0]+"|"+initial[1]+"&destinations="+destination[0]+"|"+destination[1]+"&key="+api_key;

As a link it looks like this:
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=42.9814292|-70.9477546&destinations=51.5073509|-0.1277583&key=

The JSON response is
    {
       "destination_addresses" : [ "", "" ],
       "origin_addresses" : [ "", "" ],
       "rows" : [
          {
             "elements" : [
                {
                   "status" : "NOT_FOUND"
                },
                {
                   "status" : "NOT_FOUND"
                }
             ]
          },
          {
             "elements" : [
                {
                   "status" : "NOT_FOUND"
                },
                {
                   "status" : "NOT_FOUND"
                }
             ]
          }
       ],
       "status" : "OK"
    }

When tried without "|" the response is
    {
   "destination_addresses" : [ "51.5073509,-0.1277583" ],
   "origin_addresses" : [ "42.9814292,-70.9477546" ],
   "rows" : [
      {
         "elements" : [
            {
               "status" : "ZERO_RESULTS"
            }
         ]
      }
   ],
   "status" : "OK"
}

Where exactly is the problem? I know that it has to be the coordinates and how i put them into url but I don't understand what I have to change.

A: 1) Your request is using a | pipe character rather than a , comma to separate the lat/lngs. Using a pipe instead of a comma is passing four origin/destinations as single number queries rather than two. You have to use the comma between the latitude and longitude
2) The supported travel modes for the Distance Matrix API are driving, transit, bicycling, and walking to get travel distances. However, the coordinates you are using correspond to the following locations:
Origin 42.9814292,-70.9477546 = 130 Water St, Exeter, NH 03833, USA
Destination 51.5073509,-0.1277583 = A4, London WC2N 5DU, UK
None of those modes will be able to give travel distances from the US to the UK, and flight mode is not a supported mode.
Please review the
Distance Matrix API documentation
If you are just trying to get the absolute distance between those two lat/lngs with the Google Maps APIs, you may need to look into using computeDistanceBetween() function in the Geometry library in the Javascript API
Simple JSBin adapted from Google's Navigation functions example
<!DOCTYPE html>

    <title>Distance between two points</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">


text:
Q: When using JS Pact in the browser, how do I create the pact files? I am using the JS pact library  ( github.com/pact-foundation/pact-js) to test a polymer application. I need to test the ajax code in the application, and I want to test it in the browser.
I now have all of that working in my github repo https://github.com/phil-rice/HelloPolymer (I do need to manually lift and tear down the pact broker at the moment)
I want now to produce the pact files. And... that makes it interesting because the tests are running in the browser. The normal approach to this appears to be to pass information to the Pact(), as per  //github.com/pact-foundation/pact-node#create-pact-mock-server
 provider = Pact({
            consumer: 'Friends Client',
            provider: 'Friends API',
            host: "localhost",
            port: 9999,
          // HERE I WOULD SPECIFY THE LOCATION OF THE PACT FILES
            spec: '3.0.0' // https://github.com/pact-foundation/pact-specification
        });

However this code is running on the browser. The browser doesn't let me have access to files!
How should I create my pact files?
Thanks!

A: And I answered my own question.
The pacts are generated in the directory in which I run the Pact Server from. i.e. not in the browser at all


text:
Q: How to dump&restore a postgresql type in custom binary format? for postgresql 9.3 or higher.
if i create a type with:
CREATE TYPE x(INPUT=x_in,OUTPUT=x_out,SEND=x_send,RECEIVE=x_receive,...);

then for all selects and from string casts x_in and x_out is used which is desired. however my type sometimes may hold additional informations which are unrelevant for the user - hence i should not show it in x_out but if the database is dumped/restored the extra information should be kept.
i've tryed to define SEND and RECEIVE which are working if i call them directly, but i was unsuccessful to force pg_dump to use them during creating the dump
binary dump creation/restoration:
 pg_dump -Fc db --table t > dump.bin
 pg_restore -d db -Fc dump.bin

NOTE: if i would show the additional data in the standard x_out, then the dumps and everything would be fine, but there are some third party tools which became confused about the format


text:
Q: How to fix google font pixelation issues on safari and chrome I have used Google font called http://fonts.googleapis.com/css?family=Merriweather:400,700,700italic on my website it looks good on Firefox and IE but not at the safari and Google chrome..... Please view the Image....
Image
I want it to be working on each of the browser without any pixelate issue
Requesting your best suggestion...........
Thanks

A: Just try this:
{
  -webkit-text-stroke: 0.6px;
}

A: You cannot possibly control how a browser like Chrome renders fonts. You just have control over choosing the best font at best font-size.(Some fonts looks good only at certain font sizes - the font you are using looks good from 50px onward it seems. EDIT:Ah that is a different issue)
If you / your client is so specific you can even get help from some custom rendering like

*

*Typeface.js

*Cufon
which uses canvas/flash to render fonts. Using it extensively can cause performance issues or slowness.
There used to a font-smoothening, but I guess no longer supported, you can try it though -webkit-font-smoothing property has no effect in Chrome

A: you can smooth fonts by using
body {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

read more: https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth


text:
Q: Powershell - Looking for a better way to check if multple processes have completed I've got a script that creates some processes using the Start-Process command.  There could be hundreds of processes running. The script works just fine, but I'm hoping someone can provide me with a more elegant way to check if the processes I started have all completed?  One that doesn't require any input as I'm looking to create an automated solution.
Below is a code sample.
$procList = @()

$cmd = "C:\Windows\SysWOW64\PING.EXE"
$cmdArgs = " nos3nse.com"
$proc1 = Start-Process $cmd -ArgumentList $cmdArgs -PassThru
$proc2 = Start-Process $cmd -ArgumentList $cmdArgs -PassThru
$proc3 = Start-Process $cmd -ArgumentList $cmdArgs -PassThru

$procObject = New-Object psobject -Property @{
    id = $proc1.Id
    name = $proc1.Name
    startTime = $proc1.StartTime
    dtlLogFile = $dtlLogFileTemp
}
$procList += $procObject

$procObject = New-Object psobject -Property @{
    id = $proc2.Id
    name = $proc2.Name
    startTime = $proc2.StartTime
    dtlLogFile = $dtlLogFileTemp
}
$procList += $procObject

$procObject = New-Object psobject -Property @{
    id = $proc3.Id
    name = $proc3.Name
    startTime = $proc3.StartTime
    dtlLogFile = $dtlLogFileTemp
}
$procList += $procObject

# Is there a better way to find out if these jobs have all completed?
$ppFlag = $true
while ($ppFlag) {
  foreach ($proc in $procList) {
    $chkJob = Get-Process -id $proc.id -ErrorAction SilentlyContinue
    if ($chkJob.HasExited -eq $false)
      {
        Write-Host ("looping")
        Write-Host ("Sleeping 2 seconds") -ForegroundColor Yellow
        Start-Sleep -Seconds 2
        break #break foreach loop
      }
  } #foreach
  if ($chkJob.HasExited -ne $false) { $ppFlag = $false }
} #while

A: How about this?
$a = start -NoNewWindow powershell {timeout 10; 'a done'} -PassThru
$b = start -NoNewWindow powershell {timeout 10; 'b done'} -PassThru
$c = start -NoNewWindow powershell {timeout 10; 'c done'} -PassThru
$a,$b,$c | wait-process

Waiting for  0 seconds, press a key to continue ...
Waiting for  0 seconds, press a key to continue ...
Waiting for  0 seconds, press a key to continue ...

a done
b done
c done

Wait-process can be used with an array.  Maybe you should update your question.
1..3 | foreach { start -NoNewWindow powershell {timeout 5; 'done'} -PassThru } |
  wait-process


text:
Q: Website keeps loading Setup

*

*Vagrant Box (Ubuntu 12.04 / nfs mount, for performance purposes).

*Apache Version Apache/2.2.22 (Ubuntu)

*CakePHP 3 Project.

Vhost
Took from here.
<VirtualHost *:80>
   ServerName www.kitchen.com
   ServerAlias www.kitchen.com kitchen.com
   DocumentRoot /var/www/kitchen/webroot

   CustomLog /var/log/apache2/www.kitchen.com-access.log combined
   ErrorLog /var/log/apache2/www.kitchen.com-error.log

   Options -Indexes FollowSymLinks

   #disable htaccess starting at /
   <Directory />
            AllowOverride none
    </Directory>

   <Directory /var/www/kitchen/webroot/>
            RewriteEngine On
            RewriteBase /
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

            <Files sitemap.xml>
                    RewriteEngine Off
            </Files>
       </Directory>
</VirtualHost>

All my .htaccess inside the project are the default ones
Part of the Vagrantfile
config.vm.network :private_network, ip: "192.168.33.20"
config.vm.synced_folder "./www", "/var/www", type: "nfs"

/etc/hosts on the host machine
192.168.33.20 www.kitchen.com kitchen.com

*

*I am able to reach an existing file (www.kitchen.com/css/base.css for example).

*When I'm trying to load www.kitchen.com the site keeps loading overtime.

I looked in the logs (syslog, access logs, error logs, ...) but nothing relevant ...
I also checked apache user and my project files permissions:
Apache User/Group:  www-data(33)/33

$ (/var/www/kitchen) ls -la
files:   -rw-r--r--  1 502 dialout
folders: drwxr-xr-x  9 502 dialout


text:
Q: Are there any built in methods to change a JavaScript object's properties to a certain value? I would like to change all property values of a JavaScript object to a certain value (false in this case). I know how to do this by changing all of them individually (Example A) or with a loop (Example B). I was wondering if there are any other built in methods to do this, and what is the recommended way (mainly in terms of speed or if there are any other side effects)?
Pseudocode:
// Example object
Settings = function() {
    this.A = false;
    this.B = false;
    this.C = false;
    // more settings...
}

// Example A - currently working
updateSettingsExampleA = function(settings) {
    // Settings' properties may not be be false when called
    settings.A = false;
    settings.B = false;
    settings.C = false;
    while (!(settings.A && settings.B && settings.C) && endingCondition) {
        // code for altering settings
    }
}

// Example B - currently working
updateSettingsExampleB = function(settings) {
    // Settings' properties may not be be false when called
    for (var property in settings) {
        settings[property] = false;
    }
    while (!(settings.A && settings.B && settings.C) && endingCondition) {
        // code for altering settings
    }
}

// possible other built in method
updateSettingsGoal = function() {
    this.* = false; // <-- statement to change all values to false
    while (!(this.A && this.B && this.C) && endingCondition) {
        // code for altering settings
    }
}

A: No, there is no such built-in method. If you want to "change all property values to false", then use a loop to do so. Your Example B is totally fine.
I wouldn't recommend unrolling the loop (Example A) except it's not "all properties" or you require absolute maximum speed for this snippet. But that's a micro-optimisation, it doesn't make your code better.


text:
Q: What is wrong with the segue and NavigationController navigation This is a continuation/alternative of this thread: popToRootViewControllerAnimated problem to sort out what is the problem/mistake in a more structured and easier to understand way.
When pressing the back button in VC3 i want to go back to VC1.
I have the following setup:

The following code:
VC1:
@implementation ViewController
- (IBAction)myButton1:(id)sender {

//Call InformationViewController for Quick Game
[self performSegueWithIdentifier:@"toVC2" sender:self];

}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

VC2:
@implementation nrTwoViewController
- (IBAction)myButton2:(id)sender {
//Call InformationViewController for Quick Game
[self performSegueWithIdentifier:@"toVC3" sender:self];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

VC3:
@implementation nrThreeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController popToRootViewControllerAnimated:YES];
}

@end

I only pop to VC2, not the root (VC1), and get the following message when pressing back button on VC3:
2013-10-15 08:36:08.479 segueTest[44153:a0b] nested pop animation can result in corrupted navigation bar
2013-10-15 08:36:08.831 segueTest[44153:a0b] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.

I also tried, as suggested, adding the UINavigationBarDelegate:
@interface nrThreeViewController : UIViewController <UINavigationBarDelegate>

...and:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
[self.navigationController popToRootViewControllerAnimated:YES];
return NO;
}

The result:

pop'ed from VC3 to VC2 only with no messages in the console.

A: The issue is where you placed the [self.navigationController popToRootViewControllerAnimated:YES]; the error message is Finishing up a navigation transition in an unexpected state.  This is because when viewWillDisappear is called, the view is already beginning to transition off the screen, you are then calling another transition.  Try putting it in a button action that simply pops to the root view controller and see if that solves your problem.


text:
Q: Combined Handlebars in SendGrid I'm trying to set up a string match using handlebars in SendGrid. As I understand it, you can only use the if statement with booleans so I'm trying via {{equals}} instead. This works fine but I'm then trying to inject that 'thing' into the result. The result I'm after in the below is that if the data = TEXT then the email reads "This is some TEXT"
{{#equals thing "TEXT"}}
This is some {{insert thing}}
{{/equals}}

Using {{insert thing}} outside the {{equals}} handlebar is fine but when inside it doesn't return anything. I just get "This is some"
Does anyone know if this is supported or if there is a better way?
Thanks.

A: I'm not entirely sure how to explain it, but it seems that within blocks in  handlebars there is a new scope. This works well for loops, where the scope is the current item in the loop, but less well for conditionals where the scope doesn't seem to include anything. You can get back to the root scope using the @root keyword though, so you can use that to get something from outside of the block. In this case, you can use it like this:
{{#equals thing "TEXT"}}
This is some {{insert @root.thing}}
{{/equals}}


text:
Q: Issue with Conway's Game of Life in Python I've been trying to create the Game of Life in python but I've been struggling to get the correct result no matter how I write the rules, so I'm not too sure where I'm going wrong.
I've tried writing my rules for iterating over the cells various times, writing the base code to use multiple lists or using lists of classes, but every time the result comes off wrong and after 5 or so iterations the simulation just kinda plateaus.
Here is my sourcecode:
import os
import random
import time

class Cell():
    def __init__(self, ID, state, previous_state, neighbours, index):
        self.ID = ID
        self.state = state
        self.previous_state = previous_state
        self.neighbours = neighbours
        self.index = index

    def Get_Neighbours(self,grid):
        neighbours = 0
        index_y = self.index[0]
        index_x = self.index[1]

        if index_x < height - 1:
            if grid[index_x + 1][index_y].state == 1:
                neighbours += 1
        if index_x > 0:
            if grid[index_x - 1][index_y].state == 1:
                neighbours += 1
        if index_y < width - 1:
            if grid[index_x][index_y + 1].state == 1:
                neighbours += 1
        if index_y > 0:
            if grid[index_x][index_y - 1].state == 1:
                neighbours += 1
        return neighbours

def Draw_grid(grid):
    os.system("cls")
    for Cells in Cell_grid:
        print_row = []
        for Cell in Cells:
            if Cell.state == 1:
                print_row.append("#")
            else:
                print_row.append(" ")
        print(" ".join(print_row))
    print(Cell_grid[1][1].neighbours)
    time.sleep(.5)

def Iterate_Cells(Cell_grid):
    for Cells in Cell_grid:
        for Cell in Cells:
            Cell.neighbours = Cell.Get_Neighbours(Cell_grid)
            if Cell.state == 1 & Cell.neighbours <= 1:
                Cell.state = 0
            elif Cell.state == 1 & Cell.neighbours in [2,3]:
                Cell.state = 1
            elif Cell.state == 1 & Cell.neighbours == 4:
                Cell.state = 0
            elif Cell.state == 0 & Cell.neighbours == 3:
                Cell.state = 1

"""
A cell dies if it has less than two living neighbors.
A cell survives until the next generation if it has two or three neighbors.
A cell with more than three neighbors dies.
A dead cell with exactly three neighbors turns into a living cell.
"""

width = 30
height = 30
interation = 0

Cell_grid = [[Cell(0,0,0,0,0) for i in range(width)] for j in range(height)]
counter = 0

""" initialize cells """
for i in range(width):
    for j in range(height):

        alive_seed = random.random()
        if alive_seed > .2:
            Cell_grid[i][j].state = 1
        else:
            Cell_grid[i][j].state = 0

        Cell_grid[i][j].index = (i,j)

        Cell_grid[i][j].ID = counter
        counter += 1

while True:
    Draw_grid(Cell_grid)
    Iterate_Cells(Cell_grid)
    ```

A: One problem is here and in similar checks:
if Cell.state == 1 & Cell.neighbours <= 1

& is the bitwise AND operator, not logical AND.  Looking at the operator precedence rules, this will be parsed as:
if Cell.state == (1 & Cell.neighbours) <= 1

which, thanks to comparison chaining, is expanded as:
if Cell.state == (1 & Cell.neighbours) and (1 & Cell.neighbours) <= 1

Instead, you need to use the and keyword:
if Cell.state == 1 and Cell.neighbours <= 1


text:
Q: populating textboxes based on selection of kendo combo box I need to populate two textbox controls based on a selection of combo box in my MVC 5 application. The combo box is a kendo MVC control. The values that need to be assigned to the text box controls are there in the collection that is bound to the combo box control. Could somebody let me know how to go about it. Does this need to be handled in javascript/ jquery or is it handled in kendo combo box events. An example would be great.
Combo box
        @Html.LabelFor(model => model.Name1, htmlAttributes: new { @class = "control-label col-md-4" })

                @(Html.Kendo().ComboBoxFor(model => model.Name1)

                    .HtmlAttributes(new { style = "width:300px" })
                    .DataTextField("Name1")
                    .DataValueField("CustomerMasterDataId")

                    .DataSource(dataSource => dataSource
                    .Read(read => read.Action("RequestHeader_CustomerData", "Request").Type(HttpVerbs.Post))
                    )
                )

            @Html.ValidationMessageFor(model => model.CustomerNumber, "", new { @class = "text-danger" })

Textbox

                @Html.LabelFor(model => model.CustomerNumber, htmlAttributes: new { @class = "control-label col-md-4" })

                        @Html.EditorFor(model => model.CustomerNumber, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.ValidationMessageFor(model => model.CustomerNumber, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.CustomerGroup, htmlAttributes: new { @class = "control-label col-md-4" })

                        @Html.EditorFor(model => model.CustomerGroup, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.ValidationMessageFor(model => model.CustomerGroup, "", new { @class = "text-danger" })

Controller method that poulates the combo
public ActionResult RequestHeader_CustomerData()
    {
        var response = requestRepository.GetCustomerData().AsQueryable().ProjectTo<CustomerViewModel>();

        var jsonResult = Json(response, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }

Please note that the CustomerNumber  and Name1 field would be used to populate the text boxes
ViewModel
  public class CustomerViewModel
    {
        public int CustomerMasterDataId { get; set; }
        public int CustomerNumber { get; set; }

        [Display(Name = "Customer Name")]
        public string Name1 { get; set; }

        [Display(Name = "Customer Group")]
        public string CustomerGroup { get; set; }
    }

A: Yes, handle the change event:
@(Html.Kendo().ComboBoxFor(model => model.Name1)
      .HtmlAttributes(new { style = "width:300px" })
      .DataTextField("Name1")
      .DataValueField("CustomerMasterDataId")
      .DataSource(dataSource => dataSource
      .Events(e => e.Change(onComboChange))
      .Read(read => read.Action("RequestHeader_CustomerData", "Request").Type(HttpVerbs.Post))
                )
            )

Now handle it in js:
@section scripts
{

}

Here is a js equivalent: http://jsfiddle.net/sg53719/74LwhebL/1/


text:
Q: swift - central writing characteristic to Peripheral I have connected to two iPhones and found the services and characteristics in it. I am facing problems in sending write requests from central and receiving response from peripheral. I have written the code below to write data in central and received data in Peripheral. But the function didReceiveWriteRequests didn't execute. I don't know Why didn't work.
In central view write, the data code:
func writeValue(data:NSData){
   if let discoveredPeripheral = discoveredPeripheral{
        if let deviceCharacteristics = deviceCharacteristics{
            discoveredPeripheral.writeValue(data, forCharacteristic: deviceCharacteristics, type: CBCharacteristicWriteType.WithResponse)
        }
    }
}

and in peripheral view, the receive code:
func peripheralManager(peripheral: CBPeripheralManager!, didReceiveWriteRequests requests: [AnyObject]!) {

    println("didReceiveWriteRequests")
    println("\(requests.count)")
}


text:
Q: NetworkChange.NetworkAddressChanged event stops working I am using this simple way to detect network connect/disconnect events:
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);

...

static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
    RaiseNewtorkChange();
}

static void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
    RaiseNewtorkChange();
}

static void RaiseNewtorkChange()
{
    ...
}

The problem is that sometimes NetworkAddressChanged event just stops working, after it was fired several times. Does anyone have an idea why this can happen?
Alternatively, is there another way to handle network connect/disconnect events, using C# or C/C++. Maybe there is such functionality in Windows API or WMI? I need notification on LAN/WiFi network connecting/disconnecting, without polling.

A: It seems to me that you need to use the Native Wifi API.
Take a look at the function WlanRegisterNotification, in particular this notification:

WLAN_NOTIFICATION_SOURCE_ACM: Registers for notifications generated by the auto configuration module.
  Windows XP with SP3 and
  Wireless LAN API for Windows XP with SP2:  Only the
  wlan_notification_acm_connection_complete and
  wlan_notification_acm_disconnected notifications are available.

Disclaimer: I have used Native Wifi API in the past, but I have never used this particular feature.


text:
Q: How do I copy/backup my dotenv files and config files from one computer to another in Git It's generally not great practice to store secrets (.env files) in git. However when I need to move computers, I usually have to copy and paste them individually one by one.
I don't want to copy the entire git repository because it also contains node_modules and would take forever through Google. How can I copy just my env files?

A: Run this in your sites dir
setopt sh_word_split # For zsh

dirs=$(find . -maxdepth 1 -type d -execdir test -d {}/.git \; -prune -print 2>/dev/null)

# store dotfiles here
[[ ! -d dotfiles ]] && mkdir dotfiles
dotfiles_path=$(cd dotfiles && pwd)

for dir in $dirs; do
    originalPwd=$(pwd)
    cd $dir
    ignored=$(git status --ignored)
    for file in $ignored; do
        if [[ -f $file ]]; then
            new_location="$dotfiles_path/$dir/$(dirname $file)"
            mkdir -p $new_location
            cp $file $new_location
        fi
    done
    cd $originalPwd
done

Copy the files to Google Drive:
cp -r dotfiles ~/Google\ Drive\

Wait for files to sync
On new computer, go to your ~/Sites directory and do
cp -r ~/Google\ Drive/dotfiles/* .

And everything is synced using minimal bandwidth :)
You can also put this in a script and on a cron job to auto backup
env EDITOR=nano crontab -e

Paste:
*/10 * * * * ~/Sites/backupEnv.sh


text:
Q: Tagging a list of lists This is probably a stupid question, but I am having problems trying to  tag a list with identifying integers.
For example I have tried to tag {{a,b},{c,d},{e,f}} into {{a,b,1},{c,d,2},{e,f,3}}, via:
For[i==1,i<4,i++,Insert[{{a,b},{c,d},{e,f}}[[i]],i,3]]

and
For[i==1,i<4,i++,Append[{{a,b},{c,d},{e,f}}[[i]],i]]

and
Do[Insert[{{a,b},{c,d},{e,f}}[[i]],i,3],{i,3}].

However nothing so far has been successful. Any help would be appreciated.
Also note that I would like to be able to remove these tags later.

A: How about using MapIndexed :
list = {{a, b}, {c, d}, {e, f}};
tagged = MapIndexed[Append[#1, First@#2] &, list]

{{a, b, 1}, {c, d, 2}, {e, f, 3}}

To remove the tags later, you can do
Most /@ tagged

{{a, b}, {c, d}, {e, f}}

Edit:  Thanks to tomd for pointing out kglr's syntactic wonder :
MapIndexed[ Join, list ]

{{a, b, 1}, {c, d, 2}, {e, f, 3}}

As kglr points out, the operator form can also be convenient :
MapIndexed[Join] @ list

{{a, b, 1}, {c, d, 2}, {e, f, 3}}

A: Two possibilities (there are many more):
list = {{a, b}, {c, d}, {e, f}};

Flatten /@ Transpose[{list, Range[Length[list]]}]
i = 1; Join[#, {i++}] & /@ list

both of which give
(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)

If you really want to use Do and Insert, you need to remember that Do does not produce an output by default, and Insert doesn't modify the list in its first argument (it just creates a new list). But you could use Sow and Reap, for example:
Reap[Do[Sow@Insert[list[[i]], i, -1], {i, Length[list]}]][[-1, 1]]

(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)

To modify list directly in a Do loop, you could use AppendTo:
Do[AppendTo[list[[i]], i], {i, Length[list]}]
list

(* {{a, b, 1}, {c, d, 2}, {e, f, 3}} *)

You might also consider tagging by PositionIndex
listindex = PositionIndex[list]

(* <|{a, b} -> {1}, {c, d} -> {2}, {e, f} -> {3}|> *)

which you can use to get the index of any element of list by, for example
listindex[{c, d}]

(* {2} *)


text:
Q: Do I need async/await even when I do not need to know the result? Say I have an API call which does X and I make it async/await:
export default async (req: NextApiRequest, res: NextApiResponse) => {

    let success = await sendEmail({
    //...
    });

  return res.status(200).json({success: success});
};

I send back whether sending the email was successful or not.
But say I do not need to send anything back to the frontend: Will I still need async/await then? Would it be (minimally) faster to not use async/await? Or am I misunderstanding how async/await works?

A: No, you don't have to await if you don't care about the result; your understanding is correct. However, it's important that you do use await because if you don't, and the function sendEmail fails, you will not see the error. This can cause "uncaught exception" errors to be thrown, or if you have a try {} catch {} block somewhere, the failure of sendEmail will not be caught by it.


text:
Q: ng-repeat with if else Conditions Angularjs (Front-End [HTML] part) Looking for solution
Actual Data
tier_price:
    0:
      price: "29.0000"
      price_qty: 1
    1:
      price: "28.5000"
      price_qty: 2
    2:
      price: "28.0000"
      price_qty: 4
    3:
      price: "27.1500"
      price_qty: 6

Here are my inputs
price_qty = [1,2,4,6]    Note: Array is Dynamic
$index = [0,1,2,3]       Note: Index is depend on Array Size
count = 1 to onward (Will Manually increase by Click on Button)
Note: below code will run 4 times as each time Count increase e.g [1,2,4,6]
And also Once Condition match it further should NOT check other conditions, kind of break statement

     Matching Items (This is working perfect)

  <div ng-if="model.item.count < tier.price_qty && model.item.count == tier.price_qty+$index-3">
      /** Facing issue at this place, Look like need to add One more
          condition to achieve and don't know what should be the
          condition because now if i use [model.item.count == tier.price_qty+$index-3]
          Until Count==4 it work fine but when Count==5
          then it wrong again because condition is not perfect**/

 tier.price_qty">
     When Count is More than price_qty

below is what actually i want to achieve
Buy 1, Buy 3, Buy 5 are my Counts

A: Ok here goes! Firstly I had a hard time understanding what you were trying to achieve so I hope this comes close to answering you. The most flexible answer to showing ng-repeat elements and hiding them from a given expression is through use of a custom filter. Code below shows a simple example.
Also check out the docs and this answer here

    <input type="text" ng-model="count">

buy {{ qty.p_qty }} more and get price of RM{{ qty.price }}

A: Try this

 Matching Items (This is working perfect)

<div ng-show="count < qty.price_qty">
 HERE i am facing issue as when the Count is below price_qty, and it needs   to be stay in same INDEX as well, not really sure what should be other if-condition beside above if-condition.

  Let say if you Take Count==3, you will see 3 not exist in price_qty[], So first if-Condition will be false and it will jump inside this condition because 3<4 and Index==2, next also same 3<6 and Index==3

 qty.price_qty">
 When Count is More than price_qty

A: Update after seeing the pic above.
In controller.js
$scope.myArr = [];
$scope.checkAndValidate = function (type) {
  let tier = model.selected.tier_price.find(t => t.price_qty === $scope.count);
  if (type === 'ADD') {
    if (tier) {
      $scope.myArr.push({
        count: $scope.count,
        description: `Buy ${$scope.count} more and unlock special price of RM${tier.price_qty} per unit.` }
      );
    } else {
      if ($scope.count === 3) {
        //set tier for count == 3 by selecting where price is 28.5
        tier = model.selected.tier_price.find(t => t.price_qty === 1);
        $scope.myArr.push({
          count: $scope.count,
          description: `Buy ${$scope.count} more and unlock special price of RM${tier.price_qty} per unit.` }
        );
      }
    }
  } else if (type === "SUBTRACT") {
    //remove from the array
    // check first if record exist in array otherwise it will throw an error on splice.
    tier = $scope.myArr.find(t => t.count === $scope.count)
    if(trier) {
       $scope.myArr.splice(($scope.count - 1), 1);
    }
  }
}

$scope.$on('[MyAddbtnEvent]', function () {
  $scope.count++;
  $scope.checkAndValidate('ADD');
});

$scope.$on('[MySubtractBtntEvent]', function () {
  $scope.count = $scope.count - 1;
  $scope.checkAndValidate('SUBTRACT');
});

in .html

   {{myArr.description}}

Try the above logic/code carefully, it should work for your. You will be able to debug easily also


text:
Q: react videojs chromecast not working React does not try to implement videojs chromecast plugin.
I refer to this site: https://github.com/benjipott/video.js-chromecast
Thank you.
-- my code --

import React, { Component } from 'react';
import './App.css';
import videojs from 'videojs-chromecast';

class App extends Component {
  constructor() {
    super();

  }
  componentDidMount() {
    videojs('test',{
      chromecast:{
         appId:'APP-ID'
      }
    });
  }
  render() {
    return (
      <div className="App" >
        <video id="test" autoplay="autoplay" width="640" height="360" controls="controls">
          <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/ED_1280.mp4"

          />
        </video>
      </div>
    );
  }
}

export default App;

-- error massage --


text:
Q: Level 3 data with Stripe Payments I'm working on a SAAS system that allows purchases to be made through a clients own payment gateway.  We have one client that wants to use Stripe as their gateway, however as they are using Corporate Purchase Cards (CPC), it is necessary to pass Level 3 transaction details through.    I've been trying to get details from Stripe on how we ensure that Level 3 data can be passed through successfully, however I'm not really getting anywhere with this in terms of getting any definitive information we can work with.
Stripe say that their system supports level 3 data, we just need to provide the data in the first place, however there is nothing in their documentation about this and the example we have been provided only allows for a single item to be listed - we will need to support a basket of different items.
We are using the Payment Intents process and already support adding in Metadata to the transaction.   We've been told that adding metadata for SKU, Unit of Measure, Unit Price and Extended Price will allow level 3 processing, however this does seem to fall short of the information list on other sources (not to mention does not allow listing multiple items in the order due to the metadata keys needing to be unique)
Baed on that, our Metadata population looks like this (values hard coded to example purposes)
Dictionary<string, string> nRetVar = new Dictionary<string, string>();

nRetVar.Add("Customer", "John Smith");
nRetVar.Add("Email", "John.Smith@example.com");
nRetVar.Add("Order Number", "12345");
nRetVar.Add("Order Date", "2020-02-06");
nRetVar.Add("SKU", "ABCD1234");
nRetVar.Add("Unit of Measure", "1 Pack");
nRetVar.Add("Unit Price", "$10.00");
nRetVar.Add("Extended Price", "$15.00");

Stripe support never seem to directly answer any of the questions we have been asking about this, so it's proving very hard to get any progress on this - does anyone have enough experience with this to confirm if this metadata is enough to class as level 3, or is there more that we need to be adding?

A: Stripe supports Level 3 data in their API on both Charge and PaymentIntent. This feature though is currently "gated" which means you need to get access to the feature on your specific account. It's a bit similar to a long running beta. You should contact their support team again and ask for them to enable Level 3 data on PaymentIntent for your account.
The fields they are expecting as specific to that feature. This does not go inside metadata. The documentation is also gated which means you can only see it once you get access to the feature, to avoid confusion for other developers who don't have access.
You can see what the shape looks like in stripe-java for example on Charge here. The feature is not directly supported on PaymentIntent in the library though as this is still private.


text:
Q: Retrieving a specific part of a string in R I have the next vector of strings
[1] "/players/playerpage.htm?ilkidn=BRYANPHI01"
[2] "/players/playerpage.htm?ilkidhh=WILLIROB027"
[3] "/players/playerpage.htm?ilkid=THOMPWIL01"

I am looking for a way to  retrieve the part of the string that is placed after the equal sign meaning I would like to get a vector like this
[1] "BRYANPHI01"
[2] "WILLIROB027"
[3] "THOMPWIL01"

I tried using substr but for it to work I have to know exactly where the equal sign is placed in the string and where the part i want to retrieve ends

A: We can use sub to match the zero or more characters that are not a = ([^=]*) followed by a = and replace it with ''.
sub("[^=]*=", "", str1)
#[1] "BRYANPHI01"  "WILLIROB027" "THOMPWIL01"

data
str1 <-  c("/players/playerpage.htm?ilkidn=BRYANPHI01",
          "/players/playerpage.htm?ilkidhh=WILLIROB027",
          "/players/playerpage.htm?ilkid=THOMPWIL01")

A: Using stringr,
library(stringr)
word(str1, 2, sep = '=')
#[1] "BRYANPHI01"  "WILLIROB027" "THOMPWIL01"

A: Using strsplit,
strsplit(str1, "=")[[1]][2]
# [1] "BRYANPHI01"

With Sotos comment to get results as vector:
sapply(str1, function(x){
  strsplit(x, "=")[[1]][2]
})

A: Another solution based on regex, but extracting instead of substituting, which may be more efficient.
I use the stringi package which provides a more powerful regex engine than base R (in particular, supporting look-behind).
str1 <-  c("/players/playerpage.htm?ilkidn=BRYANPHI01",
          "/players/playerpage.htm?ilkidhh=WILLIROB027",
          "/players/playerpage.htm?ilkid=THOMPWIL01")
stri_extract_all_regex(str1, pattern="(?<==).+$", simplify=T)

(?<==) is a look-behind: regex will match only if preceded by an equal sign, but the equal sign will not be part of the match.
.+$ matches everything until the end. You could replace the dot with a more precise symbol if you are confident about the format of what you match. For example, '\w' matches any alphanumeric character, so you could use "(?<==)\\w+$" (the \ must be escaped so you end up with \\w).


text:
Q: Using ASP.NET MVC 2 credentials to log into other services Here is my scenario -
1/ I have an ASP.NET MVC application running on my server, it uses Windows Authentication.
2/ There is different web application (written in Java) somewhere else that also uses Windows Authentication.
In the Controller of my MVC application I need to grab some information from this other Web app. How can I connect to the "foreign" application using the credentials of the user that is accessing my Controller?
Any help appreciated.

A: Impersonation doesn't leave the ASPNET process. This means that you cannot delegate the credentials and access a remote resource using them. You could either swap back to Forms authentication which uses cookies or you will need Kerberos.


text:
Q: Формирование турнирной таблицы Хочу сформировать футбольную  турнирную таблицу на основе следующих данных:
games - расписания только матчей без результата, goals - результаты матчей.
Хочу формировать данные на лету в формате:
|Команда|Количество матчей|Победы|Поражения|Ничья|Голы|Очки|

Возможно так сделать в моей структуре данных, и что посоветуете изменить?
 CREATE TABLE `teams` (
      `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
       `title` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_unicode_ci',
        `created_at` TIMESTAMP NULL DEFAULT NULL,
        `updated_at` TIMESTAMP NULL DEFAULT NULL,
         PRIMARY KEY (`id`)
);

 // расписание
    CREATE TABLE `games` (
        `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
        `team1_id` INT(10) UNSIGNED NOT NULL,
        `team2_id` INT(10) UNSIGNED NOT NULL,
        `tournament_id` INT(10) UNSIGNED NOT NULL,
        `published` TINYINT(4) NOT NULL DEFAULT '1',
        `match_date` DATE NOT NULL,
        `match_time` TIME NOT NULL,
        PRIMARY KEY (`id`)
    )

 // результаты игр
    CREATE TABLE IF NOT EXISTS `goals` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `team_id` int(10) unsigned NOT NULL,
      `game_id` int(10) unsigned NOT NULL,
      `goals` tinyint(4) NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`),