text:
Q: Setting scale for data driven pages I'm trying to use DDP to produce a map book for a series of works. Each item of work is a feature in a polyline feature class, and a copy of the class is being used to define my DDPs. I already have set up dynamic text, page definition queries etc.
As the work lines are variable in length, I want to constrain my map scale so that they are not zoomed in or out too far. My code:
import arcpy
from arcpy import env

env.workspace = r"U:"
mxd = arcpy.mapping.MapDocument(r"U:\EMS.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
ddp = mxd.dataDrivenPages
indexLayer = ddp.indexLayer

# def ddpScale():
#     if df.scale < 6000:
#         df.scale = 6000
#     elif df.scale > 10000:
#         df.scale = 10000
#     else:
#     df.scale = 10000

for i in range(1, mxd.dataDrivenPages.pageCount + 1):
    mxd.dataDrivenPages.currentPageID = i
    for scale in df.scale:
        if df.scale < 6000:
            df.scale = 6000
        elif df.scale > 10000:
            df.scale = 10000
        else:
            df.scale = 10000
    #df.scale = ddpScale

ddp.exportToPDF(r"U:\test.pdf")

del mxd

The commented out lines were my attempt to define a function for setting the scale, but I opted for a elif statement instead. I basically want any pages with a scale less than 1:6000 to be 1:6000, and all others to be 1:10,0000.
As an addition, I would like lines that are above 1:10,000 originally to be split across multiple pages as needed.
How would I got about setting the scale in this manner?
The error I am getting:
Traceback (most recent call last):
  File "C:/XXXddp.py", line
20, in <module>
    for scale in df.scale:
TypeError: 'float' object is not iterable

A: An alternative is to use a field with scales as Data Driven Scale Field:

When you specify a Data Driven Scale field, values from this field
  define the map scale of the detail data frame for each page in the
  Data Driven Pages series

The field can be calculated using arcpy by the extent of each feature:
import arcpy

fc = "Areas" #Change to match your fc
scalefield = "Scale" #Add this field before executing the code.

with arcpy.da.UpdateCursor(fc,["SHAPE@",scalefield]) as cursor:
    for row in cursor:
        ext = row[0].extent
        maxdiffxy = max([ext.XMax-ext.XMin,ext.YMax-ext.YMin]) #Max width or height of feature
        if maxdiffxy<2500: #If smaller than 2500 meters, use 6000 scale. Will have to be adjusted
            row[1] = 6000
        else:
            row[1] = 10000
        cursor.updateRow(row)


text:
Q: Disable animations in office 365 Is there any way to disable the animations that Microsoft has enabled by default in office 365?
It seems that ticking 'Turn off all unnecessary animations (when possible)' no longer does the trick. It was working fine around 2 days ago, and then it seems that office got updated, together with the new loading animation.
I have made sure that this function is still ticked, however this now changes completely nothing. Since this is a new behaviour I couldn't find anything on the Internet, other than 'tick turn off all unnecessary animations in ease of use'. I couldn't find anything in Office settings which would disable those animations.
If this helps I am running Windows 7.

A: I found this to work for various versions, up to the latest version of Word. But please note that this will affect ALL Office applications, not only Word!
I'm actually copying & adapting from this page on askvg.com .
If you don't feel to edit the registry yourself, you can download the necessary automatic script from that link. Otherwise, take the following steps:

*

*Close any office application.

*Press "WIN+R" key combination to launch RUN dialog box then type regedit and press Enter. It'll open Registry Editor and go to following key:
For Office 2013:
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common
For Office 2016, 2019 & 365:
HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common

*Check if there is a key "Graphics" existing. If not, right-click on Common key and select New -> Key option. It'll create a new key, set its name as Graphics

*Now in right-side pane, create a new DWORD DisableAnimations and set its value to 1

*Close Registry Editor and open any Office application. Changes are instant: no more animations and effects.

*If you want to restore default animations, change value of DisableAnimations to 0 or simply delete the DWORD.

A: Disabling the hardware acceleration as mentioned by tomasz86 helped in Word.  It looked like an update tried to make page scrolling smooth or something.
I would just add (to make it easier to find - at least in Office 365) that the path to the option is:
File > Options > Advanced > Display (this subsection has the "Disable hardware graphics acceleration" option to check)

A: To disable animations in Office 365, use regedit and navigate to this key: [HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Graphics].
Then add a new DWORD with name DisableAnimations and value 1.
This should disable all annoying animations Office-wide. I've found this is the only way to stop the annoying folder opening / closing animations in Outlook.
To disable the annoying animations in Excel, there is an option in File / Options / Ease of Access called Provide feedback with animation that can be deselected.

A: To turn off animations [I don't see why I shuld have to wait for Excel to update the screen either!] go to options, 'Ease of Access' then untick 'Provide feedback with animation'
Job Done...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ionic 2 IOS push notification activation without using MAC I have created IONIC 2 App and currently have launched only android version, now I am planning to publish IOS version for the same.
I created IOS package using ionic package and tested in Iphone and its working but the PUSH Notification is not working for IOS and I can not find a way to implement PUSH notification for IOS without using MAC/XCODE.
Docs explain things by using XCODE - https://docs.ionic.io/services/push
Please let me know what changes I need to make to activate PUSH for IOS, I already have created APN Certificate & App Development/App Store Certificate and have linked to IONIC.IO
Please suggest.
Thanks


text:
Q: Automatically schema backup in Oracle I am working with an Oracle Database and I have a user (called XY) with permissions R/W. I would like to to do automatic backups of the user schema XY. I don't own the server and I don't know if the provider does backup of my schema. Probably does,but I would like to do myself the automatic Backup. I use as Oracle Client the tool SQL Developer.
I know that I can do Extras-> Database Copy but it is not automatic.
Can I achieve this with this client? If so, how?If it is not possible, what alternative do I have?
Thanks!

A: If you will have access to server's filesystem, or you can ask for this, you can use crontab utility. To verify whether you have access to cron, type in the following
crontab -e

If you will have an OS user,and if you can use the crontab utility to schedule a job, you can try something like this:
*/30 * * * * ~/bin/dump.bsh 1>~/bin/log/dump.log 2>&1

This simple entry make a logical backup every half hour.
The dump.bsh file:
#!/bin/bash
PATH=/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:$ORACLE_HOME/bin
. $HOME/.bash_profile

now=`date +"%Y-%m-%d_%H-%M"`
expdp user/passwd directory=data_pump_dir dumpfile=lbackup$now.dmp schemas=schema_to_backup

You need to set Oracle env variables (here in the .bash_profile) since cron passes only a minimal set of env variables to your jobs.
Otherwise, go and have a look at this SQL Developer page. In the exports (expdp) section there is also a reference to automatic jobs.


text:
Q: How to create an installer for windows service built in C++ I want to create an installer for windows service built in C++. I have followed this article to create the Service.
 I have 3 win32 console application in my solution. one for installation , one for uninstallation and one that does the actual work.

A: I must humbly recommend WiX (Windows Installer XML Toolset) for all your installer needs.


text:
Q: Rewrite rule to redirect html, but not any other files I want my htaccess to redirect URL that end on ".html" to the index.php, but not any other files (so images can keep their href and still be displayed)
This is how my htaccess looks like now, it works for the HTML redirect, but styles or images are not displayed (because they are also redirected, I guess)
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^/?([\w./]+)\.html$ /index.php?object=$1 [L]
RewriteRule ^/?([^html]+)$ /$1

How can I get it to work, so only .html-files are redirected?

A: RedirectMatch 301 (.*)\.html$ http://www.example.com$1.php

Used this before worked great.

A: RewriteRule ^/?([^html]+)$ /$1

Doesn't do what you want. It matches anything not containing any of the characters h, t, m or l. Your first rule is also strange; having both \w and . is redundant since . implies \w in addition to other characters.
Try this rule:
RewriteRule ^/?(.*)\.html$ /index.php?object=$1


text:
Q: Batch request with fql using javascript The following batch request for retrieve friends using the same app is not working:
var search = {batch: [
    {
      'name' : 'getFriends',
      'relative_url': 'method/fql.query?query=SELECT+uid,+first_name,+name,+pic_square,+pic_small+FROM+user+WHERE+is_app_user=1+and+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=' + userId + ')'
    },
    {
      'method': 'get',
      'relative_url': '{result=getFriends:$.data[*].uid}/news.reads/article',
    }
]};

and the following code executes the batch request:
FB.api('/', 'post', search, function(response) {
    console.log(response);
});

but the first search returns null. What's wrong with the query?
According to facebook documentation for batch requests, the *relative_url* is

(...) a relative_url (the portion of the URL after graph.facebook.com)

get from here.
So I changed the first block of code to:
var search = {batch: [
    {
        'name' : 'getFriends',
        'method' : 'GET',
        'relative_url': 'method/fql?q=SELECT uid, first_name, name, pic_square, pic_small FROM user WHERE is_app_user=1 and uid IN (SELECT uid2 FROM friend WHERE uid1=me())'
    },
    {
        'method': 'GET',
        'relative_url': '{result=getAmigos:$.data[*].uid}/news.reads/article'
    }
]};

the relative_url of the first block on the batch works at Open Graph API Tool at facebook, but at the JS the http code is 500 and the message body is:
{
    "error": {
        "message": "Graph batch API does not allow REST API method fql",
        "type": "FacebookApiException",
        "code": 3
    }
}

but in the api batch requests documentation allows fql queries. The documentation is outdated? Should I open a bug?
P.S: the fql without the batch request is
SELECT uid, first_name, name, pic_square, pic_small
FROM user WHERE is_app_user=1
     and uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

A: Don't use method/fql; Facebook's FQL endpoint is now just fql.
...
"name": "getFriends",
"method": "GET",
"relative_url": "fql?q=SELECT...",
...

A: it's working now. I just add the access_token parameter at the batch object. like this:
var searchArgs = {
   access_token: FB.getAuthResponse().access_token,
   batch: []
};

searchArgs.batch.push({
     'method': 'GET',
     'name': 'amigosapp',
     'relative_url': 'method/fql.query?query=SELECT+uid,+first_name,+name,+pic_square,+pic_small+FROM+user+WHERE+is_app_user=1+and+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())&limit=20',
     'omit_response_on_success': false
});

searchArgs.batch.push({
     'method': 'GET',
     'relative_url': 'news.reads/article?date_format=U&ids={result=amigosapp:$.[*].uid}'
});

the other trick was use the jsonpath expression in a different way. I couldn't make the second request for each user of the first request. So I changed the way to get it adding the friends ids at the end of the graph api request. I think that my first thought about a request per friend it's not possible using the batch request.
Then I did the call of the batch:
FB.api('/', 'POST', searchArgs,
    function(response) {
        var friends = response[0].body;
        console.log(friends);
        var activities = response[1].body;
        console.log(activities);
    }
);

Now it's just organize the posts retrieved.
[]'s


text:
Q: Loopback, AngularJS and validation I followed this tutorial to create a project with Loopback and AngularJs. https://github.com/strongloop/loopback-example-angular
Now, I have an application with:

*

*HTML files (with Bootstrap)

*AngularJS controllers

*AngularJS service (generated with syntax lb-ng server/server.js client/js/services/lb-services.js)

*Model (located in ./common folder)

*MongoDB backend

The model "Device" is defined in ./common/models/device.js
module.exports = function(Device) {
};

And in ./common/models/device.json
{
  "name": "Device",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "description": {
      "type": "string",
      "required": true
    },
    "category": {
      "type": "string",
      "required": true
    },
    "initialDate": {
      "type": "date"
    },
    "initialPrice": {
      "type": "number",
      "required": true
    },
    "memory": {
      "type": "number"
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

In the "AddDeviceController", I have an initialization part with:
$scope.device = new DeviceToBuy({
  name: '',
  description: '',
  category: '',
  initialPrice: 0,
  memory: 8
  initialDate: Date.now()
});

And I am able to save the $scope.device when executing the following method:
  $scope.save = function() {
     Device.create($scope.device)
      .$promise
      .then(function() {
        console.log("saved");
        $scope.back(); // goto previous page
      }, function (error) {
        console.log(JSON.stringify(error));
      });
  }

When everything is valid, the model is saved in the backend.  If something is not valid in the $scope.device, I receive an error from my backend.  So everything is working fine.
Now, I would like to use the model to perform client-side validation before sending my model to the backend and put some "error-class" on the bootstrap controls.
I tried something in the $scope.save function before sending to the backend:
if ($scope.device.isValid()) {
  console.log("IsValid");
} else {
  console.log("Not Valid");
}

But I get an exception "undefined is not a function" --> isValid() doesn't exist.
And I cannot find any example on how to execute this client-side validation.

A: LoopBack models are unopinionated and therefore do not provide client side validation out-of-box. You should use Angular validation mechanisms before calling $save.


text:
Q: Multiple steps multithreading in Python I'm a bit stuck with my multithreading processing. Not maybe stuck, but struggling.
The case is:

*

*Process incoming data elements read in while loop - I created a multiprocessing.Pool and a multiprocessing.Queue. As a processing worker I do:
the_pool = Pool(PROCESSES, process_item_queue, (i_queue, o_queue,))

*The idea is that process_item_queue generates some still complex data that I want to process ALSO in a queue (hence o_queue - output_queue). The body of process_item_queue looks something like:
    while True:
        args = i_queue.get(block=True)
        if args is None:
            print("Breaking out of the queue")
            break
        output = process_item(*args)
        o_queue.put([output])

*Ideally, at some point, some of the processes could already start processing the o_queue, but I have no idea how to achieve that dynamically assigned processes.

*The point I'm struggling with now, can actually be divided into multiple parts:
4.1. The process_item function returns a dict. All of the dicts have to be merged with some custom logic. My idea is, that each process should read two dicts from the queue, merge them using my custom logic, and republish dict back to the queue. At some point, obviously, we'll end up with just two dicts, possibly in different processes. I'd be okay with doing the last merge in main thread, but I don't know how to really inform my processes that, well, there's nothing more there! Normally, I'd send None and each process would quit, but this is more complicated, as we go 1024->512->256->128... etc. I also can't give it a definitive timeout, as depending on CPU, each process can take more or less time.
4.2 I can't really close the pool because o_queue is full of items. I could probably even hit some memory limits so it might be important to actually start processing those items on the fly.
Any advice will be appreciated ;)


text:
Q: Размер блока в Multicolumn Вот код: http://jsfiddle.net/94a4j/
UL всегда растягивается до 100%. Как установить ширину на auto?
И вот что будет если у родительского блока установить float: left - http://jsfiddle.net/94a4j/1/
A: Единственный способ залить элемент целиком, это сделать элемент типа inline-block и явно указать количество колонок.  Больше никаких манипуляций проводить не надо.
ul {
    -webkit-columns: 160px 2;
    -moz-columns: 160px 2;
    columns: 160px 2;
    display: inline-block;
}

Посмотреть пример
A: auto Ширина колонок вычисляется автоматически на основе других свойств (column-count, column-gap).
column-width

Задаёт оптимальную ширину колонки в многоколоночном тексте. Реальная ширина колонки может быть больше введённого значения, сокращение указанной ширины приводит к отмене нескольких колонок, текст при этом выстраивается в одну колонку.


text:
Q: Style the first few characters of text along a path How can this code be modified so that the first few characters (say 3) are colored red?
\documentclass[tikz]{standalone}
\begin{document}
\usetikzlibrary{decorations.text,calc,math}
\begin{tikzpicture}[
    scale=10,
    decoration={
        text effects along path,
        text={0123456789},
        text effects/.cd,
        character count=\i, character total=\n,
        characters={text along path,
                    evaluate={\c=(\n-\i)+1;},
                    scale=10*\c/\n,
        }
        }
    ]
    \draw[decorate]
          plot (0,0) -- (1,0);
\end{tikzpicture}

\end{document}

A: I think this is not a good answer ..... But it works.
\documentclass[tikz]{standalone}
\usepackage{xcolor}
\begin{document}
\usetikzlibrary{decorations.text,calc,math}
\begin{tikzpicture}[
    scale=10,
    decoration={
        text effects along path,
        text={{\color{red}0}{\color{red}1}{\color{red}2}3456789},
        text effects/.cd,
        character count=\i, character total=\n,
        characters={text along path,
                    evaluate={\c=(\n-\i)+1;},
                    scale=10*\c/\n,
        }
        }
    ]
    \draw[decorate]
          plot (0,0) -- (1,0);
\end{tikzpicture}

\end{document}

The color has to be set for each character.


text:
Q: dist-upgrade crashed, all files are now in my home directory I finally decided to upgrade from ubuntu 15.x to 16.x LTS on an old laptop, using the "do-release-upgrade" command. Of course things didn't went smoothly, the process has frozen somewhere near the end, probably while doing some kind of indexing of my old files.
The upgraded ubuntu version appears to work well (although only tested quickly), however all folders are given empty and it looks like all files are now in the Home directory, i.e. +500k files agglomerated in a single directory, quite a mess.
Is there any way to re-build the data-tree ? I suppose a mapping should exist somewhere.
I have tried the sequence
sudo apt-get update
sudo dpkg --configure -a
sudo apt-get dist-upgrade

Tells me that everything is fine.
Thanks


text:
Q: AC in Countable Union of Countable Sets If I understand correctly, AC is not needed in the case of a finite union of countable sets because the choice function can be built with recursion, using the case of 2 sets (which is straight-forward).
However, why is AC needed in the case of $\omega$ countable sets (or $\alpha$  infinite (well-ordered) sets, for $\omega\leq\alpha\in\text{Ord}$)?
If we take the choice function $G$ to be $\bigcup_{n<\omega}G_n$, where $G_n$ is the choice function for the case of $n$-sets union, such that $\forall m<n \;\; G_m\subseteq G_n$, then $G$ will also be a function and a choice function.
Where's my mistake/where do I implicitly use AC?
Thanks


text:
Q: Passing Data from Recycler View to new Activity in a Quote Application,new activity is opening but data not coming I'm creating a Quote Application where quote will be inside recycler view ,and on click same quote
will appear on which user clicked.As I tried using on Click Listener inside View Holder in Adapter
Class,app activity changed to other,but data not showing.
 My Adapter Class.

                 public class QuotesAdapter extends RecyclerView.Adapter<QuotesAdapter.QuotesViewHolder> {

List<String> quotes = null;
Context context;

public QuotesAdapter(List<String> quotes, Context context) {
    this.quotes = quotes;
    this.context = context;
}

@NonNull
@Override
public QuotesViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.list_item_quote, viewGroup, false);
    return new QuotesViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final QuotesViewHolder quotesViewHolder, int i) {
    String[] colors = {"#448AFF", "#FFC107", "#009688", "#E91E63", "#FF5722"};
    final String quote = quotes.get(i);
    quotesViewHolder.txtQuote.setText(quote);
    int color = i % colors.length;
    final int intColor = Color.parseColor(colors[color]);
    quotesViewHolder.quoteContainer.setBackgroundColor(intColor);

}

@Override
public int getItemCount() {
    return quotes.size();
}

public class QuotesViewHolder extends RecyclerView.ViewHolder {

    TextView txtQuote;
    LinearLayout quoteContainer;

    public QuotesViewHolder(@NonNull View itemView) {
        super(itemView);
        txtQuote = itemView.findViewById(R.id.txtQuote);
        quoteContainer = itemView.findViewById(R.id.quoteContainer);
    }
}
 }

MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView quoteList = findViewById(R.id.quoteList);
    quoteList.setLayoutManager(new LinearLayoutManager(this ));
    quoteList.setAdapter(new QuotesAdapter(getQuotes(), this));

}

private List<String> getQuotes(){
    List<String> quotes = new ArrayList<>();
    BufferedReader bufferedReader = null;

    try {
        bufferedReader = new BufferedReader(new InputStreamReader(this.getAssets().open("quotes.txt"), "UTF-8"));
        String line;
        while ((line = bufferedReader.readLine()) != null){
            quotes.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if(bufferedReader != null){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return  quotes;
}

}

A: On your itemClick in adapter use bundle to pass data
Intent intent = new Intent(context, NewActivity.class);

intent.putExtra("myKey", AnyValue);
startActivity(intent);
You can get the passed values by this way:
Bundle extras = intent.getExtras();

String myString = extras.getString("myKey");


text:
Q: Multiple Django sites in Apache and DJANGO_SETTINGS_MODULE I'm currently trying to host 2 isolated Django web applications in one Apache instance. They work, however at random times a 500 HTTP error is raised.
Apache's logfile reveals that sometimes application A tries to load settings from application B, which means that the environment variable DJANGO_SETTINGS_MODULE gets messed up between both applications.
I tried to run both sites embedded and in daemon mode, no success. Any ideas?


text:
Q: Как правильно делать запросы на сокет сервер? У меня есть сокет-сервер на php, и я в js подключаюсь к нему и делаю определенные запросы, чтобы они в риалтайме выполнялись, и мне отсылался ответ. Иногда нужно, чтобы сервер сам отправлял мне сообщения, т.е. без моего запроса, поэтому ajax мне не подходит. И вот я делаю запрос таким образом:
let sendData = {
    type: 0,
    .. и какие-то параметры ..
};

Так вот type нужен, чтобы сервер понимал, что нужно с полученной информацией делать.
Например, если type = 0, то удалить пользователя с определенным именем, которое будет передано вместе с type:
let sendData = {
    type: 0,
    name: "Alex"
};

И принимаю я все ответы от сервера ровно таким же способом. Смотрю на type и понимаю, что делать. Такой метод я придумал сам, т.к. в первый раз работаю с сокет-сервером. Мне интересно, насколько такой подход правильный.


text:
Q: Multer req.file is undefined and directory created but image not there I simply have this on my server
const storage = multer.diskStorage({
  destination: "public/something/images",
  filename: function (req, file, cb) {
    console.log(file, "file?");
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

var upload = multer({ storage: storage });

app.post("/upload", upload.single("file"), (req, res) => {
  console.log(req.file, "req?"); // this is undefined?
  console.log(req.files.File, "req?"); // this is the correct file. why does the line above not work?
  res.json({ file: req.file });
});

on my frontend I have:
<input type="file" name="file" onChange={changeHandler} />
public/something/images does get created but the image is not inside it, why is this happening?
request:
  const endpoint = () => {
    const formData = new FormData();

    formData.append("File", selectedFile);

    fetch("http://localhost:4000/upload", {
      method: "POST",
      body: formData,
    })
      .then((r) => r.json())
      .then((a) => console.log(a));
  };


text:
Q: How to add @XmlTransient in Hibernate Java obj I have a Java bean generated by Hibernate:
I want to make certain fields @XmlTransient so in the XML SOAP Request so the user doesnt have to fill them in like:
// Generated Feb 25, 2020 9:19:29 AM by Hibernate Tools 3.1

String WarriorID = "";
@XmlTransient
Name name = null;
@XmlTransient
int HPStat = -1;
@XmlTransient
int MPStat = -1;

so in my SOAPUI I expect it to appear like
<warriorID> </warriorID>

where the other fields will not be included/seen.
So I downloaded xml-apis.jar from mvnrespository so I can call upon this annotation.
The problem is after including the xml-apis.jar in my BuildPath, Eclipse still underlines the command in red implying that it doesnt know that annotation:

What am I doing wrong?
This is a webservice which will be consumed by a SOAP Client later.
I also cant use @Transient
Thanks for the help.

A:
What am I doing wrong?

As already stated in my comment, you're importing the wrong jar. There are a couple of online services that help in finding all jars that contain a certain class, e.g. http://findjar.com (ideally you'd refer to the documentation related to that class first).
Using that service you'll see that the jars containing javax.xml.bind.annotation.XmlTransient are mostly named jaxb-api.jar or have the keyword bind on their names: https://www.findjar.com/class/javax/xml/bind/annotation/XmlTransient.html
Additionally, if you're having problems even after importing the jar you think you need, you can peek inside that jar with some zip viewer (e.g. 7zip). That way you should be able to see that xml-apis.jar contains folders javax/xml/parsers and javax/xml/transform but no javax/xml/bind - so it must be the wrong file.
Btw, "I downloaded xml-apis.jar from mvnrespository" sounds like you're handling dependencies manually. If that's the case I suggest having a look into build tools such as Maven or Gradle.


text:
Q: What are the license terms of Microsoft products that are no longer supported? What are the license terms of Microsoft products that are no longer supported? Like Windows 98 or Microsoft Money?

A: See this post on Abandonware from Wikipedia:

Abandonware are discontinued products for which no product support is available, or whose copyright ownership may be unclear for various reasons. Abandonware may be computer software or physical devices which are usually computerised in some fashion, such as personal computer games, productivity applications, utility software, or mobile phones.

Consider giving the article a deeper read...Also consider checking out Microsoft's own website (thanks @Linker3000).
This in no way, shape, or form states Microsoft's license terms on their old products - just a general read for your information.

A: Many Microsoft products that have reached end-of-life continue to be sold as part of an MSDN subscription.  For instance, Windows 3.1 (released in 1992), MS-DOS (1981), Office 95 (1995), and Visual Basic 2.0 (1992) can all still be purchased in this fashion.
Unlike most abandonware, where the company that sells the products are long gone, Microsoft is of course still around to enforce their copyrights.  Therefore, use of their software is still governed under the End User License Agreement those products were shipped with.
While I doubt they'll be adding Windows Genuine Advantage activation features to Windows 3.1, if you're caught using unlicensed Microsoft software in a business setting, you'll certainly still face stiff penalties no matter how old the software is.
If you want to legally acquire such software, check places like eBay, other sites that sell used software, or your local flea market or thrift store.  You can also purchase an MSDN subscription if the software you want is included with that (Excel XLSX).

A: Admittance of "no support", is also legal grounds for claims of "confessed abandonment". Like leaving your car on the side of the road and filing an admittance of abandonment form, such as "being totaled". You may still have rights and obligations to the vehicle, but you no longer have any rights to enforce legal-claims against anyone who tampers with that vehicle, from that point in time.
Placing an ad in a newspaper for that item to be sold, which you have publicly and legally admitted to, as being "unsupported", or "abandoned", does not return or extend any of those rights back to you.
However, they are the only ones who can "legally give selling rights for any windows software", as per the copyrights which they still hold. They have rarely ever enforced the "sale and distribution of second-hand software", and there have only been a few enforced "distributions of illegal software", from microsoft. (They tend to focus on people distributing millions of copies, and the legal copyrights are more for the "businesses" and "corporations", which will not allow anything other than "legally obtained software rights".)**
** This is mostly the logo and some co-dependant code which microsoft still has rights to. Since the language still exists as VBA, much of the actual code is still protected, but they give that away for free, to "USE", which includes use for compiling code. (You just can't make a MYVB6 program with their code, as a MSVB6 replacement program, and then try to sell it as the "New Microsoft VB6".)
Some guy, sitting at home, using an abandoned and unsupported program to make programs that no-one may ever see... Totally not a concern of microsoft at all.
If you want to play the legal-loop-hole... Post the code as open-source and let anyone-else compile it. Then simply download the compiled version. (They will have no idea who actually compiled it, even if you compile it yourself. It is not like it attaches your license info to the compiled code.)
Legally, if you have the registration-code, you can obtain the software from any source you desire. You have the "rights" to that software.
That is why they can't say you are doing anything illegal, when simply downloading a torrent or file... They don't have proof that you DON'T have rights to download it, and that is against the law to even imply, without actual proof that you don't have the rights. (Innocent until proven guilty. Only a judge can order an actual legal "cease and desist order", which actually requires that proof to be presented. Any other warning is just letters on scrap paper. Even directly from your ISP, or Microsoft themselves.)

A: An MSDN Subscription covers use for development and testing. It doesn't cover commercial usage.
The legal status of abandonware has not been tested in court. The claim is that when a product is no longer available for purchase the copyright no longer applies. This may be true but we don't have code cases to be certain.
The only way that we will know the legal status of Abandonware is if someone start for example selling computers with windows 3.11 or 95. If Microsoft do nothing about it well they have to act within some limited amount of time. The best thing that can happen is that they do sue and it gets taken to court. Then we have the chance of getting clarifications from the legal system.
The legal opinion we have is to make clones. FreeDOS is a clone of Microsoft DOS. Dosbox emulates DOS as well as the hardware required to run it (faster than running DOS in a PC emulator). FreeBASIC is a clone of QuickBasic. Wine is a compatibility layer that run many Windows applications on various current operating system. ReactOS is an open source implementation of Windows 2003. Lazarus is an implementation of Delphi. These all have various degrees of completeness.
There are no effort to clone Windows 95 as far as I know. Nor is there any attempt to clone Microsoft Money. The closest you have to Windows 95 would be Wine.
ReactOS regularly do fundraising. But the interest in having a Windows NT revival has not been sufficient to obtain the amount of resources required to make it even close to replace Any version of Windows XP.
To make a clone of Microsoft Money would actually not cost that much. It's far easier than making ReactOS, Wine or even FreeDOS.
Not being a Microsoft product Lazarus is still worth mentioning. It's an implementation of Turbo Pascal/Delphi. It has an Object Pascal compiler that's very capable and supports more platforms than the current version of Delphi. And instead of the Visual Class Library (VCL) it has the Lazarus Class Library (LCL). As many other open source clone it lacks many of the Delphi features but has the advantage of running on many platforms and compiling code to even more.
This is what I would do if I really wanted to replace Windows 95 and Microsoft Money. For Windows 95 I would just drop that. I would take another OS and modify it to have the required features and software. For it to be legal you must clone all the Windows 95 software that you want to run so you don't need to be compatible.
Now the $5 Raspberry Pi Zero should have been more than sufficient hardware for a Windows 95 clone. So if striving for low cost hardware that's what I would go for. This means that Linux would have to be slimmed down to run as well as windows 95 would have run. That will cost but not as much as making a new OS from Scratch.
Then id use Lazarus and make a Windows Shell replacement that run on Linux. This would replicate the look and feel of the product. Potentially Wine can be used to run ARM PE binaries so it's possible to make the experience very close to Windows.
As for Microsoft Money that could rather easily be cloned with Lazarus. While Lazarus cannot make Windows 95 compatible binaries as it requess Unicode well there are two approaches for this. If you really want Windows 95 support then this must first be implemented in Lazarus. Probably by implementing the missing Unicode support which wouldn't be to difficult. Or you just drop that and support the many platforms that Lazarus so support. I would estimate that hiring good freelancers to do this would cost less that $100k. That's not free but you then have an unlimited license. So you can sell copies of your clone or publish it as free open source software.
There are also other options like using Java, Delphi, C# etc. But some of these options may leave you without currentat and supported development tools at some point in the future. Have is open source but Delphi isn't and C# is partially open source. C++ and Qt may actually be the best option for long term support although it will increase the initial development cost.


text:
Q: Can't compile std::map sorting, why? This is my code:
map<string, int> errs;
struct Compare {
    bool operator() (map<string, int>::const_iterator l,
        map<string, int>::const_iterator r) {
        return ((*l).second < (*r).second);
    }
} comp;
sort(errs.begin(), errs.end(), comp);

Can't compile. This is what I'm getting:
no matching function for call to 'sort(..'

Why so? Can anyone help? Thanks!

A: Maps are, by definition, sorted by their keys, so you can't resort a map by its values.
You can provide an alternate comparison function as the third template parameter to a map, if you want to sort the keys by a non-default order.
If you're trying to sort a map by its values, then perhaps you could try using Boost.MultiIndex to make a bidirectional map instead?

A: I assume you are doing using namespace std;. In that sort method requires the iterators to be random access iterators. But map iterators are bidirectional, so it will not compile.

A: This is probably because a std::map has a non-assignable iterator.
std::map has an invariant that is Strictly ascending order, it is always sorted by key.
Read more about it here:
http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html
and note 1 here:
http://www.sgi.com/tech/stl/Map.html

A: You can't sort a map. It has its own sort order, defined at construction time either as the default (use <) or a passed in comparator.

A: In addition to Marcelo's answer: The predicate used by std::sort should take values, not iterators as input.

A: As stated Marcelo you can't sort a map with std::sort you need to define the sort method in the constructor i believe is value_compare.
struct Compare
{
bool operator()(const char* a, const char* b) const
{
return strcmp(a,b) < 0;
};
std::map<char, char, Compare> compareMap;

A: The Compare template parameter takes map keys to compare (or references to keys), not the iterators. Also, the std::map takes that type at instantiation and is sorted automatically by the key (the most common implementation is the red-black tree).
Take a look at boost::multi_index for multi-key access.


text:
Q: Passing function as a parameter in invoke method of system.reflection I have got a variable which contains function hierarchy like:
string str= "fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()))"

// this hierarchy is coming as a string from database
I have imported System.reflection and used invoke method to invoke it, but it's only working if I have a only one function fun1.
With above function hierarchy it's taking complete expression as a one function name.
I am using this below code to invoke my function hierarchy:
public static string InvokeStringMethod(string typeName, string methodName)
{
// Get the Type for the class
Type calledType = Type.GetType(typeName);

// Invoke the method itself. The string returned by the method winds up in s
String s = (String)calledType.InvokeMember(
                methodName,
                BindingFlags.InvokeMethod | BindingFlags.Public |
                    BindingFlags.Static,
                null,
                null,
                null);

// Return the string that was returned by the called method.
return s;
}

Reference: http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx
Please tell me what should I do?

A: The problem is the line
string str= fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));

does not represent an expression, or what you call a 'function hierarchy'. Instead, it executes the right-hand side of the assignment evaluates into a string value.
What you are probably looking for is this:
Func<string> f = () => fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));
…
string result = f();

Here, ´f´ is a delegate into which you assign a lambda expression (anonymous method) that can later be executed by invoking the delegate f.


text:
Q: PHP mail() does not work on digitalocean ubuntu 16.04 server my tools:
server= digitalocean
domain= godaddy
installed
apache/2.4.18
php 7.0.30
ubuntu 16.04
i have tried install sendmail and configure it as below:
sudo apt-get install sendmail

and configure the /etc/hosts
sudo nano /etc/hosts

i am sure it contains 127.0.0.1 localhost localhost.localdomain myhostname
and i made
sendmailconfig

yes for all questions in sendmail config.
also restarted apache2 with
sudo service apache2 restart

it is not sending mail. can u help me?
i tried send mail with send.php
it contains:
<?php
$to = 'sendto@outlook.com';
$title = 'title of mail';
$content = 'hello from world';
$titles = 'From: sendfrom@outlook.com' . "\r\n" .
    'Reply-To: sendfrom@outlook.com' . "\r\n" .
    'X-Mailer: PHP/' .phpversion();
mail($to, $title, $content, $titles);
?>

A: Digitalocean has shared ip for users therefore, outlook, gmail etc. put it in the blacklist. In summary, mail() function works but does not deliver the mails.


text:
Q: Azure FQDN to AKS Load Balancer static IP keeps disappearing A couple of weeks ago, I set up a Load Balancer on an AKS Cluster. I am using the following script to point a .cloudapp.azure.com domain to the Load Balancer:
#!/bin/bash

# Public IP address of your ingress controller
IP="<MY_IP>"

# Name to associate with public IP address
DNSNAME="<MY_DNS_NAME>"

# Get the resource-id of the public ip
PUBLICIPID=$(az network public-ip list --query "[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[id]" --output tsv)

# Update public ip address with DNS name
az network public-ip update --ids $PUBLICIPID --dns-name $DNSNAME

The problem is that the FQDN keeps disappearing, approximately every 24 hours. Every day I have to run the script again, and then everything is alright again. Why could this be happening?
I have assigned a static IP to my Load Balancer, which also has not restarted. I used the following command to assign a static ip:
az network public-ip create --resource-group <MY_RG> --name <IP_NAME> --sku Standard --allocation-method static --query publicIp.ipAddress -o tsv

and used this IP in my charts for the nginx controller. The IP keeps pointing to the right place but the domain name keeps disappearing.
Thank you in advance for any advice, greatly appreciated.


text: Q: Importing jars and compile them using maven We use maven to download and compile classes without importing those libraries in our build path. But when we want to use some classes from an external API, we still need to import those jars to our build path? Why is that and what's the reason for that?


text:
Q: How to retrieve data from firebase database without DataSnapshot? #AskFirebase This my database in firebase

I want to get the value of page which is equal to 200.
When I tried like that:
DatabaseReference my= userid_database.child("Books").child("Book 1").child("Page");

    System.out.println(my);

Output:
https://my-proje-book-timer.firebaseio.com/qpPLvgpM0TMF6vz4Kqw8QaYroG83/Books/Book%201/Page

When I tried like that:
DatabaseReference my= userid_database.child("Books").child("Book 1").child("Page").getKey();

    System.out.println(my);

Output:
Page

I don't want to use this:
 my.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String text = dataSnapshot.getValue(String.class);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Because I want to get all values for each Book pages and make a calculation with these values. In this way, I couldn't get the values outside of the method.

A: If you don't want to use a listener, you can use the REST API to easily make an HTTP query to find the data you want, assuming that it's readable without authentication.  If you need authentication, it gets more difficult.
But you're really better off just learning now to make the listeners work for you, even if you're not accustomed to that kind of processing.


text:
Q: Is using reflection a design smell? I see a lot of C#, .net questions solved here using reflection. To me, a lot of them look like bending the rules at the cost of good design (OOP). Many of the solutions look unmaintenable and "scripty".
Is using reflection a good practice in general?
Are there things that can only be solved by reflection?
edit:
Please give examples where reflection is the only good solution.

A: I wouldn't say that using reflection is a design smell. It is an useful feature of the framework that makes the statical languages a little more dynamic. Now from practical point of view I try to avoid reflection if I can solve my problem without it.

A: Conceptually, reflection is a powerful tool to use as a gateway from non-code into code as well as a polymorphic tool.
For example...

*

*taking a string representation of a
type and turning it into an object.

*not hardcoding frameworks or plugins
together.

*dynamically using objects from
different assemblies without knowing
what they are in advance.

*serializing data without writing
dedicated code to do it.

Used properly it's an ingenious tool to take code to the next level of reusability and flexibility. Nothing wrong with that.
The only time it's a design smell is when it's being used to do something that conventional functionality already covers. (i.e., you wouldn't want to use Reflection to get the values of a DataRow or something).

A: In my humble opinion, reflection should be a last resort. Reflection makes code really difficult to understand by merely looking at it since the semantics of the language can be altered in very odd ways.
I would consider it a smell. Maybe not bad practice, but something that would raise an eyebrow.

A: Examples:

*

*Dynamic loading of types via configuration

*Using "convention" style registration (register components with your container that implement an interface or have a certain naming convention)

*Checking for/using custom attributes/type metadata

Reflection is a tool, like "throw".  should you use throw everywhere? No!  So is it a code smell to use throw?

A: With great power come great responsibility,  reflection is a very powerful tool and when used properly very good, when used improperly it's very bad, the trick is to know when your over using it

A: As with any other technology, if you focus too much on it you may start applying it to the wrong kind of problems.
There are however things that simply are not possible without reflection; any kind of general serialisation is a prime example. Another would be any kind of plug-in framework that does not at compile time have access to all the classes it may need to work with at run-time.

A: Reflection lets you examine at runtime the same information used by the compiler at compile time. Consequently, anything you can do with reflection can be done without reflection during compilation. This doesn't mean reflection has no use: you may not know what exact question you want to ask until runtime.
If you know something at compile time, express it in the type system. This will allow you to catch mistakes at compile time. For example,
string propVal = myObj.SomeProperty;

Here we are saying that we know for sure at compile time that myObj has a property called SomeProperty that is of a type that is assignable to string - and in fact, although it isn't visible here, we must also have specified a class or interface type of myObj.
string propVal = (string)myObj.GetType()
                       .GetProperty("SomeProperty")
                       .GetValue(myObj, null);

Here we are saying that myObj might have that same property - or it might not (in which case we'll get an exception at runtime).
The second one, using reflection, looks butt-ugly, but in C# 4.0 it will look practically identical. It is often held to be slower too, but that depends on the context, and will probably be less true of the dynamic features in C# 4.0.
The real distinction remains, though: the statically typed version helps us find mistakes during compilation, instead of delaying this discovery until runtime.
So if you want to make full use of the static type system to catch bugs during compilation, then try to state your assumptions via the type system, which is equivalent to saying: avoid reflection except where really necessary.

A: There are some problems which can be solved only with reflection, but I think that it can and maybe should be avoided wherever it is possible to. C# is a static and type-safe language, so use this advantages. Using reflection is often quite error-prone, I think.

A: like all things the answer is "it depends"
A valid use of reflection is in frameworks, for example a plugin framework might make use of Attributes for declaring plugin classes, Testing and Mocking Frameworks are another example.
But I would agree that generally speaking in a line of business app, most of the time it would be a "code smell" (not always though....)

A: One nice use of reflection is when you want to implement an add-in architecture.  You need some way to specify "here's a DLL, go load it and try to instantiate a type".  You don't know the type before hand; all you know is that there is some interface in there that you can access.  The only way to do this is with reflection.
Our application has a large number of modules you can run inside it.  Rather than hard-coding a list of classes we need to launch when you select a module, we have a data table that lists the name of the module's DLL and a class to run from it.  This way, when we need to add a new module, we just need a new entry in the table.  The code that launches the modules doesn't change.

A: Programming is all about building abstractions. Reflection is a very powerful tool to build abstractions. So no, if it leads to less code that is easier to understand, I wouldn't say it's a design smell.

A number of you have pointed out that reflection has a place in frameworks, testing, mocks etc. How about in line-of-business applications?

In my experience, when you write a line-of-business application of some size, you inevitably end up writing your own domain specific framework and libraries. That's where reflection has it's place.

A:
To me, a lot of them look like bending
  the rules at the cost of good design
  (OOP). Many of the solutions look
  unmaintenable and "scripty".

Honestly, "good design" has little to do with OOP. I'd say a far bigger design smell to be concerned with is the belief that good design is exactly equal to OOP. That we can't have good design without OOP, and that we can't follow the rules of OOP without it  becoming good design. It's almost as bad as people's obsession with "smells". Programmers should use their brains, not their noses.

Is using reflection a good practice in
  general? Are there things that can
  only be solved by reflection?

The way I see it, reflection is mostly a symptom of language shortcomings. Ideally, a language should allow you to do what you want without "bending the rules" through reflection. But most don't, and C# definitely doesn't, so reflection is occasionally your only sensible choice.
There are plenty of "correct" uses of reflection. Dynamically loading types/libraries would be an obvious one. Or inspecting attributes. Most unit testing frameworks depend on reflection as well, which is fine, because they have to be a bit intrusive in order to be easy to use and gain access to the code we wish to test.
But most user code which performs some kind of type inspection, testing at runtime whether a type implements a certain interface or has a certain member function, is a sign of something that, in an ideal language, shouldn't be necessary.
If you want to consider it a smell, call it a language smell, not a design one. (Of course it can be overused in design as well, but where I most often encounter it, it's a necessity because of the lack of expressiveness of the language)

A: Reflection is sometimes the only way to do certain things.  It is a very powerful tool that can at times be overused by someone that knows reflection really well but perhaps not something else.  An over use of reflection when something else will work better might be a design smell...but more often likely just bad coding.

A: Once had a program that processed files (how generic is that description)
By using reflection all you had to do was drop in a DLL into a folder, the app would pick that up and use reflection to look for classes that implemented a certain interface and check some attributes. There was no need for config files. Just drop and go, which was handy for a production system as we didn't require any downtime.
As with most solutions. there are a number of other ways to achieve the same purpose, but reflection did make this quite easy.

A: Well, clearly reflection APIs are there because they fill a need, and there are some problems that can only be solved with the use of reflection. Basically, reflection is needed when decisions need to be made in your code based on type information which is available only at runtime but not at compile time.

A: Sometimes it actually improves the reusability of code.  As a particular example, I once wrote a program for importing a csv into a database.  Using an ORM to create classes for the tables, then reflecting on these, I was able to create an importer where only exceptional situations had to be noted, and adding a column may not have required anything other than adding it to the db table, and knowing it exists in the file.
But as others have stated, it's mostly an issue of correct use.

A: Anyone can see benefits of using reflection, and I think reflection can help you achieve better design and especially OOP design concepts without writing much more code.
For example, you can build loosely coupled layers that depend on abstraction and use reflection to control behavior specific to instances at runtime.
Most obviously: generalized UI layers/components.
Flexibility and productivity of ASP.Net MVC and Dynamic data are just an example also you can see GridView as one too.

A: I'm in the middle of a project that uses (for my first time, ever) Reflection.  I have to admit, it doesn't look very good.  Normally I strive for very minimal commenting, in the belief that code should be self-commenting to the max extent possible, but with this project I am adding frequent comments; this is both to explain what's going on to the next developer who may have to maintain the code, and as "thinking out loud" for my own benefit.
Bottom line:  if it doesn't look obvious, add comments.  Always think about the person who comes after you who may have to deal with your mess.  Reflection can look messy, so comment accordingly.

A: No its a heavy use of reflection by the dot net framework itself that has earned it so much popularity
use
F# heavily uses reflection

A: All reflection does is let you observe types at runtime.  If you are a hack I suppose you could potentially code up some Rube Goldberg contraption with it, but the same can be said of a lot of other techniques.
Many core features of the framework, such as attributes, wouldn't work at all without reflection.

A: No, Reflection is not a design smell. It could, arguably, be called a "language/platform smell".
Reflection is used because code and code metadata are both stored in the assembly. Thus, they are always updated and in synch. You can code general conventions on metadata rather than being explicit on the common case.
For modularity in .NET, it is a great benefit that modules are self-describing.
This may be due to my own personal development as a programmer, but I find that learning reflection advocates a sorely needed attention to the deliverables (assemblies). Along with TDD, of course.

A: This is one of the stinkiest of smells.  A language that is "fully closed" has no need for reflection.


text:
Q: Are android fragments reusable? Are android fragments reusable - i mean if i could use code like below:
class MyTabActivity extends FragmentActivity implements OnClickListener {

    Fragment[] tabs = new Fragment[3];

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.settings_activity);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);

        //first xml-defined fragment, it is inside
        //FrameLayout with id R.id.loadTarget -> see openTab()
        tabs[0] = getSupportFragmentManager().findFragmentById(
                R.id.firstFragment);
    }

    private void openTab(int i) {
        final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.loadTarget, getTabFragment(i));
        ft.addToBackStack(null);
        ft.commit();
    }

    private Fragment getTabFragment(int i) {
        if(tabs[i] == null) {
            switch(i) {

                //0-tab fragment has been allready
                //retrieved in onCreate

                case 1:
                    tabs[1] = new MySecondTabFragment();
                    break;
                case 2:
                    tabs[2] = new MyThirdTabFragment();
                    break;
            }
        }
        return tabs[i];
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.button1:
                openTab(0);
                break;
            case R.id.button2:
                openTab(1);
                break;
            case R.id.button3:
                openTab(2);
                break;
        }
    }
}

A: Yes fragments are reusable you can attach/detach a fragment to an activity several times. As you can see in the documentation after being detached the fragment is destroyed and then created again when it is added to another activity.


text:
Q: Time complexity modified bubblesort Have this java code for bubblesort:
public void sort() {
    for(int i = 1; i < getElementCount() ; ++i) {
        for(int j = getElementCount()-1; j >= i; j--) {
            if (cmp(j,j-1) < 0) swap(j, j-1);
        }
    }
}

the method "cmp" and "swap" are as follows:
public int cmp(int i, int j) {
    return get(i).intValue()-get(j).intValue();
}

public void swap(int i, int j) {
    Integer tmp = get(i);
    set(i, get(j));
    set(j, tmp);
}

I have now written an improved version of the Bubblesort where the sorting method "sort()" looks like this:
public void sort() {
    boolean done = false;
    for(int i = 1; i < getElementCount() && !done; ++i) {
        done = true;
        for(int j = getElementCount()-1; j >= i; j--) {
            if (cmp(j,j-1) < 0) {
                swap(j, j-1);
                done = false;
            }
        }
    }
}

Can anyone explain how to compute the time complexity of the latter algorithm? I'm thinking it's comparing n elements one time, and therefore it has complexity O(1) in its best case, and O(n^2) in it's worst case scenario, but I don't know if I'm right and would like to know how to think on this issue.

A: The complexity tells the programmer how long time it takes to process the data.
The O(1) complexity says that no matter how many elements it will only take one operation.
Insert a value in an array would have O(1)
E.g.
array[100] = value;

In your best case you will have to loop throught the entire array and compare each element.
Your complexity code is then O(n) where n is number of elements in the array.
In the worst case you will have to run through the array once for each element, that would give a complexity of O(n*n)

A: I just looked over what you've done and it is exactly the same as the one you had previously listed. You have set a boolean condition done = false and then you are checking the negation of it which will always evaluate to true - exactly the same logic as before. You can remove done in your code and you will see that it runs exactly the same. Just like before, you will have a best case complexity of O(n) and a worst case complexity of O(n^2). There is no way any sorting algorithm is O(1) as at the very least you at least have to move through the list once which gives O(n).

A: Worst Case : If the array is sorted in the sorted reverse order (descending) , it will show the worst time complexity of O(N^2).
Best Case : If the array is in sorted order, then the inner loop will go through each element at least once so it is O(N) - > (If you break out of the loop using the information in done, which is not present in the code).
At no point can it be a O(1) (In fact it is mathematically impossible to get a lower function than O(N) as the lower bounds for sorting is Omega(N) for comparison based sorts)
Omega(N) is the lowest possible function, as for comparison you have to see all elements at least once.

A: The best way is to represent your loops using Sigma notation like the following (General Case):

'c' here refers to the constant time of if, cmp, and swap that execute inside the innermost loop.
For the best case (modified bubble sort), the running time should look like this:


text:
Q: Vega transform to select the first n rows Is there a Vega/Vega-Lite transform which I can use to select the first n rows in data set?
Suppose I get a dataset from a URL such as:

Person
Height

Jeremy
6.2

Alice
6.0

Walter
5.8

Amy
5.6

Joe
5.5

and I want to create a bar chart showing the height of only the three tallest people. Assume that we know for certain that the dataset from the URL is already sorted. Assume that we cannot change the data as returned by the URL.
I want to do something like this:
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "heights.csv"
  },
  "transform": [
      {"head": 3}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "Person", "type": "nominal"},
    "y": {"field": "Height", "type": "quantitative"}
  }
}

only the head transform does not actually exist - is there something else I can do to get the same effect?

A: The Vega-Lite documentation has an example along these lines in filtering top-k items.
Your case is a bit more specialized: you do not want to order based on rank, but rather based on the original ordering of the data. You can do this using a count-based window transform followed by an appropriate filter. For example (view in editor):
{
  "data": {
    "values": [
      {"Person": "Jeremy", "Height": 6.2},
      {"Person": "Alice", "Height": 6.0},
      {"Person": "Walter", "Height": 5.8},
      {"Person": "Amy", "Height": 5.6},
      {"Person": "Joe", "Height": 5.5}
    ]
  },
  "transform": [
    {"window": [{"op": "count", "as": "count"}]},
    {"filter": "datum.count <= 3"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "Height", "type": "quantitative"},
    "y": {"field": "Person", "type": "nominal", "sort": null}
  }
}


text:
Q: Easy way to share profile configuration among profiles in Maven? I have a maven profile defined like so;
<profile>
            <id>instrumentation</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <property>
                    <name>instrumentation.enabled</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>cobertura-maven-plugin</artifactId>
                        <version>2.5.1</version>
                        <configuration>
                            <formats>
                                <format>xml</format>
                                <format>html</format>
                            </formats>
                            <instrumentation>
                                <ignores>
                                </ignores>
                                <excludes>
                                    <exclude>**/Test*.class</exclude>
                                    <exclude>**/Abstract*.java</exclude>
                                    <!-- Log Classes -->
                                    <exclude>**/Log.class</exclude>
                                    <!-- Exception Classes -->
                                    <exclude>**/*Exception.class</exclude>
                                </excludes>
                            </instrumentation>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>cobertura</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>2.6</version>
                        <executions>
                            <execution>
                                <id>copy-resources</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>copy-resources</goal>
                                </goals>
                                <configuration>
                                <!-- this is important -->
                                    <overwrite>true</overwrite>
                                    <!-- target -->
                                    <outputDirectory>${env.DERBASE}/java/${project.artifactId}/target/classes</outputDirectory>
                                    <resources>
                                        <resource>
                                        <!-- source -->
                                            <directory>${env.DERBASE}/java/${project.artifactId}/target/generated-classes/cobertura</directory>
                                        </resource>
                                    </resources>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

So what I would like to do is to change this line;
<goal>cobertura</goal>

to this;
<goal>instrumentation</goal>

If an env variable such as INSTRUMENTATION_EXCLUDE_TESTS is set.
I'm just wondering what the best way to accomplish this is? (i.e. without just copy and pasting the profile with the single line changed)
Many thanks!

A: So, I solved this by setting an environment variable, which could be either;
export COBERTURA_GOAL=cobertura

or
export COBERTURA_GOAL=instrument

Then, in my pom, defined the following property;
<cobertura.goal>${env.COBERTURA_GOAL}</cobertura.goal>

Which was inserted into;
 <goal>${cobertura.goal}</goal>


text:
Q: NoClassDefFoundError: Unable to run Tycho-built Eclipse RCP application under Linux/Mac OS I'm developing a cross-platform RCP application in Win 7 (64bit), Indigo/Java 1.6, building the product with Tycho.
While the application runs fine from the Run Configuration within eclipse, and the Win x_86_64 build runs fine as well, I get the following errors on both xubuntu (with OpenJDK Java 6 Runtime (1.6.0_24) and Mac OS X (1.6.0_35).
The error (on Linux) looks like this (running java myprogram):
Exception in thread "main" java.lang.NoClassDefFoundError: myprogram
Caused by: java.lang.ClassNotFoundException: myprogram
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: myprogram. Program will exit.

I'm sure I've come across this before, and I think it was something stupid (this has happened on Windows before AFAIK, and re-installing Java fixed it for some reason). In this case, however, I think it must be to do with the build/target platform/Tycho setup.
The part of my parent POM responsible for the cross-platform build looks unsuspicious enough:
    <plugin>
      <groupId>org.eclipse.tycho</groupId>
      <artifactId>target-platform-configuration</artifactId>
      <version>${tycho-version}</version>
      <configuration>
        <resolver>p2</resolver>
        <pomDependencies>consider</pomDependencies>
        <!-- configure the p2 target environments for multi-platform build -->
        <environments>

          <environment>
            <os>linux</os>
            <ws>gtk</ws>
            <arch>x86</arch>
          </environment>
          <environment>
            <os>linux</os>
            <ws>gtk</ws>
            <arch>x86_64</arch>
          </environment>
          <environment>
            <os>win32</os>
            <ws>win32</ws>
            <arch>x86</arch>
          </environment>

          <environment>
            <os>win32</os>
            <ws>win32</ws>
            <arch>x86_64</arch>
          </environment>
          <environment>
            <os>macosx</os>
            <ws>cocoa</ws>
            <arch>x86_64</arch>
          </environment>
        </environments>
      </configuration>
    </plugin>

Does anybody have any ideas why this might not work?
Many thanks!

A: This is not how you run an Eclipse RCP application.
You either need to launch it with the appropriate native launcher, or with a java -jar plugins/org.eclipse.equinox.launcher_(yourVersion).jar (see this documentation) and probably further arguments to select your application.
Also, you need to make sure that you have the bundles in your application that Equinox needs to start up. You can do this by including the feature org.eclipse.rcp in you product.


text:
Q: Add user name with pie chart I am pretty new to pie charts and i have one that displays seconds to hh:mm:ss but I also need the username to be included as well here is my code.
   string easystone = ConfigurationManager.ConnectionStrings["easystone"].ConnectionString;

    SqlConnection con = new SqlConnection(easystone);
    SqlDataAdapter graph = new SqlDataAdapter("SELECT[User] , sum(time) as [time] FROM avgtime3 group by[user]", con);
    DataTable graphdata = new DataTable();
    graph.Fill(graphdata);
    chart1.DataSource = graphdata;
    chart1.ChartAreas["ChartArea1"].AxisX.Title = "";
    foreach (DataRow row in graphdata.Rows)
    {
        int total = (int)row["time"];
        int index = chart1.Series["Series1"].Points.AddXY(row["User"], new object[] { total });
        chart1.Series["Series1"].Points[index].Label = // I need the username to go here.
        chart1.Series["Series1"].Points[index].Label = string.Format("{0:00}:{1:00}:{2:00}", (total / 60) / 60, (total / 60) % 60, total % 60);
    }

A: Prefix the user name along with time.
chart1.Series["Series1"].Points[index].Label = row["User"].ToString() + " : " + string.Format("{0:00}:{1:00}:{2:00}", (total / 60) / 60, (total / 60) % 60, total % 60);


text:
Q: Seminar environment plus psfrag plus TeXshop -- I can't get all three to work together A while ago, I discovered that TeXshop has trouble with producing slides that overflow the right margin in the seminar environment. I found a solution in this thread on latexcommunity -- use pdftex and insert
\setlength{\pdfhorigin}{1truein}
\setlength{\pdfvorigin}{1truein}
\makeatletter
\setlength{\pdfpagewidth}{\strip@pt\paperheight truept}
\setlength{\pdfpageheight}{\strip@pt\paperwidth truept}
\makeatother

I also have been happily using psfrag to decorate my figures. I have just tried to put some of those figures into a set of slides and found that psfrag wasn't inserting the required tex. From some googling, it looks like the key here is to use "TeX and DVI", not Pdftex. I see that this question may have some better answers, but I don't immediately see whether they solve the question.
Here is an example:
\documentclass{seminar}
\usepackage{amsthm, amsmath, amssymb, amsfonts, graphics}
\usepackage{epstopdf, psfrag, pstricks}
\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}

\setlength{\pdfhorigin}{1truein}
\setlength{\pdfvorigin}{1truein}
\makeatletter
\setlength{\pdfpagewidth}{\strip@pt\paperheight truept}
\setlength{\pdfpageheight}{\strip@pt\paperwidth truept}
\makeatother

\begin{document}

\begin{slide}

{
\psfrag{1}{$x$}
\includegraphics{Test.eps}
}

\end{slide}
\end{document}

Create an eps file called Test.eps with the symbol 1 in it. If you compile with "TeX and DVI", the 1 will be replaced by x, but it will overflow the righthand margin. If you compile with "Pdftex", the margins are correct but the 1 is not replaced.
Thanks!

A: Packages that use postscript wizardry such as psfrag and pstricks won't work directly with pdflatex. The packages pstool and pst-pdf help with this, but things can get complicated. My guess is that sticking with `latex-dvips-ps2pdf' is the simplest option. In that case you just need to do
latex seminar
dvips -tlandscape seminar
ps2pdf seminar

to get the proper landscape slides. I don't have TeXShop on this machine, but if you dig around in the menus you will find the commands that it uses to create pdfs, and you should be able to edit these to add -tlandscape.

A: The "if you dig around" step was harder than expected, and last time I gave up and did something else, but I just tried again and figured it out.
These directions are for TeXShop 2.47 on OS X 10.6.8.
Go to TeXShop > Preferences > Engine

You care about the commands in the TeX + dvips + distiller area. If (as I am) you are using LaTeX, then you want to edit the bottom one. As you can see, by default, TeXShop uses simpdftex to produce PDF documents. Your challenge is to pass a command to dvips through simpdftex. To quote the simpdftex man file:
    --dvipsopts

          Give arbitrary arguments to dvips, e.g.  --dvipsopts  "-M"  Sets
          extension  for  --extendedfilename to .custom. --dvipsopts over-
          rides other flags that set dvipsopts.

I therefore edited the second field in the TeX + dvips + distiller area to read
simpdftex latex --maxpfb --extratexopts "-file-line-error -synctex=1"   --dvipsopts "-tlandscape"

The new stuff is --dvipsopts "-tlandscape", everything else was just copying the TeXShop default.
By the way, if you screw up in editing something in this preference box, clicking "default" will restore the original values.


text:
Q: Difference between  and  I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.

*

*I want to know the exact difference between type 'xrange' and type 'generator'

*If xrange is an iterator/generator, it is supposed to have .next() method. I do not understand why the .next() method doesn't work for the case below.
def generator():
    for i in xrange(20): yield i

In the above example,
    numbers = generator()
    for i in numbers:
        if i == 6: break

    for i in numbers:
        if i == 10: break
        print i

    >>> 7
    8
    9

    >>> print numbers.next()
    11

The above functionalities also hold true for a object generator of the type:
    >>> numbers = (x for x in range(100))

If I do with xrange operation, the loop starts iterating from the beginning and there is no next() operation. I know that we can do the smart way of:
    for i in xrange(20):
        if (#something):
            var = i
            break
     #perform some operations
     for i in range(var,20):
         #Do something

But I want to loop to continue after var without using var.
To be short, is there a next() kind of operation for xrange. If yes : 'How?' , else : 'Why?'

A: xrange is an iterable, so you can call iter to get an iterator out of it.
>>> x = xrange(20)
>>> iterator = iter(x)
>>> for i in iterator:
...     if i == 6: break
...
>>> iterator.next()
7

A: First you should note an xrange object is not a generator:
>>> xrange_obj = xrange(10000)
>>> type(xrange_obj)
xrange
>>> gen_obj = (x for x in range(10000))
>>> type(gen_obj)
generator
>>> import types
>>> isinstance(xrange_obj, types.GeneratorType)
False
>>> isinstance(gen_obj, types.GeneratorType)
True

It is an iterable (but not an iterator)
>>> iter(xrange_obj)
<rangeiterator at 0x3e07f930>
>>> iter(xrange_obj).next()
0

Finally, as I don't see it touched upon in the other answers currently, the reason xrange is not a generator but its own type of object is because it supports special methods to make it mimic a range.
>>> xrange_obj[1]
1
>>> len(xrange_obj)
10000
>>> gen_obj[1]
TypeError: 'generator' object has no attribute '__getitem__'
>>> len(gen_obj)
TypeError: object of type 'generator' has no len()

A: Also, you should understand that an iterator and an generator are not the same thing. An iterable is any Python object that implements an __iter__ method that returns an iterator. An iterator also must implement an __iter__ method but also a next method (__next__ in Python 3). So xrange is iterable, but not an iterator. Here is an iterator:
class NumberCounter(object):
    def __init__(self, size):
        self.size = size
        self.start = 0
    def __iter__(self):
        return self
    def next(self):
        if self.start < self.size:
            self.start += 1
            return self.start
        raise StopIteration

In the interactive interpreter:
>>> nc6 = NumberCounter(6)
>>> it = iter(nc6)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
6
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in next
StopIteration
>>> for i in NumberCounter(6):
...     print(i)
...
1
2
3
4
5
6
>>>

A generator is a Python construct that helps you create iterators easily.
From the docs:

Generators are a simple and powerful tool for creating iterators. They
  are written like regular functions but use the yield statement
  whenever they want to return data. Each time next() is called on it,
  the generator resumes where it left off (it remembers all the data
  values and which statement was last executed)... Anything that can be
  done with generators can also be done with class-based iterators as
  described in the previous section. What makes generators so compact is
  that the __iter__() and next() methods are created automatically...In
  addition to automatic method creation and saving program state, when
  generators terminate, they automatically raise StopIteration. In
  combination, these features make it easy to create iterators with no
  more effort than writing a regular function.

Here is a generator:
def number_counter(x):
    curr = 1
    while curr <= x:
        yield curr
        curr += 1

In the interactive interpreter:
>>> for i in number_counter(6):
...     print(i)
...
1
2
3
4
5
6
>>>

Here's another:
def wacky_gen():
    yield 88
    yield 2
    yield 15

Finally...
>>> for i in wacky_gen():
...    print(i)
...
88
2
15
>>>


text:
Q: Row-wise intensiveness histogram The idea is to identify the darkest rows of grayscale image. I have two options:
Option 1: manual calculation
I can calculate row-wise intensiveness of pixels manually, but I can't properly construct DenseHistogram object. Size of bins is equal to number of rows, the ranges are between 0 and 255, but I don't understand how to set those manually calculated values to the histogram?
Option 2: DenseHistogram.Calculate
My DenseHistogram object is calculating occurences of each intensity in whole image. How to instruct DenseHistogram to calculate intensity row-wise?
Please, see the picture attached. I want to have similar histogram in the end.

A: I think you should use cv::reduce with CV_REDUCE_SUM or CV_REDUCE_AVG flag.


text:
Q: Passing data in angular2 component I have a angular2 component defined which is getting input from parent as below.
@Input() data: string;
 ngOnInit() {
        console.log(this.data);
    }

In my parent page, I have the following

   <test-ui  [data]="data1">
   </test-ui>

and the typescript in parent  has:
data1: string = 'Test Data';

OnaButtonClick(){
this.data1 = 'New Data';
}

My problem is that this is not getting the "New Data". The component is always having "Test Data" as input.
How can I get the changed data in my child component?

A: I found a solution for this. I just need to add a div which will initialize this tag after I get the required Data

 <test-ui  [data]="data1">
   </test-ui>


text:
Q: Php mail function unable to send HTML I am trying to send an email with a link, the problem im facing is that outlook does not reconize the HTML which is being put in the email.
$onderwerp = "test";
$bericht = <<<EOT

  <title>Email_test</title>

 * the link

EOT;

$headers = 'From: ' . $verstuurd_van;

mail($naar_1, $onderwerp, $bericht, $headers);

Thanks in forehand for the help.

A: In order to be able to send a HTML email you need to add a few more headers:
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

So the entire email becomes something like:
$to = 'example@example.com';
        $subject = 'Test';
        $message = "

                    Hallo Example,

        ";
        $headers = "From: example@example.nl\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

        mail($to, $subject, $message, $headers);

Also take a look at: https://css-tricks.com/sending-nice-html-email-with-php/

A: just mention the headers in your email script like .
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

so your script will
$onderwerp = "test";
$bericht = <<<EOT

  <title>Email_test</title>

 * the link

EOT;

$headers = 'From: ' . $verstuurd_van;
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
mail($naar_1, $onderwerp, $bericht, $headers);

you can take reference from html email with php or w3school email html


text:
Q: Cannot install expo-cli in windows - node version 14.17.6 I wanted to start learning React Native using Expo, but I cannot install it using npm.
When I run the command npm install -g expo-cli, it gives me the following error:
added 825 packages, and audited 826 packages in 53s

28 packages are looking for funding
  run `npm fund` for details

10 vulnerabilities (4 low, 6 moderate)

To address all issues, run:
  npm audit fix

Run `npm audit` for details.

It told me to run npm audit fix and I tried the command right away.
However, the error stills seem to remain
# npm audit report

node-fetch  <=2.6.0 || 3.0.0-beta.1 - 3.0.0-beta.8
Denial of Service - https://npmjs.com/advisories/1556
fix available via `npm audit fix --force`
Will install expo@1.0.0, which is a breaking change
node_modules/node-fetch
  isomorphic-fetch  2.0.0 - 2.2.1
  Depends on vulnerable versions of node-fetch
  node_modules/isomorphic-fetch
    fbjs  0.7.0 - 1.0.0
    Depends on vulnerable versions of isomorphic-fetch
    node_modules/fbjs
      fbemitter  2.0.3 - 3.0.0-alpha.1
      Depends on vulnerable versions of fbjs
      node_modules/fbemitter
        expo  >=14.0.0
        Depends on vulnerable versions of expo-constants
        Depends on vulnerable versions of fbemitter
        node_modules/expo

xmldom  *
Severity: moderate
Misinterpretation of malicious XML input - https://npmjs.com/advisories/1769
fix available via `npm audit fix --force`
Will install expo@1.0.0, which is a breaking change
node_modules/xmldom
  @expo/plist  <=0.0.13
  Depends on vulnerable versions of xmldom
  node_modules/expo-constants/node_modules/@expo/plist
    @expo/config-plugins  <=3.0.8
    Depends on vulnerable versions of @expo/plist
    node_modules/expo-constants/node_modules/@expo/config-plugins
      @expo/config  3.3.23-alpha.0 - 5.0.8
      Depends on vulnerable versions of @expo/config-plugins
      node_modules/expo-constants/node_modules/@expo/config
        expo-constants  >=10.1.2
        Depends on vulnerable versions of @expo/config
        node_modules/expo-constants
          expo  >=14.0.0
          Depends on vulnerable versions of expo-constants
          Depends on vulnerable versions of fbemitter
          node_modules/expo

10 vulnerabilities (4 low, 6 moderate)

To address all issues (including breaking changes), run:
  npm audit fix --force

I tried running npm audit fix --force and it gave me the following outcome.
npm WARN using --force Recommended protections disabled.
npm WARN audit Updating expo to 1.0.0,which is a SemVer major change.

removed 824 packages, changed 1 package, and audited 2 packages in 19s

found 0 vulnerabilities

I thought it worked and I tried running the command expo and expo-cli and bash told me that the command could not be found.


text:
Q: R loop to subset information from a few subsequent rows and create new column I am still relatively new to R and I got this challenge.
I have a table (code below) in which the first column consists of names of managers and projects they have. Always after the name of manager (e.g. 'Tom Jones') his projects (e.g. '019200 [ytb] ppp') and other activities (e.g. 'Risk Management') are listed . Other columns represent capacity hours (capacity) and actual working hours (actual_hours) that manager spent on projects.
[Updated data frame]
df <- data.frame('Name'=c('Tom Jones', '0192000 [ytb] ppp', 'I-2020020 [BBB] Adm Valid', 'TENT DATZ 20204001 [ASS]','Risk Management', 'Andrea Jose Casteno','2040044 [Amaas] HHHHJ', '0291111 [inezzz] plmi', 'Training', 'Gerard van der Dike', '20200222+20203333 [Ttt ID/ZZ] HHH SSS DD +Dpp', 'Other' , 'R-20204444 [Res] Phhh Top SAA', 'Bill Gatea', 'Leave','2019xxxx [zzz] Aap ZZ'), 'capacity' = c(40,0,0,0,0,36,0,0,0,40,0,0,0,38,0,0), 'actual_hours' = c(44,12,2,20,10,40,30,0,10,43,20,10,13,38,20,18))

List of managers:
manager_names= c('Tom Jones', 'Andrea Jose Casteno', 'Gerard van der Dike', 'Bill Gatea')

I need to transform this table into the below output (picture below). For each manager that worked more than his capacity (actual_hours > capacity), I need to create a row in the new table. First column should be manager name. Second and third column show his capacity and actual_hours. Forth column should present short project names that manger worked on (exclude projects with 0 == actual_hours). The short project names need to be subtracted from the Name column - they are in the square brackets (e.g. BBB)

For now, I tried the below lines but I am stuck with how to subtract the information about projects (fourth column in the output). Probably a loop using the list of manager names is needed.
z=(which(df$actual_hours > df$capacity))

output_df=df[z,c("Name","capacity","actual_hours")]

y=which(output_df$capacity==0, arr.ind=TRUE)

newdf <- output_df[-y, ]

Thanks in advance for your help !

A: Here is a base R option
do.call(
  rbind,
  lapply(
    split(df, cumsum(grepl("manager\\d+", df$Name))),
    function(v) {
      if (v$capacity[1] <= v$actual_hours[1]) {
        cbind(v[1, ], projects = toString(gsub(".*\\[(\\w+)\\].*", "\\1", v$Name[-1])))
      } else {
        NULL
      }
    }
  )
)

which gives
      Name capacity actual_hours      projects
1 manager1       40           44 ytb, ytv, COM
2 manager2       36           40   TYU, inezzz
3 manager3       40           43   TYUKKK, ine

A: Here is an option with tidyverse.  After creating a grouping column by taking the cumulative sum of logical vector i.e. where the 'manager' substring is found in 'Name', then summarise by pasteing the extracted words within the square brackets, as well as get the column values of the first row with across
library(dplyr)
library(stringr)
df %>%
  group_by(grp = cumsum(str_detect(Name, 'manager'))) %>%
  summarise(projects = str_c(str_extract(Name[-1],
              "(?<=\\[)\\w+"), collapse="; "),
     across(c(Name, capacity, actual_hours), first), .groups = 'drop') %>%
  select(names(df), 'projects')

-output
# A tibble: 3 x 4
#  Name     capacity actual_hours projects
#  <chr>       <dbl>        <dbl> <chr>
#1 manager1       40           44 ytb; ytv; COM
#2 manager2       36           40 TYU; inezzz
#3 manager3       40           43 TYUKKK; ine


text:
Q: Metaprogramming C/C++ using the preprocessor So I have this huge tree that is basically a big switch/case with string keys and different function calls on one common object depending on the key and one piece of metadata.
Every entry basically looks like this
} else if ( strcmp(key, "key_string") == 0) {
    ((class_name*)object)->do_something();
} else if ( ...

where do_something can have different invocations, so I can't just use function pointers. Also, some keys require object to be cast to a subclass.
Now, if I were to code this in a higher level language, I would use a dictionary of lambdas to simplify this.
It occurred to me that I could use macros to simplify this to something like
case_call("key_string", class_name, do_something());
case_call( /* ... */ )

where case_call would be a macro that would expand this code to the first code snippet.
However, I am very much on the fence whether that would be considered good style. I mean, it would reduce typing work and improve the DRYness of the code, but then it really seems to abuse the macro system somewhat.
Would you go down that road, or rather type out the whole thing? And what would be your reasoning for doing so?
Edit
Some clarification:
This code is used as a glue layer between a simplified scripting API which accesses several different aspects of a C++ API as simple key-value properties. The properties are implemented in different ways in C++ though: Some have getter/setter methods, some are set in a special struct. Scripting actions reference C++ objects casted to a common base class. However, some actions are only available on certain subclasses and have to be cast down.
Further down the road, I may change the actual C++ API, but for the moment, it has to be regarded as unchangeable. Also, this has to work on an embedded compiler, so boost or C++11 are (sadly) not available.

A: That seems to me an appropriate use of macros. They are, after all, made for eliding syntactic repetition. However, when you have syntactic repetition, it's not always the fault of the language—there are probably better design choices out there that would let you avoid this decision altogether.
The general wisdom is to use a table mapping keys to actions:
std::map<std::string, void(Class::*)()> table;

Then look up and invoke the action in one go:
object->*table[key]();

Or use find to check for failure:
const auto i = table.find(key);
if (i != table.end())
    object->*(i->second)();
else
    throw std::runtime_error(...);

But if as you say there is no common signature for the functions (i.e., you can't use member function pointers) then what you actually should do depends on the particulars of your project, which I don't know. It might be that a macro is the only way to elide the repetition you're seeing, or it might be that there's a better way of going about it.
Ask yourself: why do my functions take different arguments? Why am I using casts? If you're dispatching on the type of an object, chances are you need to introduce a common interface.

A: I would suggest you slightly reverse the roles. You are saying that the object is already some class that knows how to handle a certain situation, so add a virtual void handle(const char * key) in your base class and let the object check in the implementation if it applies to it and do whatever is necessary.
This would not only eliminate the long if-else-if chain, but would also be more type safe and would give you more flexibility in handling those events.


text:
Q: Input to table in javascript How can i add a content to html table with input fields.
For example here is html code:

        function add(){
            var name = document.getElementById("name");
            var surname = document.getElementById("surname");
            var output = document.getElementById("output");
            output.innerHTML = "
"+name+"	"+surname+"
"

        }

  <!DOCTYPE html>

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

        <form action="">

                Name
                <input type="text" id="name">

                Surname
                <input type="text" id="surname">

        </form>
        <input type="button" onclick="add();" value="Add">

Name	Surname

I want to output my input fields in the table like rows.. but it does not work i dont know where is my problem i get [object HTMLInputElement].
And how can i make it work for entering more values because like this i can only enter one row

A: How about using this code?
It adds surname and name below the thead.

function add(){
  var name = document.getElementById("name");
  var surname = document.getElementById("surname");
  var output = document.querySelector("#output tbody");
  output.innerHTML += "
"+name.value+"	"+surname.value+"
"
}
<!DOCTYPE html>

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

    <form action="">

            Name
            <input type="text" id="name">

            Surname
            <input type="text" id="surname">

    </form>
    <input type="button" onclick="add();" value="Add">

Name	Surname

A: you should assign the value of the input fields like below.
 function add(){
            var name = document.getElementById("name");
            var surname = document.getElementById("surname");
            var output = document.getElementById("output");
            output.innerHTML = "
"+name.value+"	"+surname.value+"
"
        }

A: Try:
Give tbody an id to avoid removing thead

function add(){
  var name = document.getElementById("name");
  var surname = document.getElementById("surname");
  var output = document.getElementById("output2");
  output.innerHTML = "
" + name.value + "	" + surname.value + "
";
}

You are trying to insert an HTML input element instead of the value of the element.
To make multiple entries possible try the last line of the function to:
output.innerHTML += "
" + name.value + "	" + surname.value + "
";


text:
Q: Vote to close titles missing The close vote dialog on the iOS app has no titles on the options:

Unless there is an existing vote where that specific title shows (including the current vote count indicator):

Since it only shows when there is a vote count to display, I'm assuming it is a side effect of this fix.
For reference, this is what it should look like (old image I took from elsewhere, but you get the idea):

*

*App Version: 1.6.1.1

*Device: iPhone 6s

*OS Version: Version 10.0.1 (Build 14A403)

A: This will be fixed in 1.6.1.2.
As you could guess, I was incorrectly returning nil if I didn't need to append a vote count, rather than just returning the unmodified title.


text:
Q: Scanner Skipping Over my Opportunity to Input while this may be entirely trivial my lack of experience has rendered me stumped due to this: with this line of code
String a = scanner.nextLine();

I am shown the following error
 java.util.NoSuchElementException: No line found

I was under the impression that when operations involving the use of Scanner data follow the use of a scanner it will wait for input. This scanner simply leaves me with no chance to enter my input leaving me with operations attempting to use data that does not exist.
Here is the complete relevant code. Forget its inefficiency.
System.out.println(FactBank_QA.qA[ourRANDOM]);
        Scanner scanner = new Scanner (System.in);
        if (scanner.hasNext()){
            String a = scanner.next();
            char b = (char)a.charAt(0);
            if (b == '*') System.exit(0);
        }
        System.out.println(FactBank_QA.qA[ourRANDOM+1]);
        char c; String f = "0";
        do{
            if (scanner.hasNext()){
                f= scanner.next();
            }
                c = (char)f.charAt(0);
        }while(c != 1 || c != 2);
        if (c == 1) {
        FactBank_QA.qA[ourRANDOM] = "";
        FactBank_QA.qA[ourRANDOM+1] = "";
        }

The exception is coming from the first, the second isn't reached
Thanks for the tip too.
-Updated the code and removed a .close
I no longer receive errors (!) however the second Scanner and subsequent 'if' are now non-functional.
I did have one .close() but have removed it, this fixed the first use of 'scanner'

A: Firstly, be cautious of where you call close(). This is a good reference.
You also seem to have a logic error here:
do{
    if (scanner.hasNext()){
        f= scanner.next();
    }
        c = (char)f.charAt(0);
}while(c != 1 || c != 2);

c is a char. Remember that '0' is very different than 0. You may instead want: while(c != '1' || c != '2');. You might need to update other areas of your code as well.
Another logic error, what if I press enter without typing anything? (psst: f.charAt(0))
One more: while(c != '1' || c != '2') is an infinite loop, since c can never be simultaneously equal to '1' and '2'.