text:
Q: NSURLConnection is growing in instruments, is this NSURLCache? So I have a memory problem with my app. The app has a MKMapView with MKOverlayRenderer which loads images on the map. Everything working ok but after 30-60 minutes the app crashes due memory.
With Instruments I found that NSURLConnection is growing and because I cannot find anything else (besides all kind of stuff I dont understand) I think thats is my problem.
Screenshot instruments after runnning for 1-2 minutes:

Screenshot instruments after running for 12-13 minutes:

Images are loaded like this in the canDrawMapRect method and saved to tmp folder (if I turn this off the NSURLConnection won't grow that high):
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[OperationQueues sharedOperationQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                               [data writeToFile:path atomically:YES];

Then loaded in the drawMapRect method.
I tried fixing this with the following code:
AppDelegate:
int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory
                                                     diskCapacity:cacheSizeDisk
                                                         diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

ViewController:
- (void)didReceiveMemoryWarning
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [super didReceiveMemoryWarning];
}

right after the request: [added]
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];

But as you can see in Instruments without any luck.

*

*Could this be my problem?

*Is this the NSURLCache which is growing or something else?

As requested a couple more screenshots from instruments:

A: First, 400 network requests in one minute seems pretty excessive. Some of those requests are probably duplicated or unnecessary. The amount of calls is obviously downloading a lot of information, and not giving the os much time to cleanup.
Second, your NSURLCache is actually providing more memory space than the default cache. I tested on my device/simulator and ios provides a default memory capacity of 512 000 bytes. You're caches are initialized with 4 194 304 bytes (and way more on disk).
I would suggest that you set your cache size smaller to see some improvement. However, investigating the amount of network requests that are made will provide longer term benefits.


text:
Q: Writing unit test with JUnit and Mockito I have a method in service layer for saving an item to database. This method first checks if there is an item with the same name in database. If there is, then it throws an exception with a message, if there is not then it just saves the new item. Here is the code;
public TodoList saveTodoList(TodoList todoList) {
    List<TodoList> match = StreamSupport.stream(getAllTodoLists().spliterator(), false)
            .filter(list -> list.getName().equals(todoList.getName()))
            .collect(Collectors.toList());

    if (match.size() > 0)
        throw new ExistingDataException("Todo List already exists!");
    else
        return todoListRepository.save(todoList);
}

I am trying to learn testing with JUnit 5 and Mockito and I am a bit confused about what to test in general. How many tests should I write for this method? Do I need to test stream(I don't even know how)? How can you decide what to test in a method?
Edit: Here is my test class and test methods for the save method;
@ExtendWith(MockitoExtension.class)
class TodoListServiceTest {
    @Mock
    private ITodoListRepository todoListRepository;

    @InjectMocks
    private TodoListService todoListService;

    @Test
    @DisplayName("Should save the list to the repository")
    public void whenGivenTodoListDoesNotExistInDatabase_ThenSaveNewList() {
        TodoList mockList = mock(TodoList.class);
        mockList.setId(1);
        mockList.setName("List 1");

        when(todoListRepository.save(any(TodoList.class))).thenReturn(mockList);

        TodoList actual = todoListService.saveTodoList(mockList);

        assertEquals(mockList.getId(), actual.getId());
        assertEquals(mockList.getName(), actual.getName());
    }

    @Test
    @DisplayName("Should throw exception if there is a list with given item's name")
    public void shouldThrowExistingDataException_IfThereIsAList_WithTheSameName() {
        TodoList mockList = mock(TodoList.class);
        mockList.setId(1);
        mockList.setName("List 1");

        Throwable actualException = assertThrows(ExistingDataException.class,
        () -> {
            todoListService.saveTodoList(mockList);
        });

        assertTrue(actualException.getMessage().contains("Todo List already exists!"));
    }

A: I will try to answer some of the questions that you have asked:
How many tests should I write for this method?: Essentially while writing test cases for a function or piece of code, there is no limit on how many test cases you should write. Generally you try to test atleast 1 positive flow and 1 negative flow. If your piece of code has many edge cases, then probably check those as well.
Do I need to test stream(I don't even know how)? : No. Stream is inbuilt java feature, you don't test inbuilt features. You just test your logic.
How can you decide what to test in a method?: As I mentioned earlier, you generally test positive flows and negative flows including any edge cases. For the above function it seems you have 1 positive and 1 negative flow. Your positive scenario could be where you expect value to not be present in your database and successfully store the data and your negative scenario can be when that data is already present you throw an exception. These are two minimum test cases you should write.

redpajama_set_name: RedPajamaStackExchange


text:
Q: multi dimensional char array? What I am trying to do is create an 2-d array of character strings
The following seg faults instantly, what is wrong?
void add2(char***b, char *i)
{
    if (!i) {
       b[0][0] = (char*) malloc(120);
       sprintf(b[0][0], "%s", "hithere");
       b[0][1] = (char*) malloc(120);
       sprintf(b[0][1], "%s", "bithere");
    } else {
       strcat(b[0][0], "\\\\");
       strcat(b[0][0], i);
       strcat(b[0][1], "\\\\");
       strcat(b[0][1], i);
    }

}
void add1(char ***b)
{
 add2(b,NULL);
 add2(b,"one");
 add2(b,"two");
 add2(b,"three");
}

int main()
{
 char **keys[2] = {0};
 int i,j;

 add1(keys);

 for (i = 0; keys[i]; i++)
     for (j = 0; keys[j]; j++)
     {
         fprintf(stderr, "%s\n", keys[i][j]);
         free(keys[i][j]);
     }

}

A: When you declare the array keys you are saying to the compiler that you want to work with an array of 2 pointers to pointers to chars and ask it to initialize those pointers to pointer to char to NULL. All good.
Then you call add1(). All good.
Then you call add2() and try to put into the first element of b[0] the return value from malloc(). But the value of b[0] is NULL. The NULL was put there in the main() function. b[0] has no elements!
When you have arrays of arrays (of arrays ...) in the form of pointers you need to malloc() (and free()) every level individually.

Edit
#include <stdlib.h>

int main()
{
    char **keys[2] = {0};
    keys[0] = malloc(20 * sizeof *keys[0]); /* 20 strings */
    keys[1] = malloc(20 * sizeof *keys[1]); /* 20 strings */

    for (int k=0; k<20; k++) {
        keys[0][k] = malloc(120); /* string with 119 chars + '\0' */
        keys[1][k] = malloc(120); /* string with 119 chars + '\0' */
    }

    /* use k[0][0] through k[0][19] */
    /* use k[1][0] through k[1][19] */

    for (int k=0; k<20; k++) {
        free(keys[0][k]);
        free(keys[1][k]);
    }
    free(keys[0]);
    free(keys[1]);

    return 0;
}

I put it all in the main() function, but it's the same idea if the malloc()s and free()s are in their own function.

A: The general procedure for dynamically allocating a 2D array of char * is something like this (for any other type T, replace char * with the desired type):
char ***new2DArr(size_t rows, size_t cols)
{
  char ***newArr = NULL;
  size_t i;
  newArr = malloc(sizeof *newArr * rows);
  if (newArr)
  {
    for (i = 0; i < rows; i++)
    {
      newArr[i] = malloc(sizeof *newArr[i] * cols);
      if (newArr[i])
      {
        /* initialize or assign newArr[i][0] - newArr[i][cols-1] here */
      }
    }
  }
  return newArr;
}

This assumes you know how many rows and columns you want ahead of time.  Note that you have allocated a table of pointers; you will still have to allocate memory for each string entry, like so:
char **myArr = new2DArr(10, 10);
myArr[0][0] = malloc(strlen("Hello, World") + 1);
if (myArr[0][0])
{
    strcpy(myArr[0][0], "Hello, World");
}

If you want to add new rows or new entries to existing rows, you're going to have to do some extra bookkeeping.
Here's one example that extends a single row:
char **extendRow(char **row, char *newEntry, size_t *numEntries)
{
  char **tmp = realloc(row, *numEntries + 1);
  if (tmp)
  {
    row = tmp;
    row[*numEntries] = malloc(strlen(newEntry) + 1);
    if (row[*numEntries])
    {
      strcpy(row[*numEntries], newEntry);
      (*numEntries)++;
    }
  }
  return row;
}

And you'd call it like
table[i] = extendRow(table[i], "This is a test", &entryCount);

The result is assigned back to table[i] in the event that the pointer value is changed by realloc().  I'm doing it this way instead of passing a pointer to table[i] just to keep the pointer gymnastics to a minimum.


text:
Q: Big collections in DDD using Entity Framework I try to use DDD to describe domain model and code first approach on mapping to database tables with entity framework (using fluent api).
For example I have 2 entities: Clubs and Users. Club has many Users. And I need to add new User to Club.
class User
{
    public string Name { get; set; }
    public Club Club { get; set; }
}

class Club
{
    public string ClubName { get; set; }
    public ICollection<User> Members { get; set; }

    public void AddNewMember(User user)
    {
        //..some logic and checks
        Members.Add(user);
    }
}

*

*So, should I load all users collection in Club to add new and save? Or it's excessively?

*What is the best way for modeling entities with big collections? Should I always load them? Or move then to another separate object?

A:
should I load all users collection in Club to add new and save?

No, you can add a new User to Club.Members and EF will save the new user. It's not necessary to load the users first.

What is the best way for modeling entities with big collections

That doesn't depend on the potential size of collections but on how you plan to access them. If there are Clubs with thousands of Users there's no objection whatsoever if you'd want to query a small subset of users by a query like this:
from c in Clubs
from u in c.Users
where c.Type = "Golf" && u.Membership = "Gold"
select u

I always encourage using navigation properties. An EF entity model is for accessing a database in the first place. DDD concerns are secondary.
Of course you should probably always prevent queries in which all users of a club are loaded, unless you really need them.

A: Well it probably makes sense, based on what I can tell from your scenario, to use the virtual keyword for your collection and let Entity Framework lazy-load your collection
https://msdn.microsoft.com/en-gb/data/jj574232
Basically let Entity Framework do the work for you

A: How about introducting a new domain concept 'Member'. Member could be an aggregate and have his own dedicated repo. or you simply turn off lazy loading with your original design and add it to its collection. this all depends on your business rules.
public class User
{
    public Guid UserId { get; set; }
}

public class Member
{
    public Guid ClubId { get; set; }

    public Guid UserId { get; set; }
}

public class Club
{
    public Guid ClubId { get; set; }

    public Member RegisterMember(User user)
    {
        // Check business rules..

        return new Member { UserId = user.Id, ClubId = this.ClubId };
    }
}


text:
Q: How to go to the next activity using textView in Android For example, when i reached the score of 26 (26 is inside textview) then my activity will stop and will go to the next activity. How can i do this? Thanks in advance .

A: I assume that you are populating the text in the TextView within your app somehow, so you could just check the text value when you call TextView.setText().
When the value == 26, then use the following code to open the next activity:
Intent myIntent = new Intent(this, ActivityName.class);
startActivity(myIntent);

Alternatively, you could have a thread which checks for the TextView object's text value periodically, if you really needed to do it that way. I don't think you can get a callback for a TextView as it's your app that is populating it anyway.

A: You can do like below...
MainActivity.java
package com.xxx.yyy.testapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudant_crud_integration.android01.testapp.R;
import com.cloudant_crud_integration.android01.testapp.SecondActivity;

public class MainActivity extends AppCompatActivity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);

        final Handler messageHandler = new Handler() {
            public void handleMessage(Message msg) {
                //Toast.makeText(getApplicationContext(), "Text View value before: " + tv.getText(), Toast.LENGTH_SHORT).show();
                tv.setText(String.valueOf(Integer.parseInt(tv.getText().toString()) + 1));
                //Toast.makeText(getApplicationContext(), "Text View value After: " + tv.getText(), Toast.LENGTH_SHORT).show();
                if (Integer.parseInt(tv.getText().toString()) == 26) {
                    Intent i = new Intent(getBaseContext(), SecondActivity.class);
                    startActivity(i);
                }
            }
        };
        new Thread() {
            public void run() {
                Message m = new Message();
                m.obj = 0;
                messageHandler.sendMessageDelayed(m,10000);
            }
        }.start();
    }
}

Hope this will help you. Thanks!

A: First take a textview in xml. Then define a textview in activity page then follow the code below...On the below code textview_id is the id you have written in the xml file and CurrentActivity is the name of that activity you are writing the code and NextActivity is the name of the Desire activity you want to go..
public class MainActivity extends AppCompatActivity {
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview = findviewById(R.id.textview_id);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          Intent in = new Intent(CurrentActivity.this,NextActivity.class);
          startActivity(in);
        }
    });

}


text:
Q: Distributing MySQL storage to drives by function I'm wondering if MySQL has any capability to specify that data belonging to a certain account (representing e.g., a particular app, or a particular corporate program) be stored at at some particular place in the filesystem (such as a particular drive or RAID), instead of bundling it inside the same physical file structure that is shared by every other account, table, and data element managed by MySQL for everybody on that server.
I'm aware that I can jigger MySQL to store its entire data bundle at a place other than the default place, but I was hoping there might be a way to do this by function, for "some data but not all data."

A: In MySQL 8.0, there are options to specify the location for each table or tablespace. See https://dev.mysql.com/doc/refman/8.0/en/innodb-create-table-external.html
In earlier versions of MySQL, these options didn't work consistently. You could specify the directory for individual table partitions, if your table was partitioned, but not for a non-partitioned table. Go figure. :-)
That said, I've never encountered a situation where it was worth the time to specify the physical location of tables. Basically, if your performance depends on the difference between one RAID filesystem vs. carefully choosing among different drives, you're already losing.
Instead, I've always done this approach:

*

*Use one datadir on a fast RAID filesystem. Use the default configuration of all tables and logs under this datadir.

*Allocate as much RAM as I can afford to the InnoDB buffer pool (up to the size of the database of course - no need to use more RAM than that). RAM is orders of magnitude faster than any disk, even an SSD. So you'd prefer to be reading data out of RAM.

If that's not enough performance, there are other things you can do to optimize, like creating indexes, or modifying the application code to do more caching to reduce database reads, or using a message queue to postpone database writes.
If that's still not enough performance, then scale out to multiple database servers. In other words, sharding.


text:
Q: Sending mail using phpmailer using smpt with dkim going thru postfix So I am using phpmailer using smpt and it is going thru postfix to send emails. When I send a email from my email it goes thru without a problem when it comes to using DKIM and DMARC. But when I send using phpmailer Im not getting a DKIM.
 <?php

   function send_email($to, $from_email, $from_name, $subject, $body,
      $is_html=false, $attachments=null) {
         global $smtp_host, $smtp_port, $smtp_user, $smtp_password;
       try {
        $email = new PHPMailer(true);
           if ($from_email === $smtp_user) {
             $email->isSMTP();
             $email->Host = $smtp_host;
             $email->Port = $smtp_port;
             $email->SMTPAuth = true;
             $email->Username = $smtp_user;
             $email->Password = $smtp_password;
             $email->SMTPSecure = 'tls';
          }

             $email->CharSet = 'UTF-8';
             $email->From      = $from_email;
             $email->FromName  = $from_email;
             $email->Subject   = $subject;
             $email->Body      = $body;
             $email->AddAddress($to);

         if ($is_html == true) {
             $email->IsHTML(true);
             $email->Encoding = 'base64';
         }

         if ($attachments != null) {
           foreach ($attachments as $attachment) {
                $apath = $attachment["path"];
                $aname = $attachment["name"];
                $email->AddAttachment($apath , $aname);
            }
        }

             $email->Send();
             $status = "success";
       }
           catch (phpmailerException $e) {
           $status = $e->errorMessage();
      }
           catch (Exception $e) {
           $status = $e->getMessage();
      }
          return $status;
     }

So I think I need to add this to my code but I'm not sure if I have to add this to the code. I was thinking that opendkim would just add the DKIM to the header. But its not.
$email->DKIM_domain = 'mydomain.com';
$email->DKIM_private = '/path/to/private_key';
$email->DKIM_selector = 'default';
$email->DKIM_passphrase = '1234567';

A: There are several ways you can implement DKIM signing.

*

*With those properties in PHPMailer, where your client script needs
direct access to your private keys. Good when you have no control over the sending environment - e.g. on shared hosting, but it means each individual sending script is responsible for signing, which isn't ideal.

*Getting your mail server to do the signing for you. Good when you have you own mail server and the ability to configure it - all mail that goes through it can be signed automatically, and you don't have to do anything at the client end.

*Using a signing SMTP relay/proxy server in line
with your existing mail server, such as Hmailserver for Windows. Good when you have your own mail server, but don't have admin access to it, or it can't do DKIM.

The selector needs to match the key you're signing with, so if you have a selector called s1, you would expect the public key to be available in a TXT record called s1._domainkey in your domain's DNS. The matching private key just needs to be somewhere safe and web-inaccessible on the server.
The DNS and key arrangements are the same whichever signing mechanism you use. If you use PHPMailer's DKIM, you don't need openDKIM, but if you want to use OpenDKIM, you need to tell it which selector you want to use in its config. Some mail servers (like GreenArrow that I use) allow dynamic control of selectors via custom message headers, but I don't think OpenDKIM supports that. You may be able to set up virtual MTAs within postfix that allow something similar.
For a PHPMailer reference, look at the DKIM signing example provided, and the DKIM test in the test suite.


text:
Q: How to mock a axios post with Vue + Jest I'm trying to test a method in Vue through Jest, and I have to test an Axios request within this method.
I have already searched for several solutions, but I have not found one that matches my scenario, I am not able to test this request, even though I have used moxios, and other npm packages
// config.vue
methods: {
    async config () {
      await axios.post('/users/config')
        .then(res => {
          if (res.data.success) {
            M.toast({html: res.data.message, classes: 'green'})
            this.$router.push('/tour')
          }
        })
        .catch(() => {
          M.toast({html: 'Não foi possível contactar, ou você não possui permissão!', classes: 'red'})
        })
    }
  }
```js
// config.spec.js

import { mount, createLocalVue } from '@vue/test-utils'
import config from '@/components/config'
import axios from '@/axios-auth'
jest.mock('axios')

const localVue = createLocalVue()

describe('config', () => {
  const spy = jest.fn()

  it('mocking axios request', () => {
    const wrapper = mount(config, {
      localVue
    })
    wrapper.vm.config()
    expect(spy).toHaveBeenCalledWith('/users/config', 'post', {success: true, message: 'Configuração realizada!'})
  })
})


text:
Q: Django: output aggregation of aggregation ordered by counts I'm trying to output the following data in my django templates.
Countries would be ordered descending by # of stories.
Cities would be ordered descending by # of stories (under that country)
Country A(# of stories)
  City A (# of stories)
  City B (# of stories)

Country B(# of stories)
  City A (# of stories)
  City B (# of stories)

My models are the following:
# Create your models here.
class Country(models.Model):
    name = models.CharField(max_length=50)

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country)

class Story(models.Model):
    city = models.ForeignKey(City)
    country = models.ForeignKey(Country)
    name = models.CharField(max_length=255)

What's the easiest way to do this?

A: This solution worked for me. You will need to tweak it to pass it to a template though.
from django.db.models import Count
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')

for country in all_countries:
    print "Country %s (%s)" % (country.name, country.story__count)
    all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
    for city in all_cities:
        print "\tCity %s (%s)" % (city.name, city.story__count)

Update
Here is one way of sending this information to the template. This one involves the use of a custom filter.
@register.filter
def get_cities_and_counts(country):
    all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
    return all_cities

View:
def story_counts(request, *args, **kwargs):
    all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
    context = dict(all_countries = all_countries)
    return render_to_response(..., context)

And in your template:
{% for country in all_countries %}

{{ country.name }} ({{ country.story__count }})

    {% for city in country|get_cities_and_counts %}

{{ city.name }} ({{ city.story__count }})

    {% endfor %}
{% endfor %}

Update 2
Variant with a custom method in model.
class Country(models.Model):
    name = models.CharField(max_length=50)

    def _get_cities_and_story_counts(self):
        retrun City.objects.filter(country = self).annotate(Count('story')).order_by('-story__count')
    city_story_counts = property(_get_cities_and_story_counts)

This lets you avoid defining a filter. The template code changes to:
{% for country in all_countries %}

{{ country.name }} ({{ country.story__count }})

    {% for city in country.city_story_counts %}

{{ city.name }} ({{ city.story__count }})

    {% endfor %}
{% endfor %}


text:
Q: What does the "r" mean in chrome dev tools when you're looking at a Backbone Object? I'm learning backbone and using chrome devl tools to look at objects in my browser. What does the 'r' mean?

A: It's the name of the constructor used to create the model object. However in this case the Backbone code has been minified.
If you create an instance of the base Model class it will be logged like this:

If you look at the Backbone source code you can find the constructor definition:
var Model = Backbone.Model = function(attributes, options) {

However, if your code is compressed the object will instead show up like this:

In your case you're using Backbone's extend mechanism to create a new model type that inherits from the base Model.
Uncompressed this will show up like this:

Again, we can look at the Backbone source code to understand why:
var extend = function(protoProps, staticProps) {
    // ...
    child.prototype.constructor = child;
    // ...
    return child
}

You can see that when the new model type is created Chrome doesn't have access to the name you want to use for the model. Instead it tries to do its best to infer the correct name from the variable names.
And then, after compression, you get the single-character class name that you are seeing in the console:


text:
Q: how to reshape the following tables? There is a couple of similar questions here but I failed to apply them to my case. I have many tables like this:
GDP:
time   |    AT    |    BE   |     BG    |     CF    | : United kingdom
2014Q4 |   4564   |  4646   |    6541   |     122   | :
2014Q3 |   1234   |  5789   |    3545   |     3546  | :
2014Q2 |   1456   |   354   |    3541   |     3543  | :
:      |    :     |    :    |     :     |      :    | :
1990Q1 |   1234   |  3546   |    6546   |     5466  |

REER:
the similar table etc.
how can I reshape them to the following style:
       Country | time   |    GDP |  REER  |   :..
            AT | 1990Q1 |   4564 |  4646  |   6541  |    122  | :
            AT | 1990Q2 |   1234 |  5789  |   3545  |   3546  | :
            AT | 1990Q3 |   1456 |   354  |   3541  |   3543  |
             : |  :     |   :    |   :    |     :   |      :  | :
United Kingdom | 2014Q4 |   1234 |  3546  |   6546  |   5466  |

the code
setwd ("D:/Documents/R/eurostatData")

library (SmarterPoland)
library(reshape)
library (xlsx)
# Write to xls file --------------------------------------------------------
save.xlsx <- function (file, ...)
{
  require(xlsx, quietly = TRUE)
  objects <- list(...)
  fargs <- as.list(match.call(expand.dots = TRUE))
  objnames <- as.character(fargs)[-c(1, 2)]
  nobjects <- length(objects)
  for (i in 1:nobjects) {
    if (i == 1)
      write.xlsx(objects[[i]], file, sheetName = objnames[i])
    else write.xlsx(objects[[i]], file, sheetName = objnames[i],
                append = TRUE)
  }
  print(paste("Workbook", file, "has", nobjects, "worksheets."))
}

# load TOC
TOC <- grepEurostatTOC("Production") # get everything about Production
TOC2 <- getEurostatTOC()
View(TOC)
# END TOC

dat_raw <- getEurostatRCV("sts_inpr_q") # quaterly

# how many unique values are?
unique(dat_raw$indic_bt)
unique(dat_raw$nace_r2) # initialy I need C - manufacturing
unique(dat_raw$time) # 1980-20104

production <- cast(dat_raw,  time ~ geo, subset= nace_r2=="C" & s_adj=="GROSS" )

# RESHAPING
# !!!!nothing to write, since the steps I did were not successful.!!!!

save.xlsx("data.xlsx", production, turnover_dom, turnover_ndom, import_price,  producer_prices, labour, GCF, gdp, inflation)

A: You can use gather from the tidyr package.
    GDP <- gather(GDP_table, Country, GDP, -time)
    REER <- gather(REER_table, Country, REER, -time)

Then use the merge function to put them together.
    data <- merge(GDP, REER)

I hope this helps.


text:
Q: angular firebase build error when try ionic build I got error when I tried to build ionic app.
Actually it wasn't a problem when I build in local, but when I check build status in ionic website, I got a bellow error.
using
angular5, ionic3

typescript: node_modules/angularfire2/firebase.app.module.d.ts, line: 10
              Class 'FirebaseApp' incorrectly implements interface 'FirebaseApp'. Property
              'automaticDataCollectionEnabled' is missing in type 'FirebaseApp'.

   L9:  export declare const FirebaseAppConfigToken: InjectionToken;
  L10:  export declare class FirebaseApp implements FBApp {
  L11:      name: string;

I have no idea. Should I downgrade firebase version?
UPDATE
I edited firebase.app.module.d.ts like the answer, but I got another error now. I edited .gitignore like this.
node_modules/*
!node_modules/angularfire2/firebase.app.module.d.ts

npm WARN angularfire2@5.0.0-rc.6.0 requires a peer of
  @firebase/app@^0.1.6 but none was installed.
npm ERR! Invalid tar header. Maybe the tar is corrupted or it needs to
  be gunzipped?
npm ERR! A complete log of this run can be found in: npm ERR!
  /home/gitlab-runner/.npm/_logs/2018-04-20T07_49_29_110Z-debug.log

A: I solved with npm install @firebase/app@0.1.10.
Error doesn't happen and build success.

A: I solved this problem adding this line:
automaticDataCollectionEnabled: boolean;
on the file:
node_modules/angularfire2/firebase.app.module.d.ts
Final result:
import { InjectionToken } from '@angular/core';
import { FirebaseAppConfig } from './';
import { FirebaseApp as FBApp } from '@firebase/app-types';
import { FirebaseAuth } from '@firebase/auth-types';
import { FirebaseDatabase } from '@firebase/database-types';
import { FirebaseMessaging } from '@firebase/messaging-types';
import { FirebaseStorage } from '@firebase/storage-types';
import { FirebaseFirestore } from '@firebase/firestore-types';
export declare const FirebaseAppConfigToken: InjectionToken<FirebaseAppConfig>;
export declare class FirebaseApp implements FBApp {
    name: string;
    options: {};
    automaticDataCollectionEnabled: boolean; // missing line
    auth: () => FirebaseAuth;
    database: () => FirebaseDatabase;
    messaging: () => FirebaseMessaging;
    storage: () => FirebaseStorage;
    delete: () => Promise<any>;
    firestore: () => FirebaseFirestore;
}
export declare function _firebaseAppFactory(config: FirebaseAppConfig, appName?: string): FirebaseApp;

A: You have to add the property automaticDataCollectionEnabled to the FirebaseApp class (node_modules/angularfire2/firebase.app.module.d.ts).
export declare class FirebaseApp implements FBApp {
   name: string;
   options: {};
   automaticDataCollectionEnabled: boolean; // add it like this
   auth: () => FirebaseAuth;
   database: () => FirebaseDatabase;
   messaging: () => FirebaseMessaging;
   storage: () => FirebaseStorage;
   delete: () => Promise<any>;
   firestore: () => FirebaseFirestore;
}

A:  npm i @firebase/app@^0.1.6

This worked for me. As the warning says, firebase/app needs to be installed separately. Did the same and my project compiled successfully.


text:
Q: Cauchy's integral formula for a singular function Cauchy's integral theorem states that
$$\int_{\partial \mathbb{D}} f(z) \, d z =0 $$
for all functions $f$ that are holomorphic in $\mathbb{D} = \{|z| \leq 1\}$, i.e. no singularities are allowed in $\mathbb{D}$.
Here, $\partial \mathbb{D}$ denotes the boundary of $\mathbb{D}$ and hence $f$ is holomorphic along the path of integration.
Now my question regards functions of the form $f_\alpha(z) = \frac{1}{(1-z)^\alpha}$ where $0<\alpha<1$, which are only holomorph in the open disk $\{|z| < 1\}$.
Is Cauchy's theorem still applicable? I did some computations and it seems to hold true for $f_\alpha$. Is there a reference for a more general Cauchy theorem that allows (integrable) singularities along the path of integration?
Thanks!

A: If $f$ has a singularity at a point $p$ on the contour $\Gamma$, $\int_\Gamma f(z)\; dz$ may be undefined.  What is generally done is to deform the contour $\Gamma$ slightly to avoid $p$ and stay in the region where $f$ is holomorphic.
Cauchy's theorem, residues etc. can then be applied to the integral over the
deformed contour, and a limit taken as the amount of deformation goes to $0$.


text:
Q: Why does Apache HTTP mod_proxy perform unpredictably in Docker Swarm? I have a fairly simple Docker implementation that consists of two containers running on an overlay network:  one running Apache HTTP 2.4.16 and another running a Spring Boot app (using Tomcat 8).  The Apache container handles all external https requests and proxies traffic (via mod_proxy_http) to the Spring Boot app running in the second container.  My proxy configs look like this:
ProxyPass /web-portal http://web-portal:8080/web-portal
retry=0
ProxyPassReverse /web-portal http://web-portal:8080/web-
portal
ProxyTimeout 300

I'm setting the Spring Boot/Tomcat server.connection-timeout to the same value as Apache's ProxyTimeout
This all works just fine when running in Docker; however, I'm wanting to move to Docker Swarm and that's when I run into issues.  I've set up a very simple Docker swarm environment with a single node that also serves as the manager (by running docker swarm init).  I am running the same exact containers that I describe above.  Initially, behavior is as expected: Apache proxies https traffic destined to /web-portal to the Spring Boot app.  After a period of time (that is seemingly unpredictable) the proxy stops working and I see entries like this in the Apache ssl_error.log file:
[proxy_http:error] [pid 222] (70007)The timeout specified has expired:
[client 10.255.0.2:64842] AH01102: error reading status line from
remote server web-portal:8080, referer:
https://ojbc.org/web-portal/

[proxy:error] [pid 222] [client
10.255.0.2:64842] AH00898: Error reading from remote server returned by
/web-portal/activity, referer: https://ojbc.org/web-
portal/

When this happens, the only solutions I've found are to docker rm -f the Apache HTTP container and create a new container (docker run) or just wait for some period of time and the proxy starts working again.
To eliminate variables, I removed Spring Boot from the equation and just ran plain ol' Tomcat8 in the second container, but the issues were still present.  I've also tried proxying via mod_proxy_ajp rather than mod_proxy_http -- but I get similar errors.
I have never seen these problems when running these containers in normal (non-Swarm) Docker mode.  I've scoured this site, and others, trying to better understand why introducing Docker Swarm would cause these issues and what the solution might be, but I'm at a loss.  I'm guessing it might have something to do with load balancing in Docker Swarm, but I don't have much to back up that theory.  I appreciate any thoughts you may have. Please let me know if I can provide any further detail about my environment.


text:
Q: Figure of $SO(10)$ grand unified theory in $E_6$ from Wikipedia In this figure from Wikipedia, it shows that the representations of particles of $SO(10)$ grand unified theory, their patterns of charges for particles in the $SO(10)$ model, rotated to show the embedding in $E_6$.
Questions

*

*This figure seems to show the 5 axes, including the $B$, $W$, $W'$, $g^8$, and $g^3$. How are these 5 axes related to the previous question for the 3 axes? Figure of $SO(10)$ grand unified theory from Wikipedia

*How is the $SO(10)$ model rotated to be the embedding in $E_6$? reading from this figure.

*Look into the color patterns closely, it seems that the

*

*orange and red are on two flipped sides of the same object.

*purple and blue are on two flipped sides of the same object.

*yellow and green are on two flipped sides of the same object.

What do these two sides of colors on the flipped sides imply?


text:
Q: Combining metrics for score card We are building a score card system to measure the performance of various groups in the organization.  The scores are generated by true / false metrics on individual transactions that each group completes.
Transactions are qualified for measurement by some metrics but not others.  The number of transactions also varies between groups.  Here is a sample of what the data looks like:
Group  Transaction   Metric1Score  Metric1Qualified   Metric2Score  Metric2Qualified  ...
G1     Tran1         1             1                  0             1
G1     Tran2         1             1                  1             1
G2     Tran3         0             0                  0             1
...

We'd like to combine all of these transaction metrics into one score per group and be able to compare scores between groups.  Does anyone know how to get started on this or have any places to refer to?

A: The first question I'd ask is, what is the business problem you're trying to solve?
The second question I have is - are these groups performing largely the same function? I don't think you can really compare transactional scores unless it's a very similar function; for example, if the groups were the call center reps under each individual supervisor in the center, and the transactions are customer support calls or sales calls. Trying to compare a software engineering group with a financial analyst group in terms of transactional scores is never going to work out - the nature of the transactions and the metrics is far too different.
It's easier to make score comparisons across diverse groups if you have relationship scores, because those are easier to make consistent across groups. Even then there are caveats - a low score is about the relationship, not necessarily the group itself.
I think the best way to integrate diverse metrics is to not do it. At least not analytically. For any business, you have your business strategy and have somehow developed some faith (vision of business leaders, demonstrated analytically, etc.) that certain actions will help you achieve that strategy. Once you have organizational buy-in that something is important, go ahead and measure and report on that thing. If you are solving for reporting up to a higher level of management that doesn't want that level of detail, I think the correct approach is not to try to integrate datapoints that resist integration, but to report at a more abstract level. Report on progress against the strategy and give visibility into how the operating groups are using the transactional metrics, with the opportunity to dive deeper if they are interested.
The "Balanced Scorecard" approach is something I hear talked about in professional groups, although I've never seen it implemented. You can find more information here: http://www.balancedscorecard.org/BSCResources/AbouttheBalancedScorecard/tabid/55/Default.aspx
Hope this helps. Please comment if you're able to add some more information about the business problem you're trying to solve.


text:
Q: Android Parse.com query relation I have a custom Employee table and custom Organization table.
Employee table has a column Relation< Organization >.
I want to query organizations of an employee object.
// I have an employee object
ParseObject employee = ParseUser.getCurrentUser().getParseObject("employee");
// I get relation query
ParseQuery<ParseObject> query = employee.getRelation("organizations").getQuery();
// I execute query like this
query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> list, ParseException e) {
            // code here
        });

In my callback I'm getting ClassCastException:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
        at com.parse.ParseRESTQueryCommand.constructParameters(ParseRESTQueryCommand.java:84)
        at com.parse.ParseRESTQueryCommand.findCommand(ParseRESTQueryCommand.java:15)
        at com.parse.ParseDefaultQueryController.findFromNetworkAsync(ParseDefaultQueryController.java:57)
        at com.parse.ParseDefaultQueryController.access$100(ParseDefaultQueryController.java:17)
        at com.parse.ParseDefaultQueryController$6.runOnNetworkAsync(ParseDefaultQueryController.java:193)
        at com.parse.ParseDefaultQueryController.runCommandWithPolicyAsync(ParseDefaultQueryController.java:292)
        at com.parse.ParseDefaultQueryController.findWithCachePolicyAsync(ParseDefaultQueryController.java:201)
        at com.parse.ParseDefaultQueryController.findAsync(ParseDefaultQueryController.java:28)
        at com.parse.ParseQuery.findAsync(ParseQuery.java:1187)
        at com.parse.ParseQuery$2$1.then(ParseQuery.java:1129)
        at com.parse.ParseQuery$2$1.then(ParseQuery.java:1125)
        at bolts.Task$14.run(Task.java:796)
        at bolts.BoltsExecutors$ImmediateExecutor.execute(BoltsExecutors.java:105)
        at bolts.Task.completeAfterTask(Task.java:787)
        at bolts.Task.continueWithTask(Task.java:599)
        at bolts.Task.continueWithTask(Task.java:610)
        at bolts.Task$12.then(Task.java:702)
        at bolts.Task$12.then(Task.java:690)
        at bolts.Task$14.run(Task.java:796)
        at bolts.BoltsExecutors$ImmediateExecutor.execute(BoltsExecutors.java:105)
        at bolts.Task.completeAfterTask(Task.java:787)
        at bolts.Task.continueWithTask(Task.java:599)
        at bolts.Task.continueWithTask(Task.java:574)
        at bolts.Task.onSuccessTask(Task.java:690)
        at bolts.Task.onSuccessTask(Task.java:680)
        at bolts.Task.onSuccessTask(Task.java:714)
        at com.parse.ParseQuery$2.call(ParseQuery.java:1125)
        at com.parse.ParseQuery$2.call(ParseQuery.java:1122)
        at com.parse.ParseQuery.doWithRunningCheck(ParseQuery.java:1091)
        at com.parse.ParseQuery.findInBackground(ParseQuery.java:1122)

What am I doing wrong? This is done exactly like in Parse tutorial (https://www.parse.com/docs/android/guide#relations-using-parse-relations). I didn't find any answer to this on Google or SOF.
Any help will be appreciated.

A: From comment by @cYrixmorten
ParseUser.getCurrentUser().getParseObject("employee") will not by default return the employee object, only the pointer.
Should work if you fetch() your user before calling getParseObject().
If you switch to use an array of pointers instead of a relation you can do something like ParseQuery.getQuery("Employee").get("CITLvyOFuK").include("organizations"). The return object will contain a Employee object where the list of organizations is populated with data, e.g. employee.getList("organizations").get(0).getString("name") will work.
A relation is great if you expect a lot (100+) pointers. This way avoiding to fetch a lot of data for every employee. In your case I see no reason for not simply using an array of organizations.
And a note from me
If you want to add array of pointers in Parse Data Browser use this pattern:
[{"__type":"Pointer","className":"CLASSNAME","objectId":"OBJECTID"},{"__type":"Pointer","className":"CLASSNAME","objectId":"OBJECTID"}]

A: here's how you do it. survey being the header record with hearaboutusID as the key field in survey linking to hearaboutus table which is a relation.
    ParseQuery query = new ParseQuery("survey");
    try {
        query.include("hearaboutus");
        poSurvey = query.get(<objectID>);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    ParseQuery<ParseObject> qry = poSurvey.getRelation("hearaboutusID").getQuery();
    qry.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> hearList, ParseException e) {
            for(ParseObject hear : hearList){
                Log.d("HEAR ABOUT US ITEM: ", hear.getObjectId());
            }
        }
    });

A: https://www.dropbox.com/s/b4h2to1cdbx087b/SAmpleApp.zip?dl=0 try this i have done similar few weeks back whole src code is in it,you might are gonna need few libraries to run it....hope this will help.


text:
Q: How to prevent assigning an event listener multiple times to an element when using Click Outside hooks? There are many versions of the click outside hooks out there that will attach a "mousedown" or "touchstart" event listener to the document and close a dropdown or modal window when you click outside...
The problem is if you have many dropdowns using the same hook you end up with the same events attached to the document multiple times.
How to prevent that? and does it matter as long as you remove them when you unmount the components?
I've already researched and there doesn't seem to be a way to check whether a dom element already has an event attached to it.
An example taken from: useOnClickOutside
const useOnClickOutside = (ref, handler) => {
  useEffect(() => {
    const listener = event => {
      // Do nothing if clicking ref's element or descendent elements
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    const escape = event => {
      if (event.keyCode === 27) {
        handler(event);
      }
    };

    // these event listeners pile up on the document if you have several component using that hook
    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);
    document.addEventListener('keydown', escape, false);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
      document.removeEventListener('keydown', escape);
    };
  }, [ref, handler]);
};

Here using that hook on 5 different dropdowns on the page, assigns the same event listener 5 times to the document

A: The best practice to do this is using useEffect cleanup function
const handleMouseDown = e => {
  console.log(e)
}

useEffect(() => {
  document.addEventListener("mousedown", handleMouseDown)
  // cleanup
  return () => {
    document.removeEventListener("mousedown", handleMouseDown)
  }
}, [])

By passing the empty array [] to the useEffect you guarantee that the event listeners are registered only in the initial mounting of the component. By using the cleanup function, you avoid registering it more than once.

A: if we are calling this component multiple times then in that case also on each and every mount event will be attached to the document.
Possible to write useEffect with event listener on top of the component and call handler method from anywhere then it won't happen.


text:
Q: Javascript get id from a randomized id Hello i want to get the id using this code, (chart-0 to be replaced by the id)
var chart = new google.visualization.AreaChart(document.getElementById('chart-0');
from this element
<div id="<?=$graph_id?>" style="width: 100%; height: 200px;">

im using php to increment the value
<?php

        $g = 0;
   while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

        $graph_id = 'chart-' .$g;
         $g++;
  ?>

Using a div element, im retrieving the id with data-target="#<?=$current_id?> and it work fine, but how to do it with javascript get.documentByID?
This one data-target="#<?=$current_id?> is another example, how to target the <?=$graph_id?> using get.documentByID
Thank you in advance

A: document.getElementById is used with ID known beforehand.
In your case, you can use instead document.querySelector to match the first element or document.querySelectorAll to match all elements .
Indeed, document.querySelector accepts CSS selectors :
document.querySelector('[id^="chart-"]')

means element has id starts with chart-

and to parse ID Just remove the prefix "chart-" and call parseInt if needed :
   const prefix = "chart-";
   const parseId= (fullId) => parseInt( fullId.slice(prefix.length) );
   parseId(
     document.querySelector('[id^="chart-"]').id
   );

  const parseId= (fullId) => fullId.slice("chart-".length);
   parseId(
     document.querySelector('[id^="chart-"]').id
 );
console.log(
      document.querySelectorAll('[id^="chart-"]')
.length,
  ' elements has ID starts with "chart-"'
)

console.log('Random ID is ',
   parseId(document.querySelector('[id^=chart-]').id)
 )

A: Problem:
The php code generates ids on the server. The client doesn't know which number the php started at or how many there are.
Possible solutions:

*

*Echo each id on the php, which means you have to handcode each id into the code already, since you cant loop php code in js.

*Have the php write the ids in an array variable in the javascript so you can loop over them.

*Assume the id always starts at 0 so you can getElementById in a loop.

Better solution:
Use code that doesn't rely on knowing the id and parse it dynamically or just use a class name instead. Both results in the same thing though, only the selector differs.

The advantages here are:

*

*It doesn't matter how many charts you have.

*Or at which number the ids start.

*Or if there's gaps in the ids.

*Seperation of javascript and php code.

PHP Only version: These PHP snippets ar examples only, this isn't good code. The code may also not work 100% as I'm not a php programmer. Just trying to show the differences and issues.

'
        $g++;
    }
?>

Different version, less bad, but equally annoying to work with.

';
?>


text:
Q: Appropriate sql query for join two table Consider that we have two tables like the following tables :
Products TABLE : ( Note only in this table ID is product id )
|     ID     |   type_id |
| ---------- | --------- |
|      1     |     1     |
|      2     |     1     |
|      3     |     1     |
|      4     |     2     |
|      5     |     2     |

bundle_product_relation TABLE:
| ID | bundle_id | product_id |
| ---| --------- | -----------|
| 1  |     1     |      1     |
| 2  |     1     |      2     |
| 3  |     1     |      3     |
| 4  |     2     |      1     |
| 5  |     2     |      5     |
| 6  |     3     |      1     |
| 7  |     3     |      3     |

I want to write a function that takes the type_id as input and returns bundles whose their all products have that type_id
For example f(1) returns bundles ids : 1 , 3.
Bundle with id 2 has a product with ID 5, which is the type_id 2, So does not count as the output of the function.
What is the right query to get this output?

A: DROP TABLE IF EXISTS products;

CREATE TABLE products
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
, type_id INT NOT NULL
);

INSERT INTO products VALUES
(1,1),
(2,1),
(3,1),
(4,2),
(5,2);

DROP TABLE IF EXISTS product_bundle;

CREATE TABLE product_bundle
(product_id INT NOT NULL
,bundle_id INT NOT NULL
,PRIMARY KEY(product_id,bundle_id)
);

INSERT INTO product_bundle VALUES
(1,1),
(2,1),
(3,1),
(1,2),
(5,2),
(1,3),
(3,3);

SELECT pb.bundle_id
  FROM product_bundle pb
  JOIN products p
    ON p.id = pb.product_id
 GROUP
    BY bundle_id
HAVING MAX(p.type_id) = MIN(p.type_id)
   AND MAX(p.type_id) = 1;
+-----------+
| bundle_id |
+-----------+
|         1 |
|         3 |
+-----------+

A: You can start by creating a join which will return all results:
SELECT *
FROM bundle_product_relation
INNER JOIN products on products.ID = bundle_product_relation.product_id

Then you says you need to filter a certain type_id:
SELECT *
FROM bundle_product_relation
INNER JOIN products on products.ID = bundle_product_relation.product_id
WHERE products.type_id=1

Lastly, you only seem to be interested in bundle_id:
SELECT bundle_product_relation.bundle_id
FROM bundle_product_relation
INNER JOIN products on products.ID = bundle_product_relation.product_id
WHERE products.type_id=1

I did not do any test on correctness, that is left as an exercise to you.


text:
Q: Get Visible portion Image from UIimageView in Scrollview I have a UIImageView in a UIScrollView in which can be zoomed in and out. Now, after the user has selected the specific content to be zoomed in, I want to crop that part of image present on the scrollview and get it in the form on UIImage.
For that I am using
extension UIScrollView {

var snapshotVisibleArea: UIImage? {
    UIGraphicsBeginImageContext(bounds.size)
    UIGraphicsGetCurrentContext()?.translateBy(x: -contentOffset.x, y: -contentOffset.y)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

}
But when I implement this, the quality of the image get extremely degraded. Even If I use a 4K image, the final product looks like a 360p resolution.
This logic is just basic capturing of the screen content.
I know there can be a better way but I am not able to find a solution.
Any help is highly appreciated.

A: You can try this:
let context:CGContext = UIGraphicsGetCurrentContext()!
context.interpolationQuality = .high

Also I'm not sure but image quality could be improve if you initialize image context with this code: UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)


text:
Q: Angular2 list and @hostlistener our application requires to navigate in an html ul li based dropdown in angular 2. i have used below to capture the keys pressed, but problem is that this listener only captures the first key pressed and ignores the subsequent ones.
@HostListener('document:keypress', ['$event'])
onKeyPressHandler(event: KeyboardEvent) {
    alert(event.key);
    this.text = this.text.concat(event.key);
    alert(this.text);  // *alerts only the first entered key.*
}

Please can you let know what needs to be done for capturing all the keys pressed by the user.


text:
Q: How to get a hierarchical list of nodes and relations as json in Neo4j I have a neo4j DB in which user data and relations between them would be stored, the end user will interact with this data from a mobile app (app is in Flutter, we use a nestjs neo4j connector in between). Now we have to enable offline access to data. So the idea was to export the data of the user from neo4j as json and use it when offline, when the device gets online we will make the changes to the DB. I have some problem getting the data as json
This is a rough sample what I am trying to do

The cypher commands to create these nodes
CREATE (c:Computer {name: 'Andy',uid:'123'})
CREATE (d1:Drive {name: 'Drive1',capacity:"2gb",uid:'223'})
CREATE (d2:Drive {name: 'Drive2',capacity:"4gb",uid:'233'})
CREATE (f1:Folder {name: 'desktop',type:"special",uid:'323'})
CREATE (f2:Folder {name: 'mydocuments',type:"special",uid:'333'})
CREATE (f3:Folder {name: 'myprojects',type:"normal",uid:'343'})

CREATE (t1:File {name: 'text1',type:"txt",size:"1kb",uid:'423'})
CREATE (t2:File {name: 'text2',type:"txt",size:"1.5kb",uid:'433'})
CREATE (t3:File {name: 'text3',type:"txt",size:"2kb",uid:'443'})

CREATE (do1:File {name: 'doc1',type:"doc",size:"1mb",uid:'523'})
CREATE (do2:File {name: 'doc2',type:"doc",size:"1.5mb",uid:'533'})
CREATE (do3:File {name: 'doc3',type:"doc",size:"2mb",uid:'543'})

CREATE (c)-[r1:PARTITION{during: 'osinstall'}]->(d1)
CREATE (c)-[r2:PARTITION{during: 'setup'}]->(d2)

CREATE (d1)-[r3:AutoCreated{during: 'osinstall',type:"folder"}]->(f1)
CREATE (d1)-[r4:AutoCreated{during: 'osinstall',type:"folder"}]->(f2)
CREATE (f1)-[r5:Shortcut{type:"folder"}]->(c)
CREATE (f2)-[r6:Shortcut{type:"folder"}]->(c)
CREATE (d2)-[r7:UserCreated{type:"folder"}]->(f3)

CREATE (d2)-[r8:UserCreated{type:"file"}]->(t1)
CREATE (d2)-[r9:UserCreated{type:"file"}]->(t2)
CREATE (f3)-[r10:UserCreated{type:"file"}]->(t3)
CREATE (f3)-[r11:UserCreated{type:"file"}]->(do1)
CREATE (d2)-[r12:UserCreated{type:"file"}]->(do2)
CREATE (do2)-[r13:Shortcut{type:"file"}]->(f1)
CREATE (f3)-[r14:Shortcut{type:"folder"}]->(f1)
CREATE (f1)-[r15:UserCreated{type:"file"}]->(do3)
CREATE (do3)-[r16:Shortcut{type:"file"}]->(f3)

CREATE (c1:Computer {name: 'Randy',uid:'c1-123'})
CREATE (c1d1:Drive {name: 'Drive1',capacity:"1gb",uid:'c1-223'})
CREATE (c1t1:File {name: 'text1',type:"txt",size:"1kb",uid:'c1-423'})
CREATE (c1t2:File {name: 'text2',type:"txt",size:"1.5kb",uid:'c1-433'})
CREATE (c1sh1:SharedDrive {name:"SharedDrive",uid:'c1-s1'})

CREATE (c1)-[c1r1:PARTITION{during: 'osinstall'}]->(c1d1)
CREATE (c1d1)-[c1r2:UserCreated{type:"file"}]->(c1t1)
CREATE (c1d1)-[c1r3:UserCreated{type:"file"}]->(c1t2)
CREATE (c1t1)-[c1r4:Share{type:"file"}]->(c1sh1)
CREATE (c1)-[c1r5:SHAREDPARTITION{during: 'osinstall'}]->(c1sh1)
CREATE (c1)-[common:Network]->(c)

I want to query a root node(say Andy) with the users uid and get the data in the format
    {
    "name": "Andy",
    "uid":"123",
    "PARTITION":[
        {
            "name": "Drive1",
            "capacity":"2gb",
            "uid":"223",
            "Folder":[
               { "name": "desktop","type":"special","uid":"323",
               "File":[
                   "... Detail about file doc3 here.."
               ],
               "Shortcut":[
                   "... Detail about file doc2 here.."
               ]

               },
               {"name": "mydocuments","type":"special","uid":"333"}
            ]
        },
        {
            "name": "Drive2",
            "capacity":"4gb",
            "uid":"233",
            "Folder":[
               { "name": "myprojects","type":"normal","uid":"343",
                "File":[
                    "...Detail about Files doc1, text3 here..."
                ],
                "Shortcut":[
                    "... Detail about file doc3 here.."
                ]

               }
            ],
            "File":[
                "...Detail about Files text1,text2,doc 2 here..."
            ]

        }
    ],
    "Shortcut":[
        {
            "name": "desktop","type":"special","uid":"323"
        },{
            "name": "mydocuments","type":"special","uid":"333"
        }
    ],
    "Network":[
        {
            "name": "Randy",
            "uid":"c1-123",
            "SHAREDPARTITION":["...HERE ONLY NEED THE files and folders from shareddrive other drives should not show up..."]

        }
    ]
}

I want to add the relations from and to the node as key and for the value add a list of nodes(with their related properties) connected to it and move to the next one. I don't know how to do so. So far I have tried
match (n:Computer{uid:"123"})-[r:PARTITION]->(x)
match b=(x)-[*]->(y)
with collect(b) as c
call apoc.convert.toTree(c) yield value
return value

but this does not return the shortcut file paths properly ie., if I add a shortcut from doc3(at desktop) to myproject, I don't find the file detail with myproject shortcuts I need it at both places at desktop(under files) and myproject(under shortcut) folder. Also the shared computer details are not fetched(all drives must not be fetched just the sharedpartition). Apart from this the return data is not in the expected format and I have to process it in the app after fetching it.
Can someone help me with this?
I am also open to different solutions for neo4j flutter offline.

A: You can create a connection from the root node then collect them all together. Just make sure you are using the relationship that you want to extract. Below is not exactly you described but closest to your json format.
match b=(n:Computer{uid:"123"})-[r:PARTITION]->(x:Drive)-[]-(y:Folder)-[]-(z:File)
match c=(n)-[:Shortcut]-()
match d=(n)-[:Network]-()-[:SHAREDPARTITION]-()
with collect(b) + collect(c) + collect(d) as t
call apoc.convert.toTree(t) yield value
return value

Result:

 {
  "name": "Andy",
  "uid": "123",
  "_type": "Computer",
  "_id": 298,
  "partition": [
    {
      "uid": "233",
      "_type": "Drive",
      "name": "Drive2",
      "_id": 300,
      "partition.during": "setup",
      "capacity": "4gb",
      "usercreated": [
        {
          "uid": "343",
          "shortcut": [
            {
              "uid": "543",
              "size": "2mb",
              "shortcut.type": "file",
              "_type": "File",
              "name": "doc3",
              "_id": 309,
              "type": "doc"
            }
          ],
          "_type": "Folder",
          "name": "myprojects",
          "usercreated": [
            {
              "uid": "443",
              "size": "2kb",
              "_type": "File",
              "name": "text3",
              "_id": 306,
              "type": "txt",
              "usercreated.type": "file"
            },
            {
              "uid": "523",
              "size": "1mb",
              "_type": "File",
              "name": "doc1",
              "_id": 307,
              "type": "doc",
              "usercreated.type": "file"
            }
          ],
          "_id": 303,
          "type": "normal",
          "usercreated.type": "folder"
        }
      ]
    },
    {
      "uid": "223",
      "_type": "Drive",
      "name": "Drive1",
      "_id": 299,
      "partition.during": "osinstall",
      "capacity": "2gb",
      "autocreated": [
        {
          "autocreated.during": "osinstall",
          "autocreated.type": "folder",
          "uid": "323",
          "shortcut": [
            {
              "uid": "533",
              "size": "1.5mb",
              "shortcut.type": "file",
              "_type": "File",
              "name": "doc2",
              "_id": 308,
              "type": "doc"
            }
          ],
          "_type": "Folder",
          "name": "desktop",
          "usercreated": [
            {
              "uid": "543",
              "size": "2mb",
              "_type": "File",
              "name": "doc3",
              "_id": 309,
              "type": "doc",
              "usercreated.type": "file"
            }
          ],
          "_id": 301,
          "type": "special"
        }
      ]
    }
  ],
  "shortcut": [
    {
      "uid": "333",
      "shortcut.type": "folder",
      "_type": "Folder",
      "name": "mydocuments",
      "_id": 302,
      "type": "special"
    },
    {
      "uid": "323",
      "shortcut.type": "folder",
      "_type": "Folder",
      "name": "desktop",
      "_id": 301,
      "type": "special"
    }
  ],
  "network": [
    {
      "_type": "Computer",
      "name": "Randy",
      "uid": "c1-123",
      "_id": 310,
      "sharedpartition": [
        {
          "_type": "SharedDrive",
          "name": "SharedDrive",
          "uid": "c1-s1",
          "_id": 473,
          "sharedpartition.during": "osinstall"
        }
      ]
    }
  ]
}


text:
Q: GWT: Identify which Button in a Table was clicked I am struggling with something which I think should be extremely easy.
I have a Grid in GWT, which I populate its cells with some textual data; at the last column I want to place a Button (or Image) which when clicked, I would like to take some action using the specific/associated data for that row.
I want to use a single ClickHandler for all the buttons. How can I then identify which button (and subsequently which row) has been clicked? Can I associate some sort of tag/identity value to a button (or Image) widget in GWT? With this identity/tag value, then I would be able to identify which row data I am working with.
Any clues?

A: In the handler use method getCellForEvent(ClickEvent event) of your Grid object. It will return HTMLTable.Cell object which has both row and column index. You pass the event object that has been delivered to the handler method. It works even if you have embed widgets in the cell and you get the click event for that widget.
Actually the method is defined in base HTMLTable, so you can use it also in FlexTable.


text:
Q: Unable to execute java jar from another java file I have an eclipse plugin project and I need to execute and external jar from the project. The jar file is in the src folder of my project. Can some one help me how to execute the jar from within the project? This is the code I have
startJar.java:
    ProcessBuilder pb = new ProcessBuilder("java", "-jar","MyJar.jar");
    pb.start();

It doesn't work.startJar.java and MyJAr.jar are in the same folder. Help?

A: There is a problem it is in src folder, it should be in bin folder
If you want to let it in src folder, you have to change path like this:
String path = ".."+File.separator+"bin"+File.separator+"MyJar.jar";
ProcessBuilder pb = new ProcessBuilder("java", "-jar",path);
pb.start();

It looks like this (/ or \ depends on OS):
../bin/MyJar.jar

Note: much better will be moving .jar file into bin folder


text:
Q: Where is the "purge-journal-archiving" setting? I am trying to setup incremental backups with journal archiving in MarkLogic, but I am having a hard time finding the setting "purge-journal-archiving" in the admin interface. In order to setup this up "purge-journal-archiving" needs to be set to "true". I have checked in the database's configure page and there is nothing to specify this while setting up the backup. I don't know if im missing something somewhere. Do I need to call it via the Rest API?
The documentation for this does not provide clear direction on where to change this.
Incremental Backup with Journal Archiving

Incremental backup improves restore both time and space requirements over journal archiving, but it's not an either/or decision. You can, and should, use both where appropriate. If your goal is to be able to restore to any arbitrary point in time, while minimizing potential data loss, we suggest the following:

*

*Configure a scheduled full backup at some coarse granularity (for example, weekly) and enable journal archiving

*Configure a scheduled incremental backup as some finer granularity (for example, hourly), and specify purge-journal-archiving=true.

*Set retain until backup on the database Merge Policy so that deleted fragments are retained until they have been included in an incremental backup. See Setting Merge Policy or admin:database-set-retain-until-backup for details.

A: I could not find the purge journal archiving setting in the UI. I would think it would be on the Scheduled Backups page once you've selected a database, but could not find it there.
There are a few other ways you change this setting.

*

*When creating a incremental-backup through the xquery admin API you can set the purge-journal-archive flag. see for more detail (https://docs.marklogic.com/admin:database-daily-incremental-backup).

*You can also do it as part of HTTP request to the Management API. See for more details (https://docs.marklogic.com/REST/POST/manage/v2/databases). If you have a ml-gradle project, highly recommended this, you should be able to add this to your database settings file.

*You can also manually purge the journals after doing a backup or put it as part of script using the server JavaScript code (or XQuery).  (https://docs.marklogic.com/xdmp.databaseJournalArchivePurge). You could make this part of a main module or rest extension and call it. If you are really in a pinch you could call the eval endpoint with the server side code.


text:
Q: Add Validation for Model creation I have a Ruby on Rails project with 3 models: User, Group and Task.
The idea is that users can be in different groups and groups can have different users, so member is a table in between connecting them.
The problem is that when doing the seeding:
puts "Creating Users"
admin_one = User.create!(email: "jose@test.io", password: "1234567")
admin_two = User.create!(email: "joe@test.io", password: "1234567")

puts "Creating Groups"
group_one = Group.create!(name: "Test Group One", description: "blablabla", admin: admin_one)
group_two = Group.create!(name: "Test Group Two", description: "blablabla", admin: admin_two)

puts "Creating Tasks"
task_one = Task.create!(name: "Task 1", user: user_one, group: group_one, assignee: admin_one)
task_two = Task.create!(name: "Task 2", user: admin_one, group: group_one, assignee: admin_one)
# Test if we can create tasks for users not part of the group
task_two = Task.create!(name: "Task 3", user: admin_one, group: group_one, assignee: admin_two)

I realized that even if admin_one is part of group_one, I can still create a Task with the assignee being admin_two (who is not related to that group at all).
Is there a way to set it so that the task assignee's group needs to be one that the user is in? Is a callback the only option or there are other ways to implement the logic?
Thanks!

A: You can use a custom validation for this:
# in task model
validate :assignee_in_correct_group

def assignee_in_correct_group
  errors.add(:group_id, 'is not the same as assignee group id') unless assignee.groups.exist?(id: group.id)
end


text:
Q: Match Exact Row Number of Nth Largest Value In Data With Duplicates One can achieve the Nth largest value in a column of data like so:
=LARGE(A1:A5, N)
But in data with multiple repeat values, one cannot MATCH the result to it's accurate position in the column.
Take the following simple example: Column A=c(3,3,3,1,2,2,1,4,3) and Column B=c(1,2,4,8,16,32,64,11,12). I want to get the value in column B matching up with say the Nth largest value in Column A. But
=INDEX(A1:B5, MATCH(LARGE(A1:A5,N), A1:A5, 0), 2) with N<4 will always return 1 instead of a mix of 1, 2, and 4 (order is not important to me so long as all appear).
Specifically looking for a way to do this without array formulas or VBA. Also want this to work in the general case, and to be able to further manipulate the results. See in the example that Column V gives the desired output, but one cannot edit further (Column W).
Example Output:

A: From your sample data it seems just sorting will work. Use SORTBY() function.
=SORTBY(T3:T7,S3:S7,-1)

A: Edit : in follow the OP's comment, formula revised to :
In V2, formula copied down :
 =INDEX(S$2:T$7,AGGREGATE(15,6,ROW(A$1:A$6)/(S$2:S$7=LARGE(S$2:S$7,ROW(A1))),SUMPRODUCT(0+(LARGE(S$2:S$7,ROW(INDIRECT("1:"&ROW(A1))))=LARGE(S$2:S$7,ROW(A1))))),2)

A: An effort to explain the solution graciously provided by @bosco_yip ...
The key to this question is to find the row number of each specific instance. Once we get the row number, we can use INDEX as we already have the range ($S$2:$T$10) and the column number (2) we want.
To get the correct row numbers, we use the AGGREGATE function (documentation here: https://exceljet.net/excel-functions/excel-aggregate-function), which takes four arguments:

*

*the operation to be performed (the 15 in the formula, which represents the function SMALL)

*how to treat certain values (the 6 in the formula, which represents ignoring error values)

*the array being looked at

*which nth value in the array to evaluate.

Since we have the first two arguments of the function, we turn our attention to generating the array, which we get with ROW($A$1:$A$9)/($S$2:$S$10=LARGE($S$2:$S$10,ROW(A1))). There are two clever tricks that make this solution work without strict array formulas -- changing the array that the function looks at for each row, and utilizing formulas that spill over data to create the array.
The first part of the formula is given by =($S$2:$S$10=LARGE($S$2:$S$10,ROW(A1)))
For each row, this creates a True/False Array that looks like the below. Notice row i generates an array whose value is true wherever the ith largest value in the range is met.

We would like to take this a step further and instead have each array display the row number where the ith largest value in the range is. To do so, we simply divide another range of numbers 1:9 by the prior array since "TRUE" is crudely evaluated as 1 and "FALSE" as 0. This gives us the following array for each row (recall we exclude errors in the AGGREGATE function with a second of "6").

We now have the array for each row and turn our attention to the last argument of the AGGREGATE function. If the jth greatest number in our original data is repeated k times, then we need k separate arguments for each array. We get these separate arguments by using the below formula:
SUMPRODUCT(0+LARGE($S$2:$S$10,ROW(INDIRECT("1:"&ROW(A1))))=LARGE($S$2:$S$10,ROW(A1))))
The first part of this formula, LARGE($S$2:$S$10,ROW(INDIRECT("1:"&ROW(A1)))) generates an array that simply lists the elements in our original data from greatest to least up to the first i items for row i. As an example, the array generated for row 6 would be c(4,3,3,3,3,2).
Each ith array is then tested against the ith largest value in the original data to generate a TRUE/FALSE array as shown below.

Finally, we use SUMPRODUCT on the array (SUMPRODUCT of a single array is the same as adding the array) to count the number of entries that are true (note that SUM or SUMIF or COUNTIF will not work). So the ending value of the AGGREGATE function is shown below (different colors represent different values in the original data) next to the results of the entire function

A: I would like to suggest two array (CSE) formula which gets desire result.

How it works:

*

*Without an array (CSE) formula it's not possible, since the formula needs to read each largest elements from column K while skip duplicates to pair the correct value from column L, eventually are same value.

*An array (CSE) Formula in cell S2:
{=IF(ROW(A1)<=3,INDEX($K$2:$L$7,MATCH(LARGE($K$2:$K$7-ROW($K$2:$K$7)/10^3,ROWS($2:2)),$K$2:$K$7-ROW($K$2:$K$7)/10^3,0),2),"")}

*Array (CSE) formula in cell T2:
{=IF(ROW(A1)<=3,INDEX($K$2:$L$7,MATCH(LARGE(INDEX($K$2:$K$7+(ROWS($K$2:$K$7)-ROW($K$2:$K$7))/10^3,0),ROWS($2:2)),INDEX($K$2:$K$7+(ROWS($K$2:$K$7)-ROW($K$2:$K$7))/10^3,0),0),2),"")}

*Finish formula with Ctrl+Shift+Enter.

*Adjust cell references in the formula as needed.


text:
Q: PHP: feof miss last word the problem is simple but complicated at the same time.
feof doesn't print my last word. It take from file name city and code (Venice,A908) and should show in OUTPUT: nameCity,codeOfCity.
Let me show you an example:
City.csv
Abano Terme,A001
Abbadia Cerreto,A004
Abbadia Lariana,A005
Abbiategrasso,A010
Zubiena,M196
Zuccarello,M197
Zuclo,M198
Zungri,M204

Code:
<?php
$buffer = "";
$file = fopen("City.csv", "r");

//while (($c = fgetc($file)) != EOF )
//while (($c = fgetc($file)) != NULL )
//while (($c = fgetc($file)) !== false )
while(!feof($file))
{
    $c = fgetc($file);
    $buffer .= $c;

    if($c == ",")
    {
        echo $buffer;
        $buffer = "";
    }

    if($c == "\n")
    {
        echo $buffer."
";

        $buffer = "";
    }
}

fclose($file);
?>

OUTPUT:
Abano Terme,A001
Abbadia Cerreto,A004
Abbadia Lariana,A005
Abbiategrasso,A010
Zubiena,M196
Zuccarello,M197
Zuclo,M198
Zungri,

A: Since it seems like you are just trying to output the file as is, with only change being to substitute HTML line breaks
 instead of new line characters why not simplify things?
echo nl2br(file_get_contents('City.csv'), true);

Or if you don't want to read the whole file into memory:
$file = fopen('City.csv', 'r');
while(!feof($file)) {
    echo nl2br(fgets($file), true);
}
fclose($file);

In one of the comments above you mention that you want the city and city values available as variables (though your code example doesn't seem to indicate this).  If that is the case, try fgetcsv() like this:
$file = fopen('City.csv', 'r');
while($values = fgetcsv($file)) {
    $city = $values[0];
    $city_code = $values[1];
    echo $city . ',' . $city_code . '
';
}
fclose($file);

A: Your problem is, there's no newline at the end of your file, so it never hits the last "\n" check to output the buffer contents.
to fix this, you just need to put in another check on that conditional. change
if($c == "\n")

to:
if($c == "\n" || feof($file))

Here's a much cleaner and more concise version of your code if you'd like to use the correct function for parsing a csv file:
<?php
$buffer = array();
$file = fopen("City.csv", "r");
while(!feof($file) && $buffer[] = fgetcsv($file));
fclose($file);
foreach($buffer as $line){
    echo join(',', $line).'
';
}
?>


text:
Q: Missing fonts in Acrobat reader in wine I have managed to install Adobe Acrobat Reader (the only "free" PDF editor I could find) in wine. This is working, but a lot of texts are not being rendered.
I have run the following to install it (based on this guide):
winetricks mspatcha
wine path/to/installer.exe

I did fail and retry several times, so I may or may not have selected a 32-bit version.
Anyway, it works, but some fonts are missing. It is usable, but sometimes I really do miss the texts, eg in pop-up messages.
Does anyone know how to fix these fonts?

A: To ensure that you have correct links to downloads update WineTricks as recommended on its page.
wget https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks
chmod +x winetricks

And then place it in correct location
sudo cp winetricks $(which winetricks)

Then try to install all fonts with it:
winetricks allfonts

A: I just installed the latest version of Acrobat Reader DC (2019) in Wine using this guide by user filozofio here :

*

*install wine and winetricks

*execute these commands in a terminal:

*

*winetricks atmlib

*winetricks riched20

*winetricks wsh57

*winetricks mspatcha

*Get the Windows 7 fonts, especially the sego* fonts.

*

*I got them from here: https://www.w7df.com/7/download.html

*Copy the windows fonts to a folder in /usr/share/fonts

*execute this command in a terminal:

*

*sudo fc-cache -vf

*Download the Windows version of Adobe Acrobat Reader DC from https://get.adobe.com/reader/otherversions/

*Install it via wine

*

*wine /path/to/installer.exe (e.g. wine ~/Downloads/AcroRdrDC1901020064_en_US.exe

*At start up, select "always start with protected mode disabled" (not possible in wine)

*Accept the license

A: As iwilltry42 says, but his answer contains loads of jargon(I beg my pardon). For me It worked like these:
1) simply installed Adobe Acrobat from the Ubuntu store.
2) Downloaded the Windows 7 fonts from https://www.w7df.com/7/download.html
3) Extracted it and pasted it in /usr/share/fonts(pate the entire extracted folder)
Bingo !
Note:- While pasting the file open file manager in super user mode(i.e - sudo nautilus)


text:
Q: RHEL 6.6: redis-package for php54 Redhat Enterprise Linux Server 6 contains php54 packages, in addition to the normal php packages that ship version 5.3.
Unfortunately for me, a php-redis package exists, but no php54-redis package.
Do I have to compile the extension myself, or are there inofficial repositories that contain the package, or is there another way to get the redis extension for 5.4?

A: Nothing prevents you from installing redis from pecl, like pecl install redis.

A: Some packages have no version number. Like php-apc for example. Try to install it and check the dependencies.
Check the PHP-Version / Dependencies with (you need yum-utils)
repoquery --requires php-redis

There you can see on which PHP-Version is depends.


text:
Q: Proper representation for a conditional function I have a function shown in below image. But the 2nd line (the parenthesis) has something that I don't know how to formulate properly.
The equation (I was not allowed to post images directly)
1- Does this count as a piecewise function?
2- Would someone please help me to create a proper presentation?
Thanks.

A: I wouldn't try to write a one-line definition of $M_i$. That's bound to end up confusing.
Instead I might first define $d(R)$ to be the least index $i$ for which $R_i=0$, or $0$ if none of the $R_i$ are zero. Then I would write, e.g.,
$$M_i(R) = \begin{cases}F(R_i) & d(R) = 0\\1 &d(R) = i\\0 & \textrm{otherwise.}\end{cases}$$


text:
Q: How to terminate a coplanar waveguide with 50 ohm load? So I want to structure a coplanar waveguide by lithography, VNA - coaxial - picoprobe - coplanar waveguide transition to measure impedance of the waveguide. As signal and ground lines are on one surface, compared to e.g. a cpw without groundplane, one should be able to terminate the waveguide with 50 Ohm at the end on the wafer?
I found some hinted ways to do this, e.g. different stub geometries, or an antenna or resistor as terminating load. The last one I know from BNC cables, the 50 Ohm ending caps. The correct stub geometry has probably to be found by something like CST Microwave, Sonnet, HFSS? My CPW consists of 100 nm thick gold, width 15 micron, gap 10 micron, 1-2 mm length, 1-2 GHz.

To find a material able to be deposited accurately with resitivity to yield 50 Ohm for this geometrical demands seems tricky like in the upper right of the picture. The lower left is my guess but probably wrong, causing reflections because of the 90° bended ground lines before ending in the stub, so maybe a tapering like in the lower right has to be designed or an antenna-like small coil?
Is there maybe a easier solution for this on-die termination, maybe to use unbalanced or coupled lines (sorry dont know exact name, basically CPW with 1 signal and 1 ground line). Maybe this is easier to design geometrically a terminating stub/antenna/resistor at the end?

A: The issue I see if you're trying to create a matched termination, is that except for the one at upper-right, your terminations are all short circuits, not matched terminations.
Since your frequency band is exactly one octave, it's possible that you could design the length of the CPW from your probe pads to the short-circuit to be approximately 1/8 wavelength, so that the short will appear as a match when seen from your probe point. This will work well for a narrow band around, say, 1.414 GHz, and will be a very bad approximation at the edges of your band at 1 and 2 GHz. If you have space, you could make different test structures with different lengths for testing in different portions of your band.
If you can work out how to do it, the option at upper-right would create a matched termination over a much broader band, but as you say it would require very careful design to ensure it's really a broadband 50 Ohm termination. From a geometry p.o.v., I'd suggest using a symmetric structure with 100 Ohm resistance from the central trace to the ground on each side.
An option that might be even better is to build a "through" structure instead of a stub structure. Put probe pads at both ends of your transmission line, and use two probes. Then let the VNA and its 2-port calibration math work out the errors due to the slight mismatch of the probe at the far end, instead of relying on your assumed-perfect 50-Ohm load as a reference for determining the trace impedance.


text:
Q: Why are physical simulations more accurate with floating point numbers "closer to one"? I've often heard it said that any sort of "dimensional" (involving length, time, mass, charge, etc.) calculation should be put in a dimensionless form for two reasons

*

*Getting a value ~ 1e14 when all of your inputs are near 1 is rather obvious (and unlikely) making it easier to pinpoint algorithmic errors.

*Conventional IEEE floating point numbers are denser near zero so dimensionless calculations are more accurate.

I have a pretty intuitive grasp of the first point (if all my lengths ≈ 1 and my masses ≈ 1 and my times ≈ 1 then I can expect all of my forces will reasonably ≈ 1) but I'm having a more difficult time digesting the second. I totally understand why the epsilon between floats depends on your location on the real line, but I don't see how this fact can be exploited for better accuracy. For instance, if you're using the SI speed of light (c = 3e8) and add to it a small epsilon (eps = 1e-8), then c + eps == c and you've "lost" the epsilon to the floating-point void. I don't see how using a dimensionless speed of light (c = 1) diminishes this sort of issue. Why are "dimensionless" simulations said to be more accurate?

A: So over here what matters isn't as much addition exclusively as it is multiplication/scaling.
Let's consider what it means for floating-point numbers to be "more dense" near zero. The way floating-point works is... imagine the exponent to define which interval of the form [2^{n-1}, 2^n] we are working in - as you can see, as the exponent part grows, your intervals grow larger: [0.5,1], [1,2], [2,4], [4,8] and so on. However, the mantissa - the part of the number that's fixed in size (2^54 for double precision) is, well, fixed. And this number can be viewed as an offset into the interval. (What happens when your number hits the largest possible offset? Well, we reset the offset and increment our exponent by 1. Hence "floating" point, since the binary decimal point floats depending on the magnitude of the number you are trying to represent).Let's look at the interval [1,2]: what's the spacing between successive floats in it? A: (2-1)/2^54 = 2^-54. Now, what about [4096,8192]? A: (8192-4096)/2^54 = 2^-42. And so on. So by "more dense" we literally mean that we can represent smaller differences between numbers in that interval, and so improve accuracy.
Another reason is actually the reason you mentioned - that sufficiently small numbers, those less than "machine epsilon", if added to any floating-point number, will have no effect. Now, machine epsilon for double precision is smaller than you think: it turns out for any binary precision b, your machine epsilon is 2^{-b+1}, so for doubles we have 2^-53 ≈ 2.2204460492503131e-16. Now, consider the large number of physics formulae that have a factor of c^2 ≈ 8.98755179e16 in the denominator. It turns out this becomes ~1.11265e-17: so if whatever else you are multiplying by it is less than ~8, your overall expression is... < DBL_EPSILON and thus eated.
The solution to these issues is to scale intermediate expressions so they indeed land in the densest possible interval for floating-point arithmetic. The easiest way to start is... indeed, to use natural/dimensionless units! It's both physically sound and actually even makes the formulas simpler to write down, and you can always scale back from dimensionless units to dimension-ful ones at the very end if desired. So we do just that. :)


text:
Q: iOS data source delegation I've been working through the Stanford CS193p course for iOS 5.0 development (available on iTunes U) and have run into a problem whilst attempting Assignment 3 (pdf).
I am trying to implement a graphing calculator on top of a previous calculator model I have developed. In my storyboard I have added a "graph" button to my calculator which segues to a new view controller. Inside this is a view called 'GraphView'. I need to delegate the data source for this view. I can set it inside my GraphViewController like so:
self.graphView.dataSource = self;

I can also set that in Interface Builder. What I would like to do is set it to my CalculatorViewController, which first sent the segue message, but there is no mention of GraphViewController or GraphView in it's code, so I'm not sure how to accomplish this. Interface Builder would not let me drag the data source out of it's own view's frame either.
Short version: I want to delegate my data source from my Graph View to my CalculatorViewController. See the storyboard here: Storyboard.
Any help would be very greatly appreciated.

A: You can do this in the prepareForSegue function.  You can find a similar example to how this is done in PsychologistViewController.m.


text:
Q: Macros print output #include <stdio.h>

#define N 100

void f(void);

int main(void)
{
f();
#ifdef N
#undef N
#endif

return 0;
}

void f(void){
#if defined(N)
  printf("N is %d\n",N);
#else
  printf("N is undefined\n");
#endif // defined
}

Why does this output print N is undefined shouldn't it print N is 100 because of the function call on f before it reaches the undef that removes the value 100?

A: Preprocessor directives and macros are processed at a very early stage of compilation, they have no existence at runtime.
Running your code just through the preprocessor (cpp -P -- warning: remove the #include first) shows the actual C code that is being compiled.
void f(void);
int main(void)
{
f();
return 0;
}
void f(void){
  printf("N is undefined\n");
}

As to why this expansion is chosen rather than the alternate message, consider these lines in your source.
#ifdef N
#undef N
#endif

Regardless of whether it's defined or not initially, it will not be defined after these lines are (pre-)processed.


text:
Q: How to set up dnx builds on CCNet? dnu runs but fails with "dnx not found" I'm trying to set up some ASPNetv5 builds on CCNet. I added an exec block like this:
<cb:define name="DnuPackageRestore">
    <exec>
        <executable>dnu</executable>
        <cb:ifdef name="SourceFolder">
            <baseDirectory>$(SourceFolder)</baseDirectory>
        </cb:ifdef>
        <cb:else>
            <baseDirectory>$(WorkingPath)\$(ProjectName)</baseDirectory>
        </cb:else>
        <description>DNU Package Restore</description>
        <buildArgs>restore</buildArgs>
    </exec>
</cb:define>

For some strange reason, CCNet fails for .cmd files in PATH, so I changed executable from dnu to dnu.cmd. It now runs dnu fine but that immediately crashes saying it can't find dnx:
2016-03-02 14:17:19,073 [SuperThing:DEBUG] Starting process [dnu.cmd] in working directory [D:\CI\W\SuperThing] with arguments [restore]
2016-03-02 14:17:19,076 [SuperThing:DEBUG] Not setting PriorityClass on [D:\CI\W\SuperThing\dnu.cmd] to default Normal
2016-03-02 14:17:19,091 [13:DEBUG] [SuperThing dnu.cmd] '"D:\CI\W\SuperThing\dnx"' is not recognized as an internal or external command,
2016-03-02 14:17:19,091 [13:DEBUG] [SuperThing dnu.cmd] operable program or batch file.

It claims to be looking in SuperThing for dnx, but since it says the same for dnu.cmd I think that's a red herring.
If I PowerShell remote into the server as the same user, everything works fine (I installed dnvm, let it install 1.0.0-rc1-update1 and I ran dnvm set default -p).
There's seemingly something wonky with how CCNet is executing this dnu.cmd that's causing it to fail (my guess is a PATH is getting lost somewhere?).

A: In general, you can't execute ".cmd" files using standard Process.Start (not sure if CCNet does that). Instead, you need to exec cmd with arguments /c [path to cmd file]. Perhaps try that and see if it resolves the issue?


text:
Q: Linux: Comparing two files but not caring what line only content I am trying to use comm or diff Linux commands to compare to different files. Each file has a list of volume names. File A has 1500 volumes and file B has those same 1500 volumes plus another 200 with a total of 1700. I am looking for away to just find those 200 volumes. I dont care if the volumes match and are on different lines, I only want the mismatched volumes but the diff and comm command seem to only compare line by line. Does anyone know another command or a way to use the comm or diff command to find these 200 volumes?
First 5 lines of both files: (BTW there is only one volume on each line so File A has 1500 lines and File B has 1700 lines)
File A:
B00004
B00007
B00010
B00011
B00013

File B:
B00003
B00004
B00007
B00008
B00010

So I would want the command to show me B00003 and B00008 just from the first 5 lines because those volumes are not in File A

A: Try
comm -23 <( sort largerFile) <(sort smallerFile)

This assumes that your Vol name will be the first "field" in the data. If not, check man sort for ways to sort files on alternate fields (and combinations of fields).
The <( ....) construct is known as process substitution. If you're using a really old shell/unix or reduced functionality shell (dash?), process substitution may not be available. Then you'll have to sort your files before you run comm and manage what you do with the unsorted file.
Note that as comm -23 means "suppress output from 2nd file" (-2) and "suppress output from the two files in common" (-3), the remaining output is differences found in file1 that are not in file2. This is why I list largerFile  first.
IHTH

A: awk can also help.
 awk  'NR==FNR {a[$1]=$1; next}!($1 in a) {print $0}' fileA fileB


text:
Q: Why does hclust gives a different cluster than pvclust in r? I am trying to get the p-values for hierarchical clustering analysis on the following dataset.The dendrograms generated by pvclust and hclust are completely different.Because the pvclust mentioned they used the same method as hclust, it should be identical.
require(vegan)
test

  S1 S2 S3 S4 S5 S6 S7 S8 S9 S10
1  1  1  1  1  1  1  0  1  1   0
2  0  0  1  0  0  0  0  0  0   0
3  1  0  0  1  1  0  0  0  1   1
4  1  0  1  0  1  1  0  1  0   1
5  0  1  0  1  0  0  0  0  1   0
6  1  0  1  0  1  1  0  0  0   1
7  1  1  0  1  0  0  1  0  1   0
8  1  1  0  1  0  1  1  0  1   0
9  1  0  1  0  1  1  0  1  0   0

div.norm=decostand(test,"normalize")
div.ch=vegdist(div.norm,"bray")
div.ch.UPGMA=hclust(div.ch,method = "average")
plot(div.ch.UPGMA)

This generates the following dendrogram:
Cluster using hclust
Then I tried to run the same dataset using pvclust.
require(pvclust)
test.tr=t(test)
result=pvclust(test.tr, method.dist="cor", method.hclust="average", nboot=1000)
plot(result)

I get the following dendrogram which is different from the one generated by hclust. cluster using pvclust
Some suggested that I should not transpose the data. But that produces a dendrogram where the columns are clustered (I don't want that).
Any help would be greatly appreciated!

A: The pvclust implementation of hierchical clustering that you're using relies on bootstrap resampling. This introduces a degree of randomness and you could get different results between 2 runs of pvclust thus you should expect it to be precisely the same as hclust.
Moreover, you may have noticed some fairly serious warnings while running pvclust:

Bootstrap (r = 0.5)... Done.
Bootstrap (r = 0.6)... Done.
Bootstrap (r = 0.7)... Done.
Bootstrap (r = 0.8)... Done.
Bootstrap (r = 0.9)... Done.
Bootstrap (r = 1.0)... Done.
Bootstrap (r = 1.1)... Done.
Bootstrap (r = 1.2)... Done.
Bootstrap (r = 1.3)... Done.
Bootstrap (r = 1.4)... Done.
Warning messages:
1: inappropriate distance matrices are omitted in computation: r =  0.5
2: inappropriate distance matrices are omitted in computation: r =  0.6
3: inappropriate distance matrices are omitted in computation: r =  0.7
4: inappropriate distance matrices are omitted in computation: r =  0.8
5: inappropriate distance matrices are omitted in computation: r =  0.9
6: inappropriate distance matrices are omitted in computation: r =  1
7: inappropriate distance matrices are omitted in computation: r =  1.1
8: inappropriate distance matrices are omitted in computation: r =  1.2
9: inappropriate distance matrices are omitted in computation: r =  1.3
10: inappropriate distance matrices are omitted in computation: r =  1.4

As every iteration of the pvclust has an unusable distance matrix the results should be interpreted with extreme caution and this could invalidate them and change them significantly.


text:
Q: CakePHP how to create hasMany data without knowing the foreign key in one saveAll? I was hoping to create and save the associated data like what I did with belongsTo data - the associated data are created on the fly and foreign ID is also generated and saved on the fly by a single call to saveAll or saveAssocated which has transaction built-in.
But this seems not the case for data in hasMany relationship. Take User and Comment as example. Comment has user_id as the foreign key.
It seems that I cannot save User $data by using single saveAll($data) on User
Array(
    'name' => 'Jack',
    'email' => 'jack@abc.com',
    'Comment' => array(
         array(
            'title' => 'I like this article.'
         )
    )
)

I read some docs. It seems that I need to mention the user_id as the foreign key for the Comment data to create correctly.
If that's the case, since I don't have user ID until it's created, it seems that I need to code to let SAVE happen twice.
I really think that I am missing something. There should be a CAKE way for doing this.

A: This is done automatically by Cake as long as you follow the conventions and format the data accordingly. For hasMany associations, the main model data, and the associated model data, need to be set on string keys on the same level, like
array
(
    'User' => array(),
    'Comment' => array()
)

Also note that

The saveAll function is just a wrapper around the saveMany and
  saveAssociated methods. it will inspect the data and determine what
  type of save it should perform. If data is formatted in a numerical
  indexed array, saveMany will be called, otherwise saveAssociated is
  used.
This function receives the same options as the former two, and is
  generally a backwards compatible function. It is recommended using
  either saveMany or saveAssociated depending on the case.

So either will do.
Long story short, the model data needs to be separated and indexed by string keys, it's essentially the same format as a find() call would return it. That way Cake will know that it needs to save associated data, and will automatically insert the foreign key for the Comment records.
array
(
    'User' => array
    (
        'name' => 'Jack',
        'email' => 'jack@abc.com'
    ),
    'Comment' => array
    (
        array
        (
            'title' => 'I like this article.'
        )
    )
)

See also

*

*Cookook > Models > Saving Your Data > Associations: Linking Models Together > hasMany

*Cookook > Models > Saving Your Data > Model::saveMany()

*Cookook > Models > Saving Your Data > Model::saveAssociated()

*Cookook > Models > Saving Your Data > Model::saveAll()