text:
Q: Should I use public properties and private fields or public fields for data? In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:
private int myInt;
public int MyInt
{
     get { return myInt; }
     set { myInt = value }
}

My question is: how does this differ from:
public int MyInt;

and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!

A: When you create private field name and a simple public property Name that actually gets and sets the name field value
public string Name
{
   get { return name; }
}

and you use this property everywhere outside your class and some day you decide that the Name property of this class will actually refer to the lastName field (or that you want to return a string "My name: "+name), you simply change the code inside the property:
public string Name
{
   get { return lastName; //return "My name: "+name; }
}

If you were using public field name everywhere in the outside code then you would have to change name to lastName everywhere you used it.

A: Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.
Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.

A: You have to use properties in the following cases:

*

*When you need to serialize data in the property to some format.

*When you need to override properties in derived class.

*When you implement get and set methods with some logic. For example, when you implement Singleton pattern.

*When you're derived from interface, where property was declared.

*When you have specific issues related to Reflection.

A: See this article http://blog.codinghorror.com/properties-vs-public-variables/
Specifically

*

*Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.

*You can't databind against a variable.

*Changing a variable to a property is a breaking change.

A: Three reasons:

*

*You cannot override fields in subclasses like you can properties.

*You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.

*Convention. That's just the way it's done.

I'm sure there are more reasons that I'm just not thinking of.
In .Net 3.x you can use automatic properties like this:
public int Age { get; set; }

instead of the old school way with declaring your private fields yourself like this:
private int age;

public int Age
{
    get { return age; }
    set { age = value; }
}

This makes it as simple as creating a field, but without the breaking change issue (among other things).

A: It... depends?
I always use getters & setters, since they created this shortcut:
public int Foo { get; set; }
At compile time it is translated.  Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.
However public, private, protected... it's all a matter of who you want to be able to tweak the data.  We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.
protected _foo;
public Foo
{
    get { return _foo; }
} //lack of set intentional.

A: I can't believe that with 11 answers, nobody has said this:
Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.

A: There are many reasons why.
Mainly:

*

*You can do some other functions when the variable is set

*You can prevent setting and provide only get

*Some 'things' only work on properties (DataBinding, for example)

*You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).

A: The point is - what if further down the line you want to make sure that every time myInt is referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.

A: Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).
I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).
However, that's just a language limitations and apart from static/const fields I alsways use properties.

A: The idea is you should not accidentally/unintentionally change the value of a class private field outside.
When you use get and set, that means you are changing the class private field intentionally and knowingly.

A: Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value

private string _email;
public string Email
{
    get
    {
        return this._email;
    }
    set
    {
        this._email = value;
        ReplaceList(); //**
    }
}

A: In simpler words, answer to your question is the access modifiers i.e. public and private.
If you use:
public int myInt;
public int MyInt
{
     get { return myInt; }
     set { myInt = value }
}

then both MyInt property and myInt variable is available in the project to be modified.
Means, if your class suppose A is inherited by class suppose B,
then myInt and MyInt both are available for modification and no check can be applied.
Suppose you want myInt value can be set in derive class if some particular condition pass.
This can be achieved only by making field private and property to be public.
So that only property is available and conditions can be set based on that.


text:
Q: No executable file created Why isn't the newly named executable file being created? But if I delete the shift, it does create the file?
if [ "$1" = "-o" ];
then
  op="$2"
  shift 2
  gcc -o "$op" "$@" &> errors.txt
else
 shift
 echo "went to else -o not detected"
 gcc "$@" &> errors.txt
fi

A: If you pass -o to the script then the script will pass -o to gcc and therefore call the resultant file something other than "a.out". Because that's what passing -o to gcc does.

redpajama_set_name: RedPajamaStackExchange


text:
Q: как обрезать блок под карты поступил такой заказ сделать карту на основе yandex map api по макету -

карту импортировал подключил , теперь как обрезать её ?
вырезать часть карты как показано в yandex песочнице не подойдёт так как - во первых мне нужно получить москву в зуме как показано на макете , а во вторых при зуме карта не сохраняет обрезаность.
я думаю над тем что бы блоку к которому загружается карта сделать фиксированую ширину + высоту и добавить overflow:hidden , а сам блок обрезать по точкам в форме как показано на макете.
можете подсказать как это сделать ?
или у вас есть другое решения для реализации ?

A: Если правильно понял сценарий, то контур Москвы планируется сделать статичным, а карту внутрь через API Яндекс пробросить с актуальными данными.
Сразу замечу, что такой вариант Яндекс забракует не глядя и в лучшем случае просто заблочат. Ведь вы своим контуром однозначно закроете копирайты, а это недопустимо даже на коммерческих тарифах.
Потому решение - не терять время, найти подходящую карту и сделать статичную картинку с контуром и нужной инфой внутри (опять же не на подложке Яндекса при текущем ТЗ).


text:
Q: Jackson JSON mapping array to java class I want to map the following JSON:
[
  {
     "rate": {
        "id": "1",
        "value": "1"
     }
  },
  {
     "rate": {
        "id": "2",
        "value": "2"
     }
  }
]

To List<Rate> using annotations. How can I map the "rate" property to the Rate object?
Would it not be possible to annotate it like this?
@JsonClassMapping("rate") // Fictitious annotation
public class Rate {
    @JsonProperty("id")
    int id;
    @JsonProperty("value")
    int value;
}

Thse JSON is slightly different from the supposed duplicate in Jackson - How to process (deserialize) nested JSON?. I cannot get the suggested solutions to work in my case.

A: have you try somthing like this?
List myObjects = mapper.readValue(jsonInput, new TypeReference>(){});


text:
Q: How to improve Tesseract results I want to detect text in images while using OpenCV and tesseract. My steps are:

*

*To detect text I am using the scene text detection algorithm of cv::text. This actually works pretty good also under difficult circumstances

*Identified text respectively the image area containing the text is extracted from the main image

*I pass each sub-image to Tesseract

However, tesseract barely finds text and if it finds text, it is wrong. Example: (image taken from https://github.com/opencv/opencv_contrib/blob/master/modules/text/samples/scenetext01.jpg)

Green: Detected text by OpenCV (good).
Yellow: The text recognized by tesseract based on the green rectangles (bad)
Extracted text is "DOUBLEI". The 'I' is a result of the black border to the right.
As you can see the other words such as "PROHIBITED" should also be easily detected by tesseract. I tried to increase the size of the extracted sub-images containing text and used thresholding but I can not improve my results.
In various tutorials I see tesseract working under more difficult conditions so it should actually work.
When directly using "tesseract.exe" with the same image no text is detected at all:

A: Try to add a little white background. I remember that tesseract had big problems with text that reaches the borders of the image. Add 10px of white to each side and see if it helps.


text:
Q: Components are not receiving route props The docs state

All three render methods will be passed the same three route props
match location history

And they showcase it with this example
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

// All route props (match, location and history) are available to User
function User(props) {
  return
Hello {props.match.params.username}!
;
}

ReactDOM.render(
  <Router>
    <Route path="/user/:username" component={User} />
  </Router>,
  node
);

Seems easy enough.
But then I try it with my code and that's not working.
import * as React from 'react';
import { Switch, Route, BrowserRouter, Redirect } from 'react-router-dom';
import { isFalsy, readFromStorage } from 'utils/general.utils';

import { Homepage } from './pages/homepage/Loadable';
import { Header } from './global/components';
import { Register } from './pages/auth/register/Loadable';
import { Login } from './pages/auth/login/Loadable';
import { ACCESS_TOKEN } from 'constants/storage.constants';

const PrivateRoute = ({ children, ...rest }) => {
  const accessToken = readFromStorage(ACCESS_TOKEN);
  return (
    <Route
      {...rest}
      render={({ location }) =>
        !isFalsy(accessToken) ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: location },
            }}
          />
        )
      }
    />
  );
};

export function App(props) {
  const routes = [
    {
      path: ['/'],
      component: Homepage,
      exact: true,
      private: false,
    },
    {
      path: ['/register'],
      component: Register,
      private: false,
    },
    {
      path: ['/login'],
      component: Login,
      private: false,
    },
  ];

  return (
    <BrowserRouter>

      <Switch>
        {routes.map(route => {
          const Component = route.component;
          const RouteWrapper = route.private ? PrivateRoute : Route;
          return (
            <RouteWrapper
              key={route.path[0]}
              path={route.path}
              exact={route.exact}
            >
              <Component {...props} />
            </RouteWrapper>
          );
        })}
      </Switch>
    </BrowserRouter>
  );
}

And yes I am wrapping my App in ReactDom likeso
ReactDOM.render(
  <Provider store={store}>
    <HelmetProvider>
      <React.StrictMode>
        <App />
      </React.StrictMode>
    </HelmetProvider>
  </Provider>,
  ROOT,
);

But the Register, Login and Home component don't have the props of the route. What am I doing wrong here?
I am using v5.2.0

A: Issue
You simply are not passing the route props on through to the rendered components since you are always rendering children components as wrapped children and not on one of render, component, or children props.
const PrivateRoute = ({ children, ...rest }) => {
  const accessToken = readFromStorage(ACCESS_TOKEN);
  return (
    <Route
      {...rest}
      render={({ location }) =>
        !isFalsy(accessToken) ? (
          children // <-- Just renders children, passes no props
        ) : (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: location },
            }}
          />
        )
      }
    />
  );
};

And you pass along the props that were passed to App
export function App(props) { // <-- props
  const routes = [....];

  return (
    <BrowserRouter>

      <Switch>
        {routes.map(route => {
          const Component = route.component;
          const RouteWrapper = route.private ? PrivateRoute : Route;
          return (
            <RouteWrapper
              key={route.path[0]}
              path={route.path}
              exact={route.exact}
            >
              <Component {...props} /> // <-- spread here, no route props
            </RouteWrapper>
          );
        })}
      </Switch>
    </BrowserRouter>
  );
}

Solution

*

*Rewrite your PrivateRoute component to render either a Route or Redirect so the route props can be passed along.
const PrivateRoute = (props) => {
  const accessToken = readFromStorage(ACCESS_TOKEN);

  return !isFalsy(accessToken) ? (
    <Route {...props} />
  ) : (
    <Redirect
      to={{
        pathname: '/login',
        state: { from: props.location },
      }}
    />
  );
};

*Pass (nearly) the entire route config object to the wrapper. Here you will be spreading path, exact, component (or render, etc) into either a Route or PrivateRoute which will pass on the route props.
<Switch>
  {routes.map(({ private: isPrivate, ...props }) => {
    const RouteWrapper = isPrivate ? PrivateRoute : Route;
    return (
      <RouteWrapper
        key={props.path[0]}
        {...props}
      />
    );
  })}
</Switch>

Demo


text:
Q: Converting Issue date with download to CSV I have a problem with the Function Module "GUI_DOWNLOAD" because of the date converting.
I want to get the date like I have it in my internal table but CSV (Excel) keeps converting it everytime.
The internal table contains the line like this: 12345678;GroupDate;2021-12-31;
The Output in the .csv-File should be "2021-12-31" but it keeps converting to "31.12.2021".
I also tried to put an ' (apostroph) before the date but the output will be '2021-12-31
Does anybode have an Idea ?
      lv_conv = '2021-12-31'.
  CONCATENATE TEXT-001 LV_CONV INTO LV_CONV.

    CALL FUNCTION 'GUI_DOWNLOAD'
  EXPORTING
    FILENAME = IV_PATH
  TABLES
    DATA_TAB = LT_FILE.

LT_FILE is a string table.
Thanks for the help.

A: Like Suncatcher and Sandra said the file is right but it is only the settings from excel which convert the date.
If the Output file won´t be needed for other purposes than showing the code could be something like this
CONCATENATE '=("' LV_CONV '")' INTO LV_CONV.

The csv-Output would be a date like this 1960-01-01 but in the cell the value would look like =("1960-01-01").


text:
Q: How to find request param in nginx reverse proxy Regarding nginx reverse proxy I am struggling to get the parameters values from the request URL in NGINX conf.d
My URL is https://abcd.cloudfront.net/app/dashboards#/view/aa501030-e93e-11eb-bdcf-531cdb7c714a?param1="somecryptedvalue=="
here aa501030-e93e-11eb-bdcf-531cdb7c714a in URL is the dynamic part.
I just need the value of param1.
the below code worked fine for me if URL is just https://abcd.cloudfront.net?param1="somecryptedvalue=="
if ($args ~ "^url=(.+)") { #gets the "url" get parameter
set $key1 $1;
}


text:
Q: Issue with paging when deleting object when using DeletObject (Entity Framework) I'm having an issue with paging when I delete an object using the DeleteObject method (Entity Framework). The deletion works fine, as it is supposed to, but the page number is updated to the next page. I mean, if I'm deleting a record that is on page 3 of my search results, after the deletion is completed, the page number is updated to "page 4", even though the search results still correspond to page 3!
I have checked everything I could think of, but I can't figure out what is wrong. Has anyone had this problem before? (I'm pretty new to MVC, Razor, etc).
Thank you!

A: Thanks for the reply, Gert Arnold and Moeri; I posted in a hurry going to a meeting and didn't add enough details.
As I went to grab the code to post here, I found the solution:
function DeleteRecord(SubscriptionID){
  var URL = "@Url.Content("~")PubSub/DeleteSubscriber/" + SubscriptionID;

  if(confirm("Are sure you want to delete this record?")){
  $.get(URL, function (data) {
    if(data=="True")
    {
        $("#SubscriptionContainer"+SubscriptionID).show();
        $("#Subscription"+SubscriptionID).html("Delete Successful! Refreshing list please wait........");
         window.setTimeout(function () {
              GetPage($("#PageNumber").val() - 1); //Adding the "- 1" solved the issue
           }, 2000);
    }
    });
    }
}

To fix the code all I did was replacing GetPage($("#PageNumber").val(), with GetPage($("#PageNumber").val() - 1);


text:
Q: PHP match string in array, modify string and then create new array I'm not sure how to better phrase my question, but here is my situation.
I have an array like the following:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");

I need to loop through this array and try to match the first portion of each string in the array
e.g.
$id          = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
     fetch this string
     append "999888" to "122874|876394|120972"
     insert this string back to array
}

So the resulting array becomes:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");

Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.
Thanks

A: crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr
    $temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");

    $id = "222222";
    $rand_number = "999888";

    foreach($temp_array as $t){
        if(substr(0,6,$t)==$id){
            $new[] = $t.'|'.$rand_number;
        }else{
            $new[] = $t;
        }
    }

A: You could also using some exploding in this case too:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
                    // ^ reference
    $pieces = explode('|', $line); // explode pipes
    $first = explode('-', array_shift($pieces)); // get the first part, explode by dash
    if($first[0] == $id) { // if first part is equal to id
        $first[2] = $rand_number; // replace the third part with random
        $first = implode('-', $first); // glue them by dash again
        $line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
    }
}
echo '<pre>';
print_r($temp_array);

A: Try this:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id          = "222222";
$rand_number = "999888";

// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){

    // Get the first characters of the element up to the occurrence of a dash "-" ...
    $num = substr($arr, 0, strpos($arr, '-'));

    // ...and check if it is equal to $id...
    if ($num == $id){
        // ...if so, add $random_number to the back of the current array element
        $temp_array[$i] .= '|'  . $rand_number;
    }
}

Output:
Array
(
    [0] => 111111-Name1-122874|876394|120972
    [1] => 222222-Name2-122874|876394|120972|999888
    [2] => 333333-Name3-122874|876394|120972
)

See demo
Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.

http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php

A: Another version using array_walk
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");

$id          = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
    $parts = explode('-', $value); // Split parts with '-' so the first part is id
    if ($parts[0] == $param['id']){
        $parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
        $value=implode('-',$parts); //combine the parts back
    }
},$params);

print_r($temp_array);

If you just want to append The code becomes much shorter
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
    // here check if the first part of the result of explode is ID
    // then append the rand_number to the value else append '' to it.
    $value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);

Edit: Comments added to code.


text:
Q: Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter? I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1.  Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.
I have the character mapping so I'm interested in the technical aspects.
This is my approach so far:
# char mapping lookup table
EBCDIC_TO_LATIN1 = {
  0xC1:'41', # A
  0xC2:'42', # B
  # and so on...
}

BUFFER_SIZE = 1024 * 64
ebd_file = file(sys.argv[1], 'rb')
latin1_file = file(sys.argv[2], 'wb')

  buffer = ebd_file.read(BUFFER_SIZE)
  while buffer:
    latin1_file.write(ebd2latin1(buffer))
    buffer = ebd_file.read(BUFFER_SIZE)

ebd_file.close()
latin1_file.close()

This is the function that does the converting:
def ebd2latin1(ebcdic):

   result = []
   for ch in ebcdic:
     result.append(EBCDIC_TO_LATIN1[ord(ch)])

   return ''.join(result).decode('hex')

The question is whether or not this is a sensible approach from an engineering standpoint.  Does it have some serious design issues? Is the buffer size OK? And so on...
As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format.  The patent office has been using EBCDIC until they switched to Unicode in 2005.  So there are thousands of documents within each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.
Also:
$ recode IBM500/CR-LF..Latin1 file.ebc
recode: file.ebc failed: Ambiguous output in step `CR-LF..data'

Thanks for the help so far.

A: EBCDIC 500, aka Code Page 500, is amongst Pythons encodings, although you link to cp1047, which doesn't. Which one are you using, really? Anyway this works for cp500 (or any other encoding that you have).
from __future__ import with_statement
import sys
from contextlib import nested

BUFFER_SIZE = 16384
with nested(open(sys.argv[1], 'rb'), open(sys.argv[2], 'wb')) as (infile, outfile):

    while True:
        buffer = infile.read(BUFFER_SIZE)
        if not buffer:
            break
        outfile.write(buffer.decode('cp500').encode('latin1'))

This way you shouldn't need to keep track of the mappings yourself.

A: If you set up the table correctly, then you just need to do:
translated_chars = ebcdic.translate(EBCDIC_TO_LATIN1)

where ebcdic contains EBCDIC characters and EBCDIC_TO_LATIN1 is a 256-char string which maps each EBCDIC character to its Latin-1 equivalent. The characters in EBCDIC_TO_LATIN1 are the actual binary values rather than their hex representations. For example, if you are using code page 500, the first 16 bytes of EBCDIC_TO_LATIN1 would be
'\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F'

using this reference.

A: While this might not help the original poster anymore, some time ago I released a package for Python 2.6+ and 3.2+ that adds most of the western 8 bit mainframe codecs including CP1047 (French) and CP1141 (German): https://pypi.python.org/pypi/ebcdic. Simply import ebcdic to add the codecs and then use open(..., encoding='cp1047') to read or write files.

A: Answer 1:
Yet another silly question: What gave you the impression that recode produced only ASCII as output? AFAICT it will transcode ANY of its repertoire of charsets to ANY of its repertoire, AND its repertoire includes IBM cp500 and cp1047, and OF COURSE latin1. Reading the comments, you will note that Lennaert and I have discovered that there aren't any "proprietary" codes in those two IBM character sets. So you may well be able to use recode after all, once you are certain what charset you've actually got.
Answer 2:
If you really need/want to transcode IBM cp1047 via Python, you might like to firstly get the mapping from an authoritative source, processing it via script with some checks:
URL = "http://source.icu-project.org/repos/icu/data/trunk/charset/data/ucm/glibc-IBM1047-2.1.2.ucm"
"""
Sample lines:
<U0000>  \x00 |0
<U0001>  \x01 |0
<U0002>  \x02 |0
<U0003>  \x03 |0
<U0004>  \x37 |0
<U0005>  \x2D |0
"""
import urllib, re
text = urllib.urlopen(URL).read()
regex = r"<U([0-9a-fA-F]{4,4})>\s+\\x([0-9a-fA-F]{2,2})\s"
results = re.findall(regex, text)
wlist = [None] * 256
for result in results:
    unum, inum = [int(x, 16) for x in result]
    assert wlist[inum] is None
    assert 0 <= unum <= 255
    wlist[inum] = chr(unum)
assert not any(x is None for x in wlist)
print repr(''.join(wlist))

Then carefully copy/paste the output into your transcoding script for use with Vinay's buffer.translate(the_mapping) idea, with a buffer size perhaps a bit larger than 16KB and certainly a bit smaller than 2GB :-)

A: No crystal ball, no info from OP, so had a bit of a rummage in the EPO website. Found freely downloadable weekly patent info files, still available in cp500/SGML even though website says this to be replaced by utf8/XML in 2006 :-). Got the 2009 week 27 file. Is a zip containing 2 files s350927[ab].bin. "bin" means "not XML". Got the spec! Looks possible  that "proprietary codes" are actually BINARY fields. Each record has a fixed 252-byte header. First 5 bytes are record length in EBCDIC e.g. hex F0F2F2F0F8 -> 2208 bytes. Last 2 bytes of the fixed header are the BINARY length (redundant) of the following variable part. In the middle are several text fields, two 2-byte binary fields, and one 4-byte binary field. The binary fields are serial numbers within groups, but all I saw are 1. The variable part is SGML.
Example (last record from s350927b.bin):
Record number: 7266
pprint of header text and binary slices:
['EPB102055619         TXT00000001',
 1,
 '        20090701200927 08013627.8     EP20090528NN    ',
 1,
 1,
 '                                     T *lots of spaces snipped*']
Edited version of the rather long SGML:
<PATDOC FILE="08013627.8" CY=EP DNUM=2055619 KIND=B1 DATE=20090701 STATUS=N>
*snip*
<B541>DE<B542>Windschutzeinheit für ein Motorrad
<B541>EN<B542>Windshield unit for saddle-ride type vehicle
<B541>FR<B542>Unité pare-brise pour motocyclette</B540>
*snip*
</PATDOC>

There are no header or trailer records, just this one record format.
So: if the OP's annual files are anything like this, we might be able to help him out.
Update: Above was the "2 a.m. in my timezone" version. Here's a bit more info:
OP said: "at the beginning of each file there are a few digits in ASCII that tell you about the length of the file." ... translate that to "at the beginning of each record there are five digits in EBCDIC that tell you exactly the length of the record" and we have a (very fuzzy) match!
Here is the URL of the documentation page: http://docs.epoline.org/ebd/info.htm
The FIRST file mentioned is the spec.
Here is the URL of the download-weekly-data page: http://ebd2.epoline.org/jsp/ebdst35.jsp
An observation: The data that I looked at is in the ST.35 series. There is also available for download ST.32 which appears to be a parallel version containing only the SGML content (in "reduced cp437/850", one tag per line). This indicates that the fields in the fixed-length header of the ST.35 records may not be very interesting, and can thus be skipped over, which would greatly simplify the transcoding task.
For what it's worth, here is my (investigatory, written after midnight) code:
[Update 2: tidied up the code a little; no functionality changes]
from pprint import pprint as pp
import sys
from struct import unpack

HDRSZ = 252

T = '>s' # text
H = '>H' # binary 2 bytes
I = '>I' # binary 4 bytes
hdr_defn = [
    6, T,
    38, H,
    40, T,
    94, I,
    98, H,
    100, T,
    251, H, # length of following SGML text
    HDRSZ + 1
    ]
# above positions as per spec, reduce to allow for counting from 1
for i in xrange(0, len(hdr_defn), 2):
    hdr_defn[i] -= 1

def records(fname, output_encoding='latin1', debug=False):
    xlator=''.join(chr(i).decode('cp500').encode(output_encoding, 'replace') for i in range(256))
    # print repr(xlator)
    def xlate(ebcdic):
        return ebcdic.translate(xlator)
        # return ebcdic.decode('cp500') # use this if unicode output desired
    f = open(fname, 'rb')
    recnum = -1
    while True:
        # get header
        buff = f.read(HDRSZ)
        if not buff:
            return # EOF
        recnum += 1
        if debug: print "\nrecnum", recnum
        assert len(buff) == HDRSZ
        recsz = int(xlate(buff[:5]))
        if debug: print "recsz", recsz
        # split remainder of header into text and binary pieces
        fields = []
        for i in xrange(0, len(hdr_defn) - 2, 2):
            ty = hdr_defn[i + 1]
            piece = buff[hdr_defn[i]:hdr_defn[i+2]]
            if ty == T:
                fields.append(xlate(piece))
            else:
                fields.append(unpack(ty, piece)[0])
        if debug: pp(fields)
        sgmlsz = fields.pop()
        if debug: print "sgmlsz: %d; expected: %d - %d = %d" % (sgmlsz, recsz, HDRSZ, recsz - HDRSZ)
        assert sgmlsz == recsz - HDRSZ
        # get sgml part
        sgml = f.read(sgmlsz)
        assert len(sgml) == sgmlsz
        sgml = xlate(sgml)
        if debug: print "sgml", sgml
        yield recnum, fields, sgml

if __name__ == "__main__":
    maxrecs = int(sys.argv[1]) # dumping out the last `maxrecs` records in the file
    fname = sys.argv[2]
    keep = [None] * maxrecs
    for recnum, fields, sgml in records(fname):
        # do something useful here
        keep[recnum % maxrecs] = (recnum, fields, sgml)
    keep.sort()
    for k in keep:
        if k:
            recnum, fields, sgml = k
            print
            print recnum
            pp(fields)
            print sgml

A: Assuming cp500 contains all of your "additional propietary characters", a more concise version based on Lennart's answer using the codecs module:
import sys, codecs
BUFFER_SIZE = 64*1024

ebd_file = codecs.open(sys.argv[1], 'r', 'cp500')
latin1_file = codecs.open(sys.argv[2], 'w', 'latin1')

buffer = ebd_file.read(BUFFER_SIZE)
while buffer:
    latin1_file.write(buffer)
    buffer = ebd_file.read(BUFFER_SIZE)

ebd_file.close()
latin1_file.close()


text:
Q: PowerShell storing Get-Content into variable returns no data I have a very simple script that grabs the content from an XML file and returns it but is not working:
$DataFile = Get-ChildItem \\$Server\C$\ *.data -Name
[xml]$DataFileContent = Get-Content Microsoft.PowerShell.Core\FileSystem::\\$Server\C$\$DataFile
Write-Host $DataFileContent

This script is not returning any data on the Write-Host, but the following is returning the correct data:
$DataFile = Get-ChildItem \\$Server\C$\ *.data -Name
Get-Content Microsoft.PowerShell.Core\FileSystem::\\$Server\C$\$DataFile

Yes, the file is an xml file and the file exists. I'm sure I am missing something, but not sure what it is. Any help will be appreciated

A: You cannot use Write-Host here since you're trying to display an [xml] object. Try write-output instead.
If you require Write-Host, you would need to represent the object as a string beforehand or use a property that outputs a string. For example:
[xml]$x = Get-Content y.xml
Write-Host $x.InnerXml

This may be a good idea to use with write-output, as well.

A: First things first: Write-Host has few legitimate uses in general - do not use it to output data: Write-Host's output goes straight to the console and can therefore neither be sent through the pipeline, nor captured, nor redirected (loosely speaking; for the full story, see the last section of this answer of mine).
If your intent is to print a friendly representation of an object for display only, use Out-Host rather than Write-Host, because the latter does not apply PowerShell's usual, friendly output formatting.
$DataFileContent | Out-Host # print object *for display only*

If your intent is to output data, you can rely on PowerShell's implicit output behavior, which sends any output that is not explicitly captured or redirected to the success output stream, which by default prints to the console using friendly formatting:
$DataFileContent # same as: Write-Output $DataFileContent

Explicit use of Write-Output is rarely needed. A notable exception is if you want to output a collection as a single object, using -NoEnumerate.
Note: Instances of [xml] happen to have only semi-friendly default output formatting that provides no insight into the document structure; to see the latter, access the .OuterXml property, though you may additionally want to apply pretty-printing, which requires more work.

Write-Host output differs from Out-Host and implicit / Write-Output output that prints to the console as follows:

*

*Instead of applying PowerShell's default output formatting, Write-Host essentially calls the .ToString() method on its input, which results in different, often near-useless representations - with the notable exception of string input.

*Additionally, Write-Host enumerates the input objects, if applicable,  so that a given input object's elements are individually stringified.
An input object is considered enumerable if it implements the [System.Collections.IEnumerable] interface.
This enumeration happens recursively, which in the case of [xml] instances results in output that is not only useless, but also confusing - see below.
[xml] instances, which represent XML documents, are enumerable, and so are their enumerated elements (XML nodes), recursively.
Write-Host recursively enumerates the top-level nodes of the document - which is either the root element alone, or, additionally, if present, the XML declaration - and invariably hits one or more leaf nodes, whose enumeration is invariably empty and yields the empty string.
Given that Write-Host separates the stringification of its (enumerated) input objects with a space each, you either get the empty string or one or more spaces as the overall output.


text:
Q: Double quotes in c# doesn't allow multiline e.g.
string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";

I need to make it as for readability:
 string str = "
 {
   \"aps\":
         {
             \"alert\":\"" + title + "" + message + "\"
         }
 }";

How to achieve this, please suggest.

A: You could use what X-Tech has said, use additional concatenation operators ('+') on every line, or use the symbol '@':
 string str = @"
         {
           'aps':
                 {
                     'alert':'" + title + "" + message + @"'
                 }
         }";

Since its a JSON, you can use single quotes instead of double quotes.
About '@': Multiline String Literal in C#

A: If you really need to do this in a string literal, I'd use a verbatim string literal (the @ prefix). In verbatim string literals you need to use "" to represent a double quote. I'd suggest using interpolated string literals too, to make the embedding of title and message cleaner. That does mean you need to double the {{ and }} though. So you'd have:
string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
   ""aps"":
   {{
       ""alert"":""{title}{message}""
   }}
}}";
Console.WriteLine(str);

Output:
{
   "aps":
   {
       "alert":"This is the title: (Message)"
   }
}

However, this is still more fragile than simply building up JSON using a JSON API - if the title or message contain quotes for example, you'll end up with invalid JSON. I'd just use Json.NET, for example:
string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
    ["aps"] = new JObject
    {
        ["alert"] = title + message
    }
};
Console.WriteLine(json.ToString());

That's much cleaner IMO, as well as being more robust.


text:
Q: Why Netbeans clears line after carriage return? public class Test {
    public static void main(String[] args) {
        System.out.println("Hii people\rBye");
    }
}

The output of the above Java program should be Bye people. But it gives the output as Bye in the NetBeans. What is the reason for that?

A: https://en.m.wikipedia.org/wiki/Carriage_Return#Computers. This might help. Carriage returns is represented differently on different platforms
 Although, the carriage return should actually mean returning the caret to the beginning of the line. It is represented differently on different platforms. It is commonly represented with a new line. Since it's the new line character for Mac. It also sometimes represented as just whitespace.


text:
Q: Android keyboard change enter key How can I change EditText keyboard enter key like this ?

A: Try using android:imeOptions with your EditText in your layout file:
android:imeOptions="actionGo"

A: The solution for me was adding these two lines in the XML of Edittext
android:imeOptions="actionDone"
android:inputType="text"

Thx everyone.

A: Android have  "android:imeOptions"  to specify the keyboard action button
1. android:imeOptions="actionGo"
2. android:imeOptions="actionDone"
3. android:imeOptions="actionNext"
4. android:imeOptions="actionPrevious"
5. android:imeOptions="actionSend"

...and more,
you can use based on requirement

A: use this in your xml where you have define your edittext android:imeOptions="actionDone"


text:
Q: VHDL/Verilog: access HDMI port I just got a new board.
http://www.digilentinc.com/Products/Detail.cfm?NavPath=2,400,836&Prod=ATLYS
As you can see, I have two HDMI inputs and two HDMI outputs on the board.
What I want to do is take one HDMI input and perform some transforms on the 1080p signal. Specifically, I want to make the pixels in the centre of the screen slightly less bright and the pixels at the edge of the screen much brighter. This new signal is then output onto one of the HDMI output ports.
I don't really know how to go about this - I am very new to FPGA design.
Do I need to get some IP, or can I do this myself using standard tools? I have the Xilinx ISE webpack.
Any insight greatly appreciated,

A: There are generally two options for you:
1) You could go ahead and implement your own HDMI receiver/transmitter modules in an HDL of your choice. But for your purpose this seems to be too time consuming and too much overkill, because all you want to do is "change some pixel values".
I also would not recommend this to a beginner in the field of HDL/FPGA.
The HDMI specification is also not available for free as far as I know, so this is probably not the cheapest solution.
2) Use an existing IP core. Have you checked out the "Support Documents" at the bottom of the digilent page(link in your question)?
There seems to exist a reference design which "
accepts an HDMI input, buffers the input frames into memory, and then outputs the buffer to another HDMI port."
If you have the necessary license to use the EDK(Embedded Development Kit) this reference design should contain exactly what you are looking for.
But even if you want a pure HDL solution, a look at the HDL source files coming with the EDK solution can't hurt.
A full license for the EDK also costs, but you can get a free 30 day evaluation license from Xilinx.
Finally there are a lot of free IP cores available on the internet, e.g. on OpenCores.org.
edit: I just found this Xilinx forum entry Understanding DVI/HDMI and Atlys possibly covering some of the issues you are facing/goind to face.


text:
Q: Mozilla translates  as  Our CMS outputs linebreaks as

 (stupid, i know, but syntactically corrent(?))
This translates to

 in chrome and IE10 and to

 in Firefox.
All browsers shows it as two linebreaks.
Why are not

 translated like
 or just
, is there something i can do
to make browser interpret

 as just one linebreak?

A: It's defined by the HTML5 specifications: http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody (search the text An end tag whose tag name is "br" in the page).
If your document is parsed as an HTML document, each closing br tag will be always parsed as if it was an opening tag (and creates an element with no content). But if you parse your document as an XHTML document a

 sequence will produce the same DOM tree as the
 tag. To have your document parsed as an XHTML document, you have to send it with the application/xhtml+xml mime type.
More details are available in the specifications: http://www.w3.org/TR/html5/introduction.html#html-vs-xhtml; http://www.w3.org/TR/html5/the-xhtml-syntax.html.

A: To answer your question... seeing as your CMS seems to output this abomination, if you need a quick fix...
Fiddle - http://jsfiddle.net/P6bDp/
Bonus CSS selector list - http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/
CSS
br + br {display: none;}

This will eliminate the second
 and leave a single line break. Fix that CMS though :)

A: hey

 is not syntactically correct, you must use it as
 (look at the slash). its inline element so no need to close like other elements. it closes itself


text:
Q: What is the limit on number of columns in Oracle 10G and Derby Databases Until recently I thought limit on number of columns in Oracle DB was 255. But turns out the limit is 1000. Can someone confirm this?
Also I was trying to find if there is any similar limit on number of columns in Derby DB, particularly embedded derby java DB

A: Here's link to Oracle documentation: Logical Database Limits.
Excerpt:
Per table                           1000 columns maximum
Per index (or clustered index)        32 columns maximum
Per bitmapped index                   30 columns maximum

Here's link to Derby documentation: A Derby Database
Excerpt:
columns per table   1,012


text:
Q: Show a hierarchy of posts with a query I'm building a simple thread/discussion mechanism, but I'm having a hard time to create a query that will retrieve my posts like a tree/hierarchy of posts.
I have a POSTS table with the following attributes (simplified): id, text, username, type, replytoid
type: 'THREAD START' or 'REPLY'
replytoid: The comment is replying another comment, so I store here the 'parent' id. The 'THREAD START' has a NULL replytoid.
My test data is: (fiddle)
| ID |             TEXT | USERNAME |                 TYPE | REPLYTOID |
|----|------------------|----------|----------------------|-----------|
|  1 | My name is Alice |    Alice | THREAD START         |    (null) |
|  2 |  Reply to @Alice |      Bob | REPLY                |         1 |
|  3 |    Reply to @Bob |    Carol | REPLY                |         2 |
|  4 |  Reply to @Carol |     Dave | REPLY                |         3 |
|  5 |  Reply to @Alice |      Eve | REPLY                |         1 |
|  6 | My name is Frank |    Frank | THREAD START         |    (null) |
|  7 |  Reply to @Frank |     Gina | REPLY                |         6 |

I've tried many kinds of JOINs, but I can't achieve my expected output, that is:
| ID |             TEXT | USERNAME |            TYPE | REPLYTOID | LEVEL | THREADID |
|----|------------------|----------|-----------------|-----------|-------|----------|
|  1 | My name is Alice |    Alice | THREAD START    |    (null) |     1 |        1 |
|  2 |  Reply to @Alice |      Bob | REPLY           |         1 |     2 |        1 |
|  5 |  Reply to @Alice |      Eve | REPLY           |         1 |     2 |        1 |
|  3 |    Reply to @Bob |    Carol | REPLY           |         2 |     3 |        1 |
|  4 |  Reply to @Carol |     Dave | REPLY           |         3 |     4 |        1 |
|  6 | My name is Frank |    Frank | THREAD START    |    (null) |     1 |        6 |
|  7 |  Reply to @Frank |     Gina | REPLY           |         6 |     2 |        6 |

A: This is a good example of a problem where you can use recursive CTE. Start with root posts as anchor and build up the replies linking them to parents. You can get the level by increasing the previous level and thread by preserving the parent id.
with cte as
(
  select *, 1 as level, id as thread
  from posts
  where replytoid is null

  union all

  select posts.*, cte.level + 1 as level, cte.thread
  from posts
  inner join cte on cte.id = posts.replytoid
)

select * from cte
order by thread, level

SQL Fiddle


text:
Q: Using a GPLv3 library in a freemium business model I read several related questions about the use of GPLv3 in a commercial app but they don't say anything about a freemium app. I would like to use a GPLv3 library in two apps, a free one (with limited features) and a paid one.
Basically, the free app will allow to use the library without limitations, and the paid one will include it as well as other unrelated features.
I will release the free app under GPLv3 but do I need to release the paid one under the same license?
I don't want to release the whole source code of my paid app (for obvious reasons), as the other features don't use the library in any way. It would just be more convenient for users who bought the full version to have all features in a single app instead of putting the library in a separate one.

A: If you own the copyright to all the source code, you can offer it under two different licenses.  This is called dual licensing, and is fairly common.
Edit:
If you're talking about a 3rd party library written by someone else and licensed under the GPLv3, you can't use that in a work that you're distributing and licensing in a way that's not compatible with the GPLv3.

A: From here:

If I use a piece of software that has been obtained under the GNU GPL, am I allowed to modify the original code into a new program, then distribute and sell that new program commercially?
You are allowed to sell copies of the modified program commercially, but only under the terms of the GNU GPL. Thus, for instance, you must make the source code available to the users of the program as described in the GPL, and they must be allowed to redistribute and modify it as described in the GPL.
These requirements are the condition for including the GPL-covered code you received in a program of your own.

and also:

A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all.

Combining these two statements might lead to the following conclusion:
When you sell your app, you're obliged to give all the code to any of your users who asks for it. It's bound by GPLv3 too. They would then be free to alter it as they see fit and redistribute at their leisure (or rather "as described in the GPL").

A: Please look into the Apache license.  It allows you to distribute closed-source code with Apache-licensed open-source code.
As someone else pointed out, you can distribute a work under two licenses, one a traditional copyright, and another under GPL (for years, MySQL has successfully made this their business model), but the whole work must be open-source in order to distribute it under the GPL.  That's the point of the GPL and the reason that the Apache license came into being.
If you wanted to freely distribute all the source code for your application, while at the same time preventing others from distributing closed-source code with your code, then GPL would be perfect.  There is no way to distribute a single creative work that is part GPL and part closed-source.
Kudos for using an existing license and asking this question instead of making up your own license!


text:
Q: How to get a div of such form that works in all browsers (IE10+)? I am facing an issue with the div element of such form:

Any ideas on how to get this shape? Ideally, the solution should work at least in IE10+. Thanks in advance.
Do not suggest to split images. I am aware of this. Triangles on both sides must be transparent.
BIG BIG EDIT

This is what should be avoided. Grey background should stay uncovered.

A: Something like this?

div {
  position: relative;
  width: 400px;
  display: inline-block;
  height: 200px;
}

div:before,
div:after {
  background-image: url('http://www.wired.com/wp-content/uploads/2015/05/the-simpsons.jpg');
  background-size: 400px 200px;
  background-repeat: no-repeat;
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100px;
  content: '';
}

div:before {
  -webkit-clip-path: polygon(50% 100%, 0 0, 100% 0);
  clip-path: polygon(50% 100%, 0 0, 100% 0);
  background-position: 0 0;
}

div:after {
  top: 100px;
  -webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
  background-position: 0 50%;
}

A: In order to ensure both browser compatibility AND a gradient/image background, you may find you will have to use multiple elements, as well as a pseudo element on each of the nested divs. A quick mock up can be seen below.

html {
  background: radial-gradient(red, black);
}
div.wrap {
  height: 300px;
  width: 300px;
  position: relative;
  overflow: hidden;

  margin: 50px auto;  /*demo only*/
}
div.part1,
div.part2 {
  position: absolute;
  height: 71%;
  width: 71%;
  top: 50%;
  left: 50%;
  transform: rotate(45deg);
  transform-origin: top left;
  overflow: hidden;
}
div.part1:before {
  content: "";
  position: absolute;
  top: -150px;
  left: -150px;
  height: 300px;
  width: 300px;
  background: url(http://lorempixel.com/300/300);
  background-size: 300px 300px;
  background-position: 0 -300px;
  transform: rotate(-45deg);
}
div.part2 {
  top: -50%;
}
div.part2:before {
  content: "";
  position: absolute;
  top: 0px;
  left: 0px;
  height: 300px;
  width: 300px;
  background: url(http://lorempixel.com/300/300);
  transform: rotate(-45deg);
  background-size: 300px 300px;
  background-position: 0 50px;
}

Please note the background position may require altering to ensure the final image is 'in sync' with each other.

A: Try Coloured CSS triangles, absolutely positioned to the left and right of a square to give the illusion of transparent triangles on the top and bottom.
Demo JS fiddle here

https://jsfiddle.net/32w08myL/

HTML

CSS
#square{
  width: 400px;
  height: 400px;
  background-image: url("https://unseenflirtspoetry.files.wordpress.com/2012/05/homer-excited.png");
  background-color: blue;
  background-repeat: no-repeat;
  display: block;
  float: left;
  position: relative;
}

.triangle-left{
  width: 0;
  height: 0;
  border-top: 200px solid transparent;
  border-bottom: 200px solid transparent;
  border-left: 200px solid #f3f5f6;
  position: absolute;
  top: 0; left: 0;
}

.triangle-right{
  width: 0;
    height: 0;
    border-top: 200px solid transparent;
    border-bottom: 200px solid transparent;
    border-right:200px solid #f3f5f6;
  position: absolute;
  top: 0; right: 0;
}


text:
Q: Generating PDF from xelatex Given a LaTeX file, foo.tex, that requires xelatex, one can convert it to PDF in the following two ways:

*

*Run xelatex foo (which directly generates foo.pdf)

*Run xelatex -no-pdf foo (which generates foo.xdv) followed by xdvipdfmx foo (which converts the xdv file to foo.pdf)

Do the two approaches, in effect, produce the same pdf file? Or is there some advantage to (1) (or indeed (2))?
(The context for this is that in the past I had always assumed that with a latex file that does not require xelatex it was preferable to call pdflatex rather than calling latex and converting the DVI to PDF. Indeed, in the past latexmk with the -xelatex argument would follow route (1), however newer versions follow (2), which initially concerned me, in analogy with my pdflatex comment above. Having found "latexmk with xelatex xdv mode" I suspect that (1) and (2) are essentially equivalent, but I wanted to confirm this. In particular I want to be sure the two routes are equivalent even if one is using packages such as microtype or hyperref.)

A: The approaches are identical because xetex calls xdvipdfmx unless you specify -no-pdf.
xetex is not like pdftex or luatex that have a modified back end that generates pdf, it always generates (extended) dvi but it runs xdvipdfmx at the end and deletes the intermediate files unless --no-pdf option is given.


text:
Q: Executing a different Jar file from another java program As a part of my program, I have a connections manager that receives a connection from a client, and then gives the client a port number and a password to use to connect.  A this point the manager needs to call the jar file I have to handle this connections, with a few arguments, and continue on,( ignoring what the other program is doing).
My problem has been with executing the jar file.  I've looked up similar question's and have tried using a process builder and using Runtime.exec.  I moved around the jar file, and checked it's permissions.  It just refuse to work from another java program, but works perfectly from the command line.  Here's an example of one of my test runs.
package test;

import java.io.*;

public class Main {
    public static void main (String [] args ) throws IOException, ClassNotFoundException, InterruptedException {
        Process p = Runtime.getRuntime().exec("java -jar \'/home/ryan/CytoscapeInterface.jar" +
        "\' arg1 arg2");
        //Process builder way
        /*ProcessBuilder pb = new ProcessBuilder("/home/ryan/CytoscapeInterface.jar",
           "-jar", "CytoscapeInterface.jar", "agr1", "arg2");
        pb.redirectErrorStream();
        Process p = pb.start();*/
        BufferedInputStream bis = new BufferedInputStream(p.getErrorStream());
        synchronized (p) { p.waitFor(); }
        System.out.println(p.exitValue());//its 1 for runtime, 2 for process Builder
        int read = bis.available();
        //had a loop, found out I just needed to go through once
        byte[] b = new byte [read];
        bis.read(b);
        read = bis.available();
        bis.close();
        FileOutputStream fos = new FileOutputStream (new File("/home/ryan/Desktop/FileTest.txt"));
        fos.write(b);//Writes error file
        fos.close();
    }
}

waitFor returns 1 for runtime and 2 for the builder.  The error output for runtime is "Unable to access jarfile '/home/ryan/CytoscapeInterface.jar'.  While using the builder gives a couple lines of error that had some weird characters, the first error was command not found.

A: I have suceessfully tested the scenario and I can execute the jar file with in java programme (without setting the classpath).
Can you make sure that you have added Manifest file in the jar which has Main-Class attribute.
My steps and output:

*

*Created Mainfest file with the following line: Main-Class: com.test.TestJSSJar

*Created Test Java program:

    package com.test;
public class TestJSSJar extends Object {

    public static void main(String args[]) {
        System.out.println("Hi! I'm in the jar");
        System.out.println("Arg:" + args[0]);
    }
}

3.Package the jar (moved to temp folder): jar cvfm jss.jar manifest.txt com
4.Write test program:
import java.io.BufferedInputStream;
import java.io.IOException;

public class TestJSS extends Object {

    static int i = 0;

    public static void main(String args[]) throws IOException, InterruptedException {
        System.out.println("Calling jar");
        Process p = Runtime.getRuntime().exec("java -jar /temp/jss.jar arg1 arg2");
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        synchronized (p) {
            p.waitFor();
        }
        System.out.println(p.exitValue());
        int b=0;
        while((b=bis.read()) >0){

            System.out.print((char)b);
        }
        System.out.println("");
        System.out.println("Called jar");
    }
}

5.Output
Calling jar
0
Hi! I'm in the jar
Arg:arg1

Called jar

A: Include jar in the classpath and call the main method of the Main-class of the jar from your main.
Suppose Main-class of CytoscapeInterface.jar is JarMain.class (You can look it up in META-INF of CytoscapeInterface.jar), then from your program, call it like this:
JarMain.main(new String[]{"arg1", "arg2"});

You can also call it from a new Thread so that you can continue with your program.
        new Thread(
        new Runnable() {
            public void run() {
                try {
                    JarMain.main(new String[]{"arg1", "arg2"});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


text:
Q: Correctly formatting data i have a list of strings i read from  a file, i currently convert them all to integers and then strip them from the list, i am doing this as shown below
def reading_ppm(file_name):

    f = open (file_name)
    setting = f.readline().splitlines()
    comment = f.readline().splitlines()
    size_x, size_y = f.readline().split()
    pixel_max = f.readline().splitlines()
    orig_data = f.read().split()

    return size_x,size_y,pixel_max, orig_data

data = map(int, orig_data)
data =  str(data).strip('[]')

when i write data to a new file i get:
255, 255, 255, 255, 255, 255, 255, 255, 255,

however what i want to get is
255
255
255
255
255
255
255
255
255
255
255
255
255
255

how can i quickly turn my long string, into ints that appear on a new line rather than all in one ?
Thanks
here is me writing the file
def writting_ppm(ppm_file,size_x,size_y,maxval,data):
    colour = 'P3'
    print size_x
    print size_y
    # maxval =  str(maxval).strip('['']')
    maxval = 255
    # data =  str(data).strip('[]')
    # print data
    with open(ppm_file, "w") as text_file:
        text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n" + (data) )

i am trying to implement a loop to do this :
with open(ppm_file, "w") as text_file:
    text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n")
    count = 0
    while count < len(data):
        text_file.write(data[count] + "\n")
        count = count + 1

but am currently getting errors, is the the right way to do this ?

A: You should use for loop and don't hack to strip the []. something like this:
def writting_ppm(ppm_file,size_x,size_y,maxval,data):
    colour = 'P3'
    print size_x
    print size_y
    # leave data as a list
    maxval =  max(maxval) # use max to get the max int in a list
    with open(ppm_file, "w") as text_file:
        text_file.write(colour + "\n" + "\n" +str(size_x) + " " + str(size_y) + "\n" + str(maxval) +"\n")
        for each in data:
            text_file.write(str(each)+'\n')


text:
Q: Apply a function to groups within a data.frame in R I am trying to get the cumulative sum of a variable (v) for groups ("a" and "b") within a dataframe. How can I get the result at the bottom -- whose rows are even numbered properly -- into column cs of my dataframe?
> library(nlme)
> g <- factor(c("a","b","a","b","a","b","a","b","a","b","a","b"))
> v <- c(1,4,1,4,1,4,2,8,2,8,2,8)
> cs <- rep(0,12)
> d <- data.frame(g,v,cs)

> d
   g v cs
1  a 1 0
2  b 4 0
3  a 1 0
4  b 4 0
5  a 1 0
6  b 4 0
7  a 2 0
8  b 8 0
9  a 2 0
10 b 8 0
11 a 2 0
12 b 8 0

> r=gapply(d,FUN="cumsum",form=~g, which="v")
>r

$a
   v
1  1
3  2
5  3
7  5
9  7
11 9

$b
    v
2   4
4   8
6  12
8  20
10 28
12 36

> str(r)
List of 2
 $ a:'data.frame':  6 obs. of  1 variable:
  ..$ v: num [1:6] 1 2 3 5 7 9
 $ b:'data.frame':  6 obs. of  1 variable:
  ..$ v: num [1:6] 4 8 12 20 28 36

I guess I could figure out some laborious way to get the data from those dataframes into d$cs, but there's got to be some easy tweak I'm missing.

A: My tool of choice for these things is the plyr package:
require(plyr)
> ddply(d,.(g),transform,cs = cumsum(v))
   g v cs
1  a 1  1
2  a 1  2
3  a 1  3
4  a 2  5
5  a 2  7
6  a 2  9
7  b 4  4
8  b 4  8
9  b 4 12
10 b 8 20
11 b 8 28
12 b 8 36

A: split<- is a pretty weird beast
split(d$cs, d$g) <- lapply(split(d$v, d$g), cumsum)

leading to
> d
   g v cs
1  a 1  1
2  b 4  4
3  a 1  2
4  b 4  8
5  a 1  3
6  b 4 12
7  a 2  5
8  b 8 20
9  a 2  7
10 b 8 28
11 a 2  9
12 b 8 36

A: I would use ave.  If you look at the source of ave, you'll see it essentially wraps Martin Morgan's solution.
R> g <- factor(c("a","b","a","b","a","b","a","b","a","b","a","b"))
R> v <- c(1,4,1,4,1,4,2,8,2,8,2,8)
R> d <- data.frame(g,v)
R> d$cs <- ave(v, g, FUN=cumsum)
R> d
   g v cs
1  a 1  1
2  b 4  4
3  a 1  2
4  b 4  8
5  a 1  3
6  b 4 12
7  a 2  5
8  b 8 20
9  a 2  7
10 b 8 28
11 a 2  9
12 b 8 36

A: > library(nlme)
> g <- factor(c("a","b","a","b","a","b","a","b","a","b","a","b"))
> v <- c(1,4,1,4,1,4,2,8,2,8,2,8)
> cs <- rep(0,12)
> d <- data.frame(g,v,cs)
> d <- d[order(d$g),]
> temp <- by(d$v,d$g,cumsum)
> d$cs <- do.call("c",temp)
> d
   g v cs
1  a 1  1
3  a 1  2
5  a 1  3
7  a 2  5
9  a 2  7
11 a 2  9
2  b 4  4
4  b 4  8
6  b 4 12
8  b 8 20
10 b 8 28
12 b 8 36

Another solution using the by function, but I had to order the data first


text:
Q: Pentaho Kettle - Convert hex to Number from field of type binary I need  to use Kettle/PDI community  version to  read  big  fixed  length  data  files and  do  some  ETL  stuff  on them.  During  development stage  I  faced  following  issue:

*

*Kettle plugin "Fixed File Input"  allows multiple  data  types with  remark they are  actually Strings or  byte arrays.

*My  input contained both:  Strings  and  byte  arrays corresponding to Little  Endian representation of long, int and short (Intel specific endian-ness).
Example  of  record  structure to be read:
       Column1(char:8), Column2(long:8 hex), Column3(char:2),Column4(int:4 hex).
I tried  to use "Select Values"  plugin  and  change  Binary  type  of  column to  Integer  but  such method  is  not implemented.   Finaly  I  ended with  following solution:

*

*I used  "User Defined Java Class"  with  code pasted  below.

As  you can see   I  used a formula  to obtain long value.
   public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
    Object[] r = getRow();

    if (r == null) {
      setOutputDone();
      return false;
    }

    // It is always safest to call createOutputRow() to ensure that your output row's Object[] is large
    // enough to handle any new fields you are creating in this step.
    r = createOutputRow(r, data.outputRowMeta.size());

    // Get the value from an input field
    byte[] buf;
    long  longValue;

    // BAN_L - 8 bytes
    buf= get(Fields.In, "BAN").getBinary(r);
    longValue=  ((buf[0] & 0xFFL) << 0) | ((buf[1] & 0xFFL) << 8)
                | ((buf[2] & 0xFFL) << 16) | ((buf[3] & 0xFFL) << 24)
                | ((buf[4] & 0xFFL) << 32) | ((buf[5] & 0xFFL) << 40)
                | ((buf[6] & 0xFFL) << 48) | ((buf[7] & 0xFFL) << 56);
    get(Fields.Out, "BAN_L").setValue(r, longValue);

    //DEPOSIT_PAID_AMT -4 bytes
    buf = get(Fields.In, "DEPOSIT_PAID_AMT").getBinary(r);
    longValue=  ((buf[0] & 0xFFL) << 0) | ((buf[1] & 0xFFL) << 8)
                | ((buf[2] & 0xFFL) << 16) | ((buf[3] & 0xFFL) << 24);
    get(Fields.Out, "DEPOSIT_PAID_AMT_L").setValue(r, longValue);

    //BILL_SEQ_NO_L -2 bytes
    buf = get(Fields.In, "BILL_SEQ_NO").getBinary(r);
    longValue =  ((buf[0] & 0xFFL) << 0) | ((buf[1] & 0xFFL) << 8);
    get(Fields.Out, "BILL_SEQ_NO_L").setValue(r, longValue);

    // Send the row on to the next step.
    putRow(data.outputRowMeta, r);

    //binaryToDecimal();

    return true;
}

Problem  arise  when  I  have  in one  data  extracts  8-20  binary  fields.
Is  there  any  alternative  to  this approach  so  I  can  call something like:
getNumberFromLE(byte [] buff, buff.length);

Is  there  any  other  plugin in development which can  be  used  to transform byte[]  to   Pentaho Kettle  "Number" data type? (BigNumber and Integer  are also  good).

A: I  found following possibilities:
1) it  is  possible  to  add  additional types  to  ValueMetaInterface class:
org.pentaho.di.core.row.ValueMetaInterface

and  add  conversion functions  into
org.pentaho.di.core.row.ValueMeta

2) add code snippet implementation getNumberFromLE to "Common use" Code snippits of  "User Defined Java Class"
3) add  as  plugin  new  data types as described  in bellow  two links:
    Jira pluggable types
GitHub pdi-valuemeta-map
AddingDataTypes


text:
Q: Good practices of SQL Server: nvarchar(max) performance New .net programmer here. As a new programmer, I always try to follow the best practices that I can when I am working. Today I started with SQL Server, and I asked co-worker which data type should I use for a user description column. He told me to use nvarchar(MAX) and I did and it worked great.
However, should we always use nvarchar(max) for this cases? or is it better to assign something like 500 characters?
I ask because I googled a little bit and I saw people saying that nvarchar(max) reserves a lot of memory for the column, which could reduce the performance of the database eventually.
Edit: Awesome answers guys, I´m clear on the topic now. No unicode stuff, therebefore im gonna go for varchar(600)

A: You should use nvarchar(max) whenever you have a field that could contain national characters (non-simple ASCII) and could be longer than 8,000 bytes.  In that case, it is exactly the right thing.
If you only have simple ASCII, then varchar() is appropriate but nvarchar() does little harm.
If you have a field that has a known maximum length or a reasonable maximum length, then max is not appropriate.  So stateName varchar(32) (or whatever), not stateName varchar(max).  Or, productDescription nvarchar(255), not productDescription nvarchar(max).
In cases, where the description is long, feel free to use it.  But don't over use it.

A: Best practice is to perform the appropriate data analysis BEFORE you design your table. Without context, one can assume that a description does not consist of pages and pages of text, so the "max" choice is probably not appropriate. As an additional consideration when choosing varchar(max), remember that you typically need to provide support for displaying such values in an application. If you do not intend to design a GUI to do so, then the choice is probably not appropriate.
And one more caveat - it is generally futile to attempt to future-proof your schema by choosing datatypes that exceed your foreseeable needs.

A: Beyond not being able to perform an online index rebuild for using a LOB data type, there will be a performance hit for choosing nvarchar(max) instead of nvarchar(4000) or nvarchar(1000).
SQL Server will assume that the average value will be half of the max size, this directly effects the memory that SQL Server will grant for queries.
Aaron Bertrand explains this along with a demo in this presentation/transcript:

So, when SQL Server looks at a column and you've decided, "Oh well, we'll just make this nvarchar 4000 so we're covered just in case." SQL Server actually believes that the average value will contain 2000 characters. So, when you have varchar 4000 and it's vastly oversized and all of the values are 10 characters you're actually—the memory that SQL Server will grant to this query is 2000 bytes per row, just for that column, instead of the 10 bytes that it really needed. So, you can see how the granted KB goes way up over time and how that actually affects the elapsed time.
- GroupBy.org - T-SQL : Bad Habits and Best Practices - Aaron Bertrand

Reference:

*

*GroupBy.org - T-SQL : Bad Habits and Best Practices - Aaron Bertrand

*Memory Grants and Data Size - Erik Darling

*Advanced TSQL Tuning: Why Internals Knowledge Matters - Paul White

*Performance comparison of varchar(max) vs. varchar(N) - Remus Rusanu

*Deletes that Split Pages and Forwarded Ghosts - Paul White


text:
Q: Trade off between layouts types In my app I have a layout which I can make in one RelativeLayout or with a nested LinearLayouts.
Is there a known trade off between the layouts? I mean, is there an equation like 1 RelativeLayout equals 3 nested LinearLayout or such?
Thanks!

A: Given that the algorithm used by the RelativeLayout is more complex than the one used by the LinearLayout, what you are essentially asking is if "three LinearLayout worth more than a RelativeLayout" performance-wise.
We could probably delve into a lot of details about how each layout measures the contained views hierarchically and try to give a theoretical answer to the question, but the correct answer is, IMHO, that the only way to find out is to create both layouts and measure how long it take for each one of them to be measured. When it comes to performances, profiling is always the solution (where excessive pre-emptive optimization rarely is...).
Keep also in mind that the profiling data might be of limited use anyway, as with each new iteration of the Android OS the developers might tweak and (hopefully) improve the algorithms used to place the views (therefore the data gathered from a 2.2 profiling session might not represent the results you would get in ICS).
Personally, I usually go with the multiple LinearLayout approach, as I feel it's easier to read and modify, but when I had to switch to a RelativeLayout I never noticed a significant degradation/improvement of performances
Hope this helps


text:
Q: How do I package a Python script for Ubuntu? I have a Python 3.2 script that I'd like to package for Ubuntu and Debian. I've certainly looked for documentation but I wasn't sure that I was getting the latest and greatest/easiest methods.
If someone with enough knowledge could please point me to the most recent guide on how to do this, it would be very useful to me.
Additionally, given a bit of what I have seen I might need a setup.py file too? If so I need to learn about that too.

A: The Ubuntu developer portal has a very complete Packaging Guide.
There is also a tool, Quickly, designed to help new developers hack and package their applications easily and... quickly. This tool will also help you creating the setup.py script.
Finally, take a look at how to get started at Ubuntu application development.

A: You could use debreate. A GUI tool to make .deb files. you can get it here.
You could also look into ST Alfas answer in this link. Hope this helps! :)


text:
Q: How to display an autocomplete menu in vimscript? I'm a beginner in vimscript and even if I search the web for hours I haven't be able to find how to do the following thing :
I want to create a vimscript who will allow to open a file by typing just some letters :
Assuming

*

*I only search in the current working directory

*I have a python script that could look recursively through the folders and store the files with the given letters in an array

What I want
<leader><leader>p call a function that will do what is necessary (I don't know what exactly for the moment...)
This function will ask the user to enter the desired letters. While he enter letters, a menu will display the available results (so, this menu needs to be refreshed automaticaly).
I wish that the user could end to type and just move to the desired file by highlighting it.
For exemple :

What I currently have
if !has('python')
    echo "Error: Sublime Search require vim compiled with +python"
    finish
endif

let s:current_file=expand("<sfile>:r")
let s:script_path = s:current_file . '.py'
exec 'pyfile ' . s:script_path

function SublimeSearchTrigger()

    python lookFor()

endfun

if !exists('g:sublimesearch_keys')
    let g:sublimesearch_keys = 1
endif

if g:sublimesearch_keys
    inoremap <leader><leader>p :call SublimeSearchTrigger()<cr>
    nnoremap <leader><leader>p :call SublimeSearchTrigger()<cr>
endif

And the python file
# -*- encoding: utf-8 -*-

import vim
import sys

def lookFor():

    # Ask user to type something to find
    vim.command("let user_input = input('Sublime search : ')")
    vim.command("call inputrestore()")

    # Visual return of what we typed
    vim.current.buffer.append( vim.eval( 'user_input' ) )

How to start ?
As you can see I'm not sure how to start but I'm really motivated (I'm planning more complex functionalities but there will be implemented with python).
Could someone help me to start ?
Thanks,
Damien

A: What you show in your screenshot is the wildmenu of the command-line. You can add custom completion to your own commands, see :help :command-completion-custom. Unfortunately, you cannot change the completion behavior of built-in commands like :edit (but you could define your own wrapper command :Edit and make that use your complete function).
The second mechanism is the insert mode completion (:help ins-completion-menu). This is used for autocompletion, snippets, any text entered into the buffer. Unless you want to insert your file names into the buffer (e.g. for completion of import statements), this isn't the right thing for you.
Many plugins implement their own completion mechanism, as this offers the most control. They create a new, split scratch buffer, and use that for displaying the matches, often in combination with the insert-mode completion menu (but not for inserting the chosen text, but acting on it). Have a look at the FuzzyFinder plugin, it employs this very well, and even allows to plug in custom data providers (that could be your Python script!)


text:
Q: cocos2d ccsprite in front or top of android xml layout want to add CCSprite on button click of android xml layout , this CCSprite must be in front of that layout button. Please help me out
holder.buttonDonate.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

//  ClanCastleDonateUI extends CCLayer and it contains CCSprite
ClanCastleDonateUI troopDonatePopup = new ClanCastleDonateUI(message2);

                            troopDonatePopup.setAnchorPoint(0.5f, 0.5f);
                            troopDonatePopup.setPosition(HowUtils.getScreenSize().x/2, HowUtils.getScreenSize().y/2);

troopDonatePopup.setVertexZ(50);

                    CCDirector.sharedDirector().getRunningScene().addChild(troopDonatePopup, 9999999);

        }
    });

A: Please be more specific. according to what i understand , do you need to change the button when clicked. or do you have to place a new sprite on the screen when a button is clicked.


text:
Q: Parallel Evaluation I want to speed-up the following program for obtaining Poincare Sections
 sol[r0_?NumericQ, z0_?NumericQ] :=NDSolve[{r'[t] == Fr/Ft, z'[t] == Fz/Ft,
 r[0] == r0, z[0] == z0}, {r,z}, {t, 0, tmax}, Method -> "Automatic"];

 p[t_] := Evaluate[{r[t], z[t]} /. sol[#, 0] & /@ Range[0.6, 3.8, 0.1]];

 ptab = Table[ListPlot[Table[Table[p[i][[j]][[1]], {i, k, tmax-k, 2 Pi}],
 {j, 1, Length[p[i]]}], PlotStyle -> {{Blue, PointSize[0.0033]}}, ImageSize
 -> 290, PlotLabel -> {"phi=", k}], {k, 0, 3 Pi/4, Pi/4}]

where $Fr,\, Fz,\, Ft $ are given by analytic expressions. I use the
     ParallelEvaluate
command, but it doesn't work!
What can I do for parallel computation or in general for a faster algorithm?
Also how can I do the same procedure for $Fr,\, Fz,\, Ft$ given by numerical data and not by analytic expressions?


text:
Q: Workarounds for "cp -p" not preserving nanoseconds on High Sierra with APFS? I don't know if this affects MacOS versions newer than High Sierra, but it seems that cp -p won't preserve timestamps with nanoseconds resolution.
Because of this, the shell can wrongly tell that a file is older than other even if it was copied by cp -p. This breaks build system dependencies when some files were installed by cp -p: they keep reinstalling and reinstalling again because the nanoseconds don't match.
Can you suggest some workaround for this? I thought compiling my own cp binary, but however cp is usually a shell builtin, and moreover I'm not aware of any nanosecond-preserving cp version out there.
Note: I know of a workaround, but it's not reasonable: Execute touch on the source file before executing cp -p. Because touch doesn't preserve nanoseconds either, it makes them zero on the source file, so the result after cp -p guarantees exactly the same timestamp. However, as I said, it's not reasonable, because I don't like to touch files just for this: you lose their real last saved date.

A: Good to know that I'm not the only one who thinks this is a problem. I ran into it while writing a Python script for monitoring parts of my macOS (10.15.7) filesystem, which also involved coping files. The script sometimes behaved erratic and produced unpredictable output. After some poking around I found out that the incapability of cp -p to preserve nanoseconds is the core of the problem.
One workaround for your problem (but not for mine) could be coreutils: gcp -p behaves as intended.

A: I thought this was fixed in 10.15, but I just didn't repro the problem correctly. To save others the same embarrassment, here's a repro that shows the problem:
% python3 -c 'open("file1", "w")'
% stat -f %Fm file1
1609301645.481666557
% cp -p file1 file2
% stat -f %Fm file2
1609301645.481666000


text:
Q: Newtonsoft.Json.JsonSerializationException when fetching an object from Akavache storage When putting an instance of an object into the Akavache-storage, all works out. But when trying to get it from the storage, I get the following error message:
Newtonsoft.Json.JsonSerializationException: Unexpected token while deserializing object: EndObject. Path 'Value.Tracks[0]'.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0015f] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x0007e] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Users/builder/data/lanes/1503/c2c00129/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61
  at System.Reactive.PlatformServices.ExceptionServicesImpl.Rethrow (System.Exception exception) [0x00006] in <filename unknown>:0
  at System.Reactive.ExceptionHelpers.ThrowIfNotNull (System.Exception exception) [0x0000d] in <filename unknown>:0
  at System.Reactive.Subjects.AsyncSubject`1[System.Collections.Generic.IEnumerable`1[Core.OfflineTrackCollection]].GetResult () [0x00039] in <filename unknown>:0
  at Core.OfflineTrackCollectionClient+<GetAll>c__async0.MoveNext () [0x00080] in /--Path--/Core/OfflineTrackCollectionClient.cs:30

I previously deserialized that object after fetching the JSON from a remote service using the following deserializers:
// Try to parse the response into the requested object
var settings = new JsonSerializerSettings { ContractResolver = new UnderscoreMappingResolver() };
var obj = JsonConvert.DeserializeObject<T>(jsonString, settings);

Within the class T I make use of some custom JsonConverter and also set a property-name by using JsonProperty - all done by annotation. DateTime objects are also along here (if that has something to say ..)
I can't wrap my head around, what I am doing wrong here - and I haven't found anything online. Later you can see the object OfflineTrackCollection I try to get here. What I've tried is, that it works if I remove that Track list or if I leave it empty. So it has something to do with a track-object (you can find the object below). Do you have any idea, or have you had that problem earlier?
Here is the class and some objects. Ping me if you want to see more code. The converters aren't called (at least the debugger didn't stop there).
namespace Core
{
    public class OfflineTrackCollectionClient : IOfflineTrackCollectionClient
    {
        const string STORAGE_PREFIX = "track_collection_";

        public async Task<IList<OfflineTrackCollection>> GetAll()
        {
            try {
                var objects = await BlobCache.LocalMachine.GetAllObjects<OfflineTrackCollection>();
                return objects.ToList();
            } catch (Exception e)
            {
                throw;
            }
        }

        public async Task Save(TrackCollection item)
        {
            var offlineTrackCollection = new OfflineTrackCollection() { Id = item.Id, Name = item.Name };

            foreach(var track in item.Tracks)
                    offlineTrackCollection.Tracks.Add(track);

            await BlobCache.LocalMachine.InsertObject<OfflineTrackCollection>(STORAGE_PREFIX + offlineTrackCollection.Id, offlineTrackCollection);
        }
    }

    [JsonObject]
    public class OfflineTrackCollection
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public IList<Track> Tracks { get; set; }
    }

    [JsonObject]
    public class Track : Document
    {
        public Track()
        {
            Type = DocumentType.TRACK;
        }

        public int ParentId { get; set; }
        public bool IsVisible { get; set; }

        [JsonConverter(typeof (StringEnumConverter))]
        public TrackSubType Subtype { get; set; }

        public IEnumerable<string> Tags { get; set; }
        public DateTime RecordedAt { get; set; }

        [JsonProperty(PropertyName = "_meta")]
        public TrackMetadata Meta { get; set; }
        public IEnumerable<TrackMedia> Media { get; set; }
    }

    [JsonObject]
    [JsonConverter(typeof (DocumentConverter))]
    public class Document
    {
        public int Id { get; set; }

        [JsonConverter(typeof (StringEnumConverter))]
        public DocumentType Type { get; set; }

        public bool ShouldSerializeId()
        {
            return false;
        }
    }
}

namespace Core.JsonConverter
{
    public class DocumentConverter : JsonCreationConverter<Document>
    {
        protected override Document Create(Type objectType, JObject jObject)
        {
            // First check up if the objectType is already fixed to a implementation.
            if (objectType == typeof (Track))
                return new Track();

            // A type has to be defined for type-juggling.
            if (jObject["type"] == null)
            {
                throw new NotImplementedException("The type of the document has not been defined!");
            }

            // Try to find out what the implementation is.
            switch (jObject["type"].Value<string>())
            {
                case "track":
                    return new Track();
            }

            throw new NotImplementedException("The type " + jObject["type"].Value<string>() +
                                              " is not implemented in the DocumentConverter.");
        }
    }

    // Copied from http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base
    public abstract class JsonCreationConverter<T> : Newtonsoft.Json.JsonConverter
    {
        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        /// <summary>
        ///     Create an instance of objectType, based properties in the JSON object
        /// </summary>
        /// <param name="objectType">type of object expected</param>
        /// <param name="jObject">
        ///     contents of JSON object that will be deserialized
        /// </param>
        /// <returns></returns>
        protected abstract T Create(Type objectType, JObject jObject);

        public override bool CanConvert(Type objectType)
        {
            return typeof (T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }

        public override object ReadJson(JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            // Load JObject from stream
            var jObject = JObject.Load(reader);

            // Create target object based on JObject
            var target = Create(objectType, jObject);

            // Populate the object properties
            serializer.Populate(jObject.CreateReader(), target);

            return target;
        }

        public override void WriteJson(JsonWriter writer,
            object value,
            JsonSerializer serializer)
        {
            // Should never be called, as the property CanWrite is set to FALSE
            throw new NotImplementedException();
        }
    }
}

EDIT Added the JsonConverter and the data I get out of when calling BitConverter.ToString(await BlobCache.LocalMachine.Get("track_collection_1")):
[encoded data, 13181 characters]

I don't really know the details of how Akavache does the serialization for storing an object in the SQL file ... but it either does not store that here or it does something to it before sending it into the JsonSerialization

A: While working on a minimal example, I recalled the mistakes I did:
Akavache didn't knew about the UnderscoreMappingResolver by the time I called the serializer. Therefore, it serialized and saved the document as { Type: "track" } but the DocumentConverter expected the property Type to be lowercase when de-serializing, like it was done when de-serializing the JSON string I got from the server.
I - back then - fixed it by implementing a switch in the DocumentConverter to either take the property type or Type. This means in coe, that I replace jObject["type"] by jObject["type"] ?? jObject["Type"].
Today, I'd rather overwrite the serializing-settings of Akavache:
How can I set JsonSerializerSettings for Akavache?
@DanBeaulieu, I'd ask you to debug your implementation of JsonCreationConverter<T>. Maybe an exception is thrown in your implementation or it quits without sending an instance of the object you'd expect.


text:
Q: Add Existing Contact to User's Contacts We have a set of public contacts the company maintains, but the users only deal with a portion of them so they have copies of them in their local lists. These get out of date. I want to overwrite the information of the local contacts from the public contacts, but can't find an easier way of doing that other than creating the ContactItem and then manually setting each property to the values from the public. Is there an easier way of adding existing contacts to the local list?
What I'm currently doing
// Get the public folder for the contacts
session = Application.GetNamespace("MAPI"); // Application is Outlook
sessionFolders = session.Foldeers;
publicFolders = sessionFolders["Public Folders"];
publicContacts = publicFolders["Public Contacts"];
publicContactsItems = publicContacts.Items;

localContacts = session.GetDefaultFolder(Outlook.OlDefaultFoldes.olFolderContacts);
localContactItems = localContacts.Items;

for(int p = 1; p <= publicContactItems.Count; p++)
{
    var pContact = publicContactItems[p];
    // Search for the contact in the users local list
    for(int l = 1; p <= localContactItems.Count; l++)
    {
        var lContact = localContactItems[l];
        if(publicContact.Email1Address == localContact.Email1Address)
        {
            // Copy information.
            // DOING localContacts.Items.Add(publicContact) DOES NOT WORK!
            // lContact = pContact doesn't work either.
            // lContact.FirstName = pContact.FirstName; lContact.Save(); does
        }
    }
}

I'm not sure what's best in the "copy information" section. I could delete the current contact and create a new one with Application.CreateItem(OlItemType.olContactItem) or I can use the current item, overwrite the properties and save. There are a lot of properties either way though.
EDIT: I may not have added enough information. The ContactItem is an Outlook class, not a object created by me. All of this code is in an Outlook Add-in. I've added more code to show this.
EDIT NUMERO DOS: Using @ext0 answer and another question for reference I was able to solve it.
the slight modificatoin to @ext0 answer
if (lContact.Email1Address == pContact.Email1Address)
{
    var lProperties = lContact.ItemProperties
    var pProperties = pContact.ItemProperties
    for (i = 0; i < pProperties.Count; i++) // ItemProperties goes back 0 index, keep it up Microsoft!
    {
        try { lProperties[i].Value = pProperties[i].Value}
        catch{}  // Even though Value is read/write, some properties are read-only
    }
    lContact.Save();
}

And remember kids! Always release your com objects after use!

A: You can update the data in your old contact object using Reflection in order to completely update all of the properties / fields. If you are using fields instead of properties, just replace GetProperties() with GetFields(). The following code replaces the contents of oldContact with all of the property values of newContact.
public static void Main()
{
    Contact oldContact = new Contact{
        name = "John",
        email = "John@example.com",
        age = 40
    };
    Contact newContact = new Contact{
        name = "Joshua",
        email = "John@example.com",
        age = 42
    };
    Type contactType = oldContact.GetType();
    foreach (PropertyInfo property in contactType.GetProperties())
    {
        property.SetValue(oldContact, property.GetValue(newContact));
    }
    Console.WriteLine(oldContact.age);
}

public class Contact
{
    public String name { get; set; }
    public String email { get; set; }
    public int age { get; set; }
}

This code will print out 42, as oldContact has been updated with the values from newContact.


text:
Q: Is it detrimental to performance to reference all of an entity type in mapStateToProps? I've been building quite an extensive app with React, Redux and Normalizr but have been struggling with a totally excessive number of redundant render cycles, and am now thinking I've perhaps misunderstood how to combine mapStateToProps and Normalizr.
In my mapStateToProps, I'm referencing all of a certain entity type, which I can then use to get an entity from its ID:
function mapStateToProps(state) {
    return {
        allMilestones: state.account.entities.milestones,
        allTasks: state.account.entities.tasks,
    }
}

Using the above mapStateToProps, whenever I need to get an entity, I can just go (for example) const taskObject = this.props.allTasks[taskId]. Quick and convenient, but I understand this means there's a lot of props being passed around - I thought passing around references wouldn't be a big deal, but then I noticed everything was re-rendering just, all the time.
Would this be a likely culprit for an unreasonable amount of render cycles?
If so, could I expect implementing Reselect for all of these cases would positively affect performance?

A: It's possible but this is a guesstimation without benchmarks (and you should try to clarify that yourself before making any optimisations). React-Redux will do a comparison of all of the keys of the object returned from mapStateToProps and will rerender if any are different.
If the reference changes each time - because you're using an immutable Map, for example - then the component will re-render any time mapStateToProps() is called.
You should try to make the return value more stable by only returning what is required by the connected component.
https://react-redux.js.org/using-react-redux/connect-mapstate#return-values-determine-if-your-component-re-renders


text:
Q: Which is better ORM (Apache Cayenne) , JDBC or SpringJDBC? I am Working on multiple database like MSSQL server and PostgreSQL with heavy transactions and complex queries. I have searched that simple jdbc is more faster then ORM. I was thinking of using ORM because I do not want to write different query for different database for same work, and also for standardized my dao layer. I am mapping my database tables without using foreign keys and for ORM like apache cayenne I have to map tables with foreign key constraint, so I can use my Joins or any other multiple table operations. Is it good to use and ORM or simple jdbc is fine.

A: From your problem dscription, you already have an understanding of the tradeoffs involved. So this is really a decision that you need to make for yourself based on those tradeoffs.
My only advice here will be to take a second look at performance requirements. While ORM does introduce an overhead of creating, storing and managing  objects, in all but a few cases, you can safely ignore this overhead for the sake of a better abstraction. Also when working with JDBC very often you end up writing your own code to convert ResultSet to objects, which will encounter its own overhead. So you may not end up with faster code, while forfeiting all the benefits of a clean object model and a framework that manages it.
So my own preference is to go with a better abstraction (ORM in this case), and then use the framework tools for optimizing the performance. E.g. to speed up processing of large ResultSets Cayenne provides a few techniques: result iterators, DataRow queries, paginated queries, etc.
On the other hand I would use JDBC or something like MyBatis when it is not possible to cleanly model your data as entities. E.g. when there are no natural relationships, all access happens via stored procedures, etc. Doesn't seem like your case though.


text:
Q: Trying to find a count of items from a two level deep association, any ideas? I am working on an application where I need to find the count of submitted items by users that have been referred by a user.
For Example -
User1 has referred 3 people (User2, User3, User4) and each of those users has submitted 5 articles.
I am trying to find a way to get the count of submitted items in User1's tree (should be 15 in this case).
My user model looks like the following (simplified)
class User < ActiveRecord::Base
  # Code for user referrals
  belongs_to :referrer, :class_name => "User"
  has_many :referrals, :class_name => "User", :foreign_key => "referrer_id"
  has_many :items
end

I can find out the count for each user easily (User.items.size), but I am having trouble finding a solution to get the referral counts as one sum.
Any ideas?

A: Try this:
user = User.find(1)
total_items_size = user.referrals.map(&:items).flatten.size

A: You can use select_value to manually run the SQL query:
def referred_items_count
  select_value("select count(*) as referred_items
  from items inner join users on users.id = items.user_id
  where users.referrer_id = #{self.id};", "referred_items")
end

The benefit is that it is a lot more scalable than using Ruby to count.

A: Get all items of User with id of 1
total = 0
Users.find(1).referrals.each do |refer|
   total += refer.items.size
end


text:
Q: PC wakes from hibernate by keyboard and mouse My new PC wakes from hibernate by pressing any key on keyboard (PS/2) or mouse (USB); just like sleep mode (with the difference that power LED doesn't blink).
If I uncheck "Allow this device to wake the computer" for them, PC doesn't wake from hibernate by keyboard and mouse anymore but it also affects sleep mode.
I checked BIOS settings; "Power On By PS/2 Keyboard" is "Disabled". So why it wakes by keyboard and mouse? I don't like this behavior. I want it to be as other normal systems: wake from sleep by mouse and keyboard, wake from hibernate only by power button.
Resetting BIOS settings didn't solve the problem.
Motherboard: Asus A320M-K
BIOS: AMI 5603
OS: Windows 10 Pro 20H2 (installed from official ISO file - still no update)
CPU: AMD Ryzen 3 3200G