text:
Q: Web Development: Complex processes: Are state machines the (only?) way to go? In web development there is a lot of focus on REST-style architectures, with the objectives of minimizing (or eliminating) state. The web frameworks that I have seen all emphasize this style (Django, Rails, flask, etc.).
While I agree that this is a good fit for the web in general, there are also many cases where this is inadequate. In particular I am thinking of the case where you want the user to follow a process, i.e. you want to offer a number of steps and these steps should be completed in a certain order (possibly with optional steps, deviating paths, etc.)
A good example of this might be a shopping cart: First you have to make your selection, then enter your address, choose shipment type, enter your payment details, finish. You don't want the user to skip any of these steps and the process can become a lot more complex. Ideally I would want this process to be defined in a separate place to separate this logic from the rest of the implementation.
Now my questions:

*

*Are finite state machines the way to go here? Do they still work well if these processes become complex and need to change a lot (e.g. this step should go here, this step should go into this process instead, etc)?

*What options are offered by/for web frameworks (not any in particular I am interested in the best solutions)?

*What are interesting / good examples of where such processes occur? Shopping carts are an obvious example but I am sure there are lots more.

A: *

*Yes, they are. Using state machines (workflows) is an appropriate solution for the problem you described. If designed well it can make your code more cleaner, remove mess from the code. Logic of each state and transition logic are incapsulated within a State class object so the code looks cleaner and more maintainable . Implementations may vary (say, the place you keep your transition logic - within state or create a separate transition manager) and don't match canonical description of state machine in discrete math so you'd better try what works for you better.

*For Ruby you can check workflow: https://github.com/geekq/workflow or stonepath: https://github.com/bokmann/stonepath. State machine pattern is also can be found in javascript frameworks (SpoutCore). It's not difficult to implement your own small state machine engine.

*Interesting examples? Lots of them. Processing orders, banking operations, games.  I used state machine when created behaviour correction module which includes phychological tests, games, video. The transitions from state to state depended there on if tests are answered correctly, if game played successfully etc.
PS. I used the terms of state machine and workflow as synonyms but they are not the same; it was discussed here: http://jmettraux.wordpress.com/2009/07/03/state-machine-workflow-engine/ . You can also find some Ruby code and links there.


text:
Q: Message publishing interface when deferring until transaction is committed Suppose I have the following interface used for publishing messages onto a message queue:
interface IMessageProducer
{
    void Publish<TMessage>(TMessage message);
}

Normally, an implementer of this interface will attempt to publish a message onto the message queue immediately. However, I've found that sometimes I need the messages to be deferred being published until the database transaction has been committed (this ensures that data used in the message handler is available in the database).
Is it appropriate to make this behavior explicit to the developer? For example, extending the interface:
interface IMessageProducer
{
    void Publish<TMessage>(TMessage message);
    void DeferPublishUntilTransactionCommit<TMessage>(ITransaction transaction, TMessage message);
}

Or by making an additional interface that adds this behavior (or even an extension method on the IMessageProducer interface):
interface IDeferUntilTransactionCommitMessageProducer
{
    void DeferPublish<TMessage>(ITransaction transaction, TMessage message);
}

Is my assumption wrong? Is this really an implementation detail where there's no reason to expose it to the developer? I've found it very useful (increasing clarity) to make the interface explicit about the intent so that the developer understands why it's important to defer publishing until the transaction has committed. Otherwise, if it's a cross-cutting concern and an implementation detail, it becomes a configuration problem that may significantly impact the running application. I've seen other software/libraries that make these choices (like using two phase commit) an implementation detail of the interface rather than explicit.

A: I'd suggest encapsulating the deferral behaviour into a decorator:
public class TransactionDeferral : IMessageProducer
{
    public TransactionDeferral(IMessageProducer decoratedMessageProducer, ITransaction deferringTransaction)
    {
        _decoratedMessageProducer = decoratedMessageProducer;
        _deferringTransaction = deferringTransaction;
    }

    public void Publish<TMessage>(TMessage message)
    {
        if (_deferringTransaction.IsCommitted)
            _decoratedMessageProducer.Publish(message);
        else
            _deferredMessages.Add(message);
    }

    private void DeferringTransaction_Committed(obsect sender, TransactionCommitedEventArgs e)
    {
        foreach (var message in _deferredMessages)
        {
            _decoratedMessageProducer.Publish(message);
        }
    }
}

The consumer of this interface may be then injected an IMessagePublisher that is in reality an instance of TransactionDeferral decorating the true message publisher, thus becoming completely agnostic of the transaction.
If the consumer has to be aware of the completion of individual message publishing operations, then you could probably modify your original interface for its Publish method to return a Task that can be eventually awaited:
public interface IMessageProducer
{
    Task Publish<TMessage>(TMessage message);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как вынести переменную с AsyncTask в основной поток? (Android) через сокет получаю информацию с сервера, присваиваю его в переменную, теперь нужно этот полученные текст вставить в TextView, подскажите, как это сделать? Вот я написал, полученное значение присваивается в переменную, но текст в TextView не меняется. Как правильно сделать?
public class MainActivity extends AppCompatActivity {
private EditText el;
private TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    el = (EditText) findViewById(R.id.editText);
    text = (TextView) findViewById(R.id.textView);

  }

public void send_data (View v) {
    String message = el.getText().toString();
    BackgroundTask bl = new BackgroundTask();
    bl.execute(message);
  }

    class BackgroundTask extends AsyncTask<String, Void, Void> {

@Override
protected Void doInBackground(String... voids) {
    try {
        String message = voids[0];
        Socket s = new Socket("10.195.42.158", 8000);
        InputStreamReader listen = new InputStreamReader(s.getInputStream());
        BufferedReader buff = new BufferedReader(listen);
        String msg = buff.readLine();
        text.setText(msg.getText());

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

Здесь в переменную типа String msg присваивается полученное сообщение от сервера, хочется теперь изменить текст TextView на текст переменной msg

A: Для обновления графических компонентов, и передачи информации в UI-поток вы должны использовать метод AsyncTask-a onPostExecute().
Пример использования AsyncTask с документации в котором отображено использование данного метода:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Схема которая отображает как выполняется AsyncTask:


text:
Q: Problems programming LPC1343 microcontroller in Ubuntu When I copy a binary that works on a lpc1343 to the mounted usb-device representing the lpc1343 flash, the binary file is changed and does not work. Doing the same with the flash mounted via usb on Windows or Mac OS does not have the same problem. What could be the problem, and how can it be fixed?
Edit: The problem seems to be the vfat implementation in Linux which seems to prefix 0s before the file to be transferred.

A: you can solve this by using mtools (userspace fat utilities):
mdel -i /dev/sdf ::/firmware.bin
mcopy -i /dev/sdf new_firmware.bin ::/

A: Another solution is to use the simpleflash python script from the r0ket[1] git repository. It writes directly to the device instead of using "cp". I had to modify the size at line 20 from 32 to 64 to work with a LPC1347 test board...
The script can be found here.
[1] LPC1343 board


text:
Q: Rails mutliple has_one relationships as a has_many I have a scenario where I need to have multiple has_one relationships and be able to access them all at once through a relationship.
Currently I have an STI table, we'll call it Animals.
There are subclasses: Lion, Meerkat, Boar
And they all need to relate to multiple Group objects.
So a Lion can be in multiple groups, but a Group may only have one Lion related.
I want to limit and refer to specifically one Lion, Meerkat and Boar.
I've tried a simple bridge table, has_many :animals, through: :associated_animals. But there doesn't seem to be an easy way to pull out group.lion.  I've also tried doing multiple has_one :lion/:meerkat/:boar relationships, but there was no obvious way to do group.animals.
Is there an STI way to get this functionality through default rails associations or do I have to do a combination of both the has_one :lion and has_many :animals?

A: Have you tried it like this:
app/models/animal.rb
class Animal < ActiveRecord::Base
  belongs_to :group
end

class Lion < Animal; end
class Meerkat < Animal; end

Of course you can split out the Lion and Meerkat classes to separate ruby files
app/models/group.rb
 class Group < ActiveRecord::Base
   has_many :animals
   has_one :lion
   has_one :meerkat
 end

after you run your migrations your schema should look something like this:
db/schema.rb
ActiveRecord::Schema.define(version: 20150309234835) do

  create_table "animals", force: :cascade do |t|
    t.string   "name"
    t.string   "type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "group_id"
  end

  create_table "groups", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

Now you should be able to write queries using group:
g = Group.find(1)
g.animals
g.lion
Lion.first.group
Animal.last.group


text:
Q: How do I check my lambda expression for null? If there are no records that match the following lambda query, I get a

System.InvalidOperationException error. Additional information: The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

The code is: runTime = db.Records.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x).Sum(c => c.RunMinutes);
The variable runTime is a decimal. I tried changing it to a decimal? but I still get the same error.
What is the correct approach to solve this problem?

A: Firstly you can select decimal values from the objects which met the condition. And then use .DefaultIfEmpty() method before the .Sum() method:
runTime = db.Records
              .Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
              .Select(c => c.RunMinutes)
              .DefaultIfEmpty()
              .Sum();

DefaultIfEmpty() function inserts a single element with a default value if the sequence is empty. And as we know, defualt value for decimal type is 0.0M.
(Default Values Table)
Additionally:
You didn't tell us Linq to What? are you using. But, if you are using LinqToEntity, then you must change your code as (DefaultIfEmpty is not supported by EF):
runTime = db.Records
              .Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
              .Sum(c => (decimal?)c.RunMinutes) ?? 0;


text:
Q: I need help with adding condition to php live search I am just learning php and ended up at this tutorial http://www.w3schools.com/php/php_ajax_livesearch.asp
Till now my PHP search file looks the same as in example but i changed the if (strlen($q) > 0) to if (strlen($q) > 3) to display results after typing minimum 3 words. I am wondering how can i make the results paginate if there are lots of them?
Thanks
Roshan

A: You would need to page after obtaining the number of records from your database.
Paging should be done by the same script that echos your ajax response.
Here is how to page:
PHP MySQL paging.

A: The idea of search suggestions is to show the user what do you have in your site, in terms of relevance, that match his query. This being said, you should only throw a subset of results, being the first result the most relevant, instead of the whole file or database. In others words, you don't need pagination.
Show the user 5 or 10 items, if he doesn't find what he's after he'll keep writing until he finds it. If he doesn't finds it he will just search it. Remember that it is a suggestion and nothing more.


text:
Q: Authorization error 401 using API - Python This is my first time using an API in Python. I want to give a query on the website http://data.bioontology.org. Not sure what the API_KEY has to be. Also, I do have an account on this website but I do not have to log in to get a query result. Can someone please help me out?
import urllib.request, urllib.error, urllib.parse
import json
import os
from pprint import pprint

REST_URL = "http://data.bioontology.org"
API_KEY = ""

def get_json(url):
    opener = urllib.request.build_opener()
    opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]
    return json.loads(opener.open(url).read())

def print_annotations(annotations, get_class=True):
    for result in annotations:
        class_details = result["annotatedClass"]
        if get_class:
            try:
                class_details = get_json(result["annotatedClass"]["links"]["self"])
            except urllib.error.HTTPError:
                print(f"Error retrieving {result['annotatedClass']['@id']}")
                continue

        print("Annotation details")
        for annotation in result["annotations"]:
            print("\tfrom: " + str(annotation["from"]))
            print("\tto: " + str(annotation["to"]))
            print("\tmatch type: " + annotation["matchType"])

text_to_annotate = "peanut, butter, pita, bread, home"

# Annotate using the provided text
annotations = get_json(REST_URL + "/annotator?text=" + urllib.parse.quote(text_to_annotate))

# Print out annotation details
print_annotations(annotations)

# Annotate with hierarchy information
annotations = get_json(REST_URL + "/annotator?max_level=3&text=" + urllib.parse.quote(text_to_annotate))
print_annotations(annotations)

# Annotate with prefLabel, synonym, definition returned
annotations = get_json(REST_URL + "/annotator?include=prefLabel,synonym,definition&text=" + urllib.parse.quote(text_to_annotate))
print_annotations(annotations, False)

Here's the error output:
HTTPError                                 Traceback (most recent call last)
<ipython-input-15-996831b96ba6> in <module>()
     52
     53 # Annotate using the provided text
---> 54 annotations = get_json(REST_URL + "/annotator?text=" + urllib.parse.quote(text_to_annotate))
     55
     56 # Print out annotation details

5 frames
/usr/lib/python3.6/urllib/request.py in http_error_default(self, req, fp, code, msg, hdrs)
    648 class HTTPDefaultErrorHandler(BaseHandler):
    649     def http_error_default(self, req, fp, code, msg, hdrs):
--> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    651
    652 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 401: Unauthorized

A: You need to have an account to request your api key. Excerpt below is from this page: https://www.bioontology.org/wiki/BioPortal_Help
Programming with the BioPortal API
Documentation about how to use the BioPortal REST API to access information is available here:
http://data.bioontology.org/documentation
Getting an API key
Use of the BioPortal REST API requires an API key.
To retrieve your API key, log into your account on the BioPortal website. If you don't have an account, you'll need to create one.
Your API key will be listed in plain text on your account page.


text:
Q: Outlook Meeting Requests Not Being Re-encoded from Base 64 by Receiving Clients Exchange 2010 + Outlook 2007. Users send outlook meeting request to a list of recipients both interanlly and externally to the organisation. Some recipients report receiving 'garbled' messages instead of meeting requests.
The emails received by some external recipients show emails with base-64 encoded attachments - and they are not able to add the meeting request to their calendar or even view it. Example of received email below:
Accept-Language: en-US, en-NZ
Content-Language: en-US
X-MS-Has-Attach:
X-MS-TNEF-Correlator:
acceptlanguage: en-US, en-NZ
Content-Type: multipart/alternative;

boundary="_000_A4701CF4E0917340AF3DD54B4BE141CA014EA83517WNS10compassh_"
MIME-Version: 1.0
X-OriginalArrivalTime: 15 Jul 2011 03:15:21.0709 (UTC)
FILETIME=[6E70D9D0:01CC429D]

--_000_A4701CF4E0917340AF3DD54B4BE141CA014EA83517WNS10compassh_
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64

V2hl...yMNCg==

--_000_A4701CF4E0917340AF3DD54B4BE141CA014EA83517WNS10compassh_
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64

PGh0b...bWw+DQo=

--_000_A4701CF4E0917340AF3DD54B4BE141CA014EA83517WNS10compassh_
Content-Type: text/calendar; charset="utf-8"; method=REQUEST
Content-Transfer-Encoding: base64

QkVHS...jIyMjIyMNCg==

--_000_A4701CF4E0917340AF3DD54B4BE141CA014EA83517WNS10compassh_--

I've shortened the base 64 encoding blocks in the above sample, but I can confirm that I've manully re-encoded the base 64 and they convert appropriately to a plain text version of the request, an HTMl version, and an .ics file which opens fine in outlook (2010).
These particular recipients normally get meeting requests fine, but something seems to be causing a probles with some of these requests.
The external recipients report using 'Outlook', but at this stage we can't be sure if it is Outlook, or Outlook Express or which specific versions.
Searching google, some bug reports for Thunderbird describe the client not re-encoding attachments, but none of our recipients seem to be using Thunderbird. There also appears to be some discussion about Outlook 2000 not opening .ics files - however , the recipients can't even see the attachments as such - but rather just encoded base 64 MIME.
Please help!

A: We had a similar issue with Exchange 2007 + outlook 2007. calendar invites sent from outlook express by client once received and accepted, the response which was sent back, the user found the response as above.
We had raised a ticket with MS and they confirmed it is a bug is Exchange 2007 and outlook express client.
Not sure abt Exchange 2010 whether they have fix this issue


text:
Q: Implicit ClassTag in pattern matching Let's take this for an example:
import scala.reflect._

def get[T](list: List[Any])(implicit tag: ClassTag[T]) = {
  list.flatMap {
    case element: T => Some(element)
    case _ => None
  }
}

I can use get() to get values of type T from a list (e.g. get[String](list) will give me all strings from that list).
Now, I understand that compiler provides the value of type ClassTag[String] automatically. I also understand that ClassTag is a type class, and somewhere behind the curtain there's a piece of code that says implicitly[ClassTag[T]].getRuntimeClass() or whatever.
But if that's so, how come we can pattern match without the class tag (we just can't differentiate between erased types in that case)? I mean, how is it achieved that, if I declare an implicit parameter (which is automatically provided by the compiler), I get one behavior, but if i don't I get a different behavior?

A: The compiler automatically translates your code roughly to this:
  def get[T](list: List[Any])(implicit tag: ClassTag[T]) = list.flatMap {
    case (element @ tag(_: T)) => Some(element)
    case _ => None
  }

ClassTag has an unapply(x: Any) overload that allows it to pattern match on values. I've cleaned up the tree obtained from reify to only show the relevant parts, but this will show you the full tree:
scala.reflect.runtime.universe.reify {
    def get[T](list: List[Any])(implicit tag: ClassTag[T]) = {
      list.flatMap {
        case element: T => Some(element)
        case _ => None
      }
    }
}

Also see the scaladoc:

The compiler tries to turn unchecked type tests in pattern matches into checked ones by wrapping a (_: T) type pattern as ct(_: T), where ct is the ClassTag[T] instance. Type tests necessary before calling other extractors are treated similarly. SomeExtractor(...) is turned into ct(SomeExtractor(...)) if T in SomeExtractor.unapply(x: T) is uncheckable, but we have an instance of ClassTag[T].


text:
Q: Copy file with a new file name My boss has asked me to write an AppleScript that with a file, specified with a hard coded path in the text script, Copy a file from one location in the Finder to another location (giving it a new file name in the process).
This was my idea
tell application "Finder"
    copy "/blah/blahblah/
    save as "blah blah2" /blah/blah/blah
end tell

A: Copy is an AppleScript command not a finder command,
copy 1 to a
will copy value 1 into variable a
The command you're looking for to copy files is duplicate.
set fileToCopy to "DiskName:Users:shortname:Downloads:document.pdf"
set targetFolder to "DiskName:Users:shortname:Desktop:"
tell application "Finder" to duplicate fileToCopy to folder targetFolder

A: Thanks for the downvotes!
Any who'zle this is what I ended up with
set desktopFolder to path to desktop as text
set thefile to desktopFolder & "lol.html"
set DestinationPath to desktopFolder & "BLAH BLAH BLAH"
set destinationFilename to "ROFL2.txt"
with timeout of 60 seconds
tell application "Finder"
    try
        set theDupe to duplicate file thefile to folder DestinationPath
        set name of theDupe to destinationFilename
    on error
        display dialog "A problem occurred duplicating the file. This may be because the file already exists!"
    end try
end tell
end timeout


text:
Q: C# Mouse Move won't work in a game         private void button1_Click(object sender, EventArgs e)
    {
        InitializeComponent();
        System.Windows.Forms.Timer ShakerZwei = new System.Windows.Forms.Timer();
        System.Windows.Forms.Timer SechsSekunden = new System.Windows.Forms.Timer();
        ShakerZwei.Interval = 6800;
        SechsSekunden.Interval = 6000;
        SechsSekunden.Tick += new EventHandler(MausBewegung);
        ShakerZwei.Tick += new EventHandler(MausBewegungZurück);
        SechsSekunden.Start();
        ShakerZwei.Start();
    }
    void MausBewegung(object sender, EventArgs e)
    {
        Cursor.Position = new Point(Cursor.Position.X + 10, Cursor.Position.Y + 10);
    }
    void MausBewegungZurück(object sender, EventArgs e)
    {
        Cursor.Position = new Point(Cursor.Position.X - 10, Cursor.Position.Y - 10);
    }

My Code works everywhere, but not in a game the camera doesn't, i already tried to change the "-10" or "+10", still doesnt work. Is there another way to move the cursor between 2 points ?


text:
Q: Jupyter Notebook: how to use ipython widget variable outside the function I am using the interact function of ipython widget and I want to use the selection as a variable outside the function. For e.g.
import ipywidgets as widgets
from ipywidgets import interact, interactive
list1 = ['ABC','DEF','GHI']

@interact
def uni_systems(items = list1):
    choice = items

It gives me an interactive dropout. Now I like to use choice or my dropout selection outside the function, but it is not defined yet. How to use it outside the function for any further processing

A: IIUC, insert global choice statement before assigning a value in it within the function. Basically, creating it as a global variable so you can use it outside the function

A: One solution, encapsulated slightly better than a global variable, is to assign the result to an attribute of the function:
@interact
def uni_systems(items = list1):
    uni_systems.choice = items

uni_systems('foo')
print(uni_systems.choice)

Trying access the result before the function has been called for the first time will raise an AttributeError.


text:
Q: Show that $\operatorname{rank}(A)=r$ Let $r$ be the smallest integer such that $A=BC$ for some $m\times r$ matrix $B$ and some $r\times n$ matrix $C$. Show that $\operatorname{rank}(A)=r$
Take $x \in \operatorname{Row}(A)$. So $x$ is a linear combination of the rows of $C$, and so $\operatorname{Row}(A)\subset\operatorname{Row}(C)$. Thus $\operatorname{row \,rank}(A)\leq \operatorname{row \,rank}(C).$
This is what I have so far, I'm not sure whether this is even correct though or where to go next.


text:
Q: Fire "data-ng-change" programatically or another way to change value of input on website using Angular JS I am writing a userscript and unfortunately the website uses Angular JS which I don't know.
There is code:
<form class="form ng-pristine ng-valid ng-valid-maxlength" name="$ctrl.actionableForm.form" _lpchecked="1">
<input type="text" maxlength="254" placeholder="" data-ng-attr-id="text-field-{{:: $ctrl.widget.header.id }}" data-ng-model="$ctrl.fieldValue.value" data-ng-change="$ctrl.updateFormFieldValue()" data-ng-blur="$ctrl.onBlur()" data-ng-focus="$ctrl.updateFormFieldValue()" data-ng-readonly="$ctrl.isReadOnly()" data-ng-trim="false" data-ng-keyup="$ctrl.handleKeyup($event)" class="form-control text-field-input ng-pristine ng-untouched ng-valid ng-not-empty ng-valid-maxlength focus-visible" id="text-field-qYMHEJMncH0S-ogeOc5CTw" data-focus-visible-added="">

I want to change the value of that input programatically, like:
document.querySelector('[id^="text-field-"]').value = 'My new value';

But it doesn't work because it doesn't fire data-ng-change="$ctrl.updateFormFieldValue()" so the new value is not saved.
Please how can I do it?

A: If someone will look for the same thing, I solved it this way:
const myField = document.querySelector('[id^="text-field-"]');
myField.value = 'My new value';
angular.element(myField).trigger('change');


text:
Q: SAPUI5 How to insert fragment or xmlview inside a semantic detail view
I searched the answer to this question but every solution that I found did not work, so I'm starting to think that probably my problem is at a higher level (but the official and unofficial SAP guides did not help).
I have a Fiori Master-Detail application, and my detail view is the following:
    <mvc:View
        controllerName="masterdetailsample.controller.Detail"
        xmlns="sap.m"
        xmlns:l="sap.ui.layout"
        xmlns:core="sap.ui.core"
        xmlns:mvc="sap.ui.core.mvc"
        xmlns:semantic="sap.m.semantic">

    <semantic:DetailPage
        id="page"
        navButtonPress="onNavBack"
        showNavButton="{device>/system/phone}"
        title="{i18n>detailTitle}"
        busy="{detailView>/busy}"
        busyIndicatorDelay="{detailView>/delay}">

        <semantic:content>
            <ObjectHeader
                id="objectHeader"
                title="{EmployeeID}">
            </ObjectHeader>
            <l:VerticalLayout>
                <IconTabBar
                    id="iconTabBar"
                    class="sapUiResponsiveContentPadding"
                    upperCase="true">
                    <items>
                        <IconTabFilter
                            id="detailIconTabBarInfo"
                            text="{i18n>detailIconTabBarInfo}"
                            tooltip="{i18n>detailIconTabBarInfo}">

                            <Toolbar design="Solid">
                                <content>
                                    <Title
                                        text="{i18n>detailIconTabBarInfo}"
                                        width = "100%">
                                    </Title>
                                </content>
                            </Toolbar>

                            <core:Fragment id="perfEval" fragmentName="masterdetailsample.view.viewcomponents.PerformanceDevelopment" type="XML"/>
                            <mvc:XMLView id="compOvw" viewName="masterdetailsample.view.viewcomponents.PerformanceDevelopment" displayBlock="true"/>

                        </IconTabFilter>
                    </items>
                </IconTabBar>
            </l:VerticalLayout>
        </semantic:content>
    </semantic:DetailPage>
</mvc:View>

And my fragment page is the following:
<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core"
    xmlns:l="sap.ui.layout"
    xmlns:f="sap.ui.layout.form"
    xmlns:mvc="sap.ui.core.mvc">
    <Text>
        FRAGMENT CONTENT
    </Text>
</core:FragmentDefinition>

While the xmlview is:
<mvc:View
    xmlns="sap.m"
    xmlns:core="sap.ui.core"
    xmlns:l="sap.ui.layout"
    xmlns:f="sap.ui.layout.form"
    xmlns:mvc="sap.ui.core.mvc"
    controllerName="masterdetailsample.controller.PerformanceDevelopment">
    <Text>
        FRAGMENT CONTENT
    </Text>
</mvc:View>

I tried every combination that I have been capable to think of but the page does not render.
Now I know that fragments and xmlviews must be surrounded by an aggregator that cannot be the "content" tag of sap.m. So I tried with "VerticalLayout" and "content" from sap.ui.layout, moving them through the page but still the browser complains about the use of the correct aggregator (from the ff console "Cannot add text nodes as direct child of an aggregation. For adding text to an aggregation, a surrounding html tag is needed: FRAGMENT CONTENT").
I have read that view must be declared into manifes.json, but if I understood correctly, only if this pages are "standalone". I thought that this is not my case since I would reuse many of this subview or fragment in my application.
I checked if I have some refuse or some wrong code left during my different attempt but everything seems correct.
I thought that maybe xmlviews and fragments cannot be used inside sap.m.semantic.DetailPage but I haven't found any evidence of this through the SAP doumentation.
It is correct to structure a detail page as I have done? Can an IconTabFilter contains a subview or a fragment or it is better to design the page in another fashion? Every time that I change something I don't know if it does not work because of conceptual or design mistake and I'm a little frustrated by this.
Thank you all

A: The error is caused by <Text> FRAGMENT CONTENT </Text>. You cannot enter text directly into the <Text> tag. You need to use <Text text="FRAGMENT CONTENT"/>.
The rest of the code seem fine.


text:
Q: Is there a shorter way to remove line breaks when reading from a file to a list? Here is my current code:
dfile = open('dictionary.txt', 'r')
sfile = open('substrings.txt', 'r')
dictionary_words = []
substrings = []

for line in dfile:
    dictionary_words.append(line.rstrip('\n'))
for line in sfile:
    substrings.append(line.rstrip('\n'))

It works but seems pretty wordy.
Is this the appropriate way to write this out, or am I missing a simpler process?

A: Try this:
with open('dictionary.txt', 'r') as f:
    dictionary_words = f.read().splitlines()

A: Either use map:
dictionary_words = map(lambda line: line.rstrip('\n'), dfile)

or a list comprehension:
dictionary_words = [line.rstrip('\n') for line in dfile]

A: A slightly less wordy alternative is to use list comprehensions:
with open('dictionary.txt', 'r') as dfile:
  dictionary_words = [line.rstrip('\n') for line in dfile]

with open('substrings.txt', 'r') as sfile:
  substrings  = [line.rstrip('\n') for line in sfile]

A: It seems your dictionary file has one word at line. It may help you:
>>> words = [w.strip() for w in open('dictionary.txt').read().split('\n')]

A: As @Chris mentions in the comment you could define a function:
def words_fromfile(filename):
    with open(filename) as f:
         return f.read().splitlines()

dictionary_words = words_fromfile('dictionary.txt')
substrings = words_fromfile('substrings.txt')

You could always change the function definition later if you don't like it for some reason without touching the rest of the code.


text:
Q: Publishing a Dialogflow agent doesn't update API answers My application, when passing an utterance to my Dialogflow agent, is not returning the up-to-date answers.
I have created a Dialogflow agent that I am accessing through a Google Service account using Google's PHP library.  I have "published" a number of times to the "Web" environment.
I just made a new intent which is matched and answered properly in the Dialogflow UI's test console.  When I type the same utterance into my application, I get a default fallback answer.
Looking on the "History" page at the conversation log, all the utterances are marked as being in the "Draft" environment - even utterances that come via my application.
How do I connect my application to my agent in such a way that it uses the version published to the "Web" environment.

A: I'm new to DialogueFlow myself, but I'll try to help.
This is where my chatbot lives: http://sidwho.com/ai.html
Are you trying to do the same? If so, I logged into my https://console.dialogflow.com -> went to "integrations" -> "web demo" -> turned it on (blue) -> copied the iframe code-> pasted it into my website using Dreamweaver.


text:
Q: How can I solve this error to visualize the gene fusion using the circlize package? I want to visualize several gene fusions in a circle using the circlize package in R.
My data is
fusion1 <- data.frame("chr" = c("chr7", "chr1", "chr12", "chr3", "chr16", "chr7", "chr12", "chr1"),
                   "start" = c(27934839, 92327028, 24366277, 64430159, 85391249, 27934839, 67462830, 741179),
                   "end" = c(28934839, 93327028, 25366277, 65430159, 86391249, 28934839, 68462830, 1741179))

fusion2 <- data.frame("chr" = c("chr17", "chr1",  "chr12", "chr3",  "chr16", "chr17", "chr12", "chr7"),
                     "start" = c(30267305, 92456741, 24048958, 64184643, 85667520, 30274636, 66990707, 55863785),
                     "end" = c(31267305,93456741, 25048958, 65184643, 86667520, 31274636, 67990707, 56863785))

My code is
library(circlize)
circos.initializeWithIdeogram()
circos.genomicLink(fusion1, fusion2, col = "red", border = NA)
circos.clear()

But I conducted the codes and got an error:
Error in region1[i, 2] == region1[i, 3] :
  comparison of these types is not implemented

This is what I expacted to happen.

A: When I run your code, there is no error. Make sure you have a clean environment and make sure your columns have the same types like this:
library(circlize)
circos.initializeWithIdeogram()
circos.genomicLink(fusion1, fusion2, col = "red", border = NA)

circos.clear()

Created on 2023-03-04 with reprex v2.0.2


text:
Q: liquibase hsql db column creation error i am using hsql db and liquibase to create a db schema and the liquibase script am using is giving an error
<changeSet author="fryder" id="1492138266795-903">
        <createIndex indexName="ACCESS_GRP_IDX" tableName="ACCESS_GRP">
            <column computed="true" name="UPPER("DESCR")"/>
        </createIndex>
    </changeSet>

cvc-complex-type.3.2.2: Attribute 'computed' is not allowed to appear in element 'column'. -> [Help 1]
plz help, note:- i created the schema defnition using liquibase generatechangelog method.
so for the people looking for answer.
HSQL db is not a fullfledged relational-db with all functions equal to oracle. removed UPPER(".. and the statement worked.

A: did you try with H2 ? it often has a more complete support of such features


text:
Q: Async API Call, Redux React-Native I have recently started to learn React-Native and I am trying to implement Redux to manage the state of my app.
As I have experience with React JS I implemented the state manage Redux the same way I would usually do with React JS. Everything seems to work except the async api call. The props in store change but it does not change in component props.

Here is how I set my redux store

import { createStore, compose, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers';

//create initial state
const initialState = {};

//create a variable that holds all the middleware
const middleware = [thunk, logger];

//create the store
const store = createStore(
  reducer,
  initialState,
  compose(
    applyMiddleware(...middleware)
  )
);

export default store;

My reducer  component

import { FETCH_REQUEST_BEGIN, FETCH_REQUEST_FAILED, DATA_FETCHED} from '../constants';

const initialState = {
  movieResults: null,
  fetching : false,
  failed : false
}

export default (state = initialState, actions)=>{

  switch(actions.type){

    case FETCH_REQUEST_BEGIN:
      return  {
        ...state,
        fetching : true
      };
    case DATA_FETCHED :
      return {
        ...state,
        movieResults : actions.payload,
        fetchin : false
      }
    case FETCH_REQUEST_FAILED:
      return  {
        ...state,
        failed : true
      };
    default :
      return state;
  }
}

This is the root reducer

import { combineReducers } from 'redux';
import movieReducer from './movieReducer';

export default combineReducers({
  movie : movieReducer
});

action component

import axios from 'axios';

import { FETCH_REQUEST_BEGIN, FETCH_REQUEST_FAILED } from '../constants';

const apiRequest = (url, type) => {
  return dispatch => {
    dispatch({
      type : FETCH_REQUEST_BEGIN
    });

    axios.get(url)
      .then((results) => {
        dispatch({
          type : type,
          payload : results.data
        });
      }).catch((error) => {
        dispatch({
          type : FETCH_REQUEST_FAILED,
          payload : error
        });
      });
  }
}

export default apiRequest;

Main component

import React, { Component } from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
import { API, DATA_FETCHED } from '../constants';
import { apiRequest } from '../actions';
import { connect } from 'react-redux';

class Home extends Component {

  componentWillMount() {
    const discoverUrlMovies =`https://jsonplaceholder.typicode.com/posts`;
    this.fetchData(discoverUrlMovies, DATA_FETCHED);
  }

  fetchData = (url, type) => {
    this.props.apiRequest(url, type);
  }

  shouldComponentUpdate(nextProps, prevProps){
    return nextProps != prevProps
  }

  render() {
    const { movie }  = this.props;

    //console out the props
    console.log('this.props', this.props);

    let displayMovies;

    if(movie === undefined || movie === null ){
      displayMovies = <ActivityIndicator size = 'large' color = '#121222'/>
    }else {
      displayMovies = <Text>Working</Text>
    }
    return (
      <View style = {{flex: 1}}>
        <Text>Home</Text>
        {
          //display result
          displayMovies
        }
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    movie : state.movieResults
  }
}
export default connect(mapStateToProps, { apiRequest })(Home);

What am I missing / doing wrong?

A: You need to define your mapStateToProps func as
movie : state.movie.movieResults

since you're combining them as
export default combineReducers({
  movie : movieReducer
});


text:
Q: Set to 2 decimals for integer in jQuery I am trying to calculate a total price depending on a users input, but I am experiencing the floating point syndrome. I have checked several other answers, but cannot make it work on my own code.
What am I doing wrong?
$(document).ready(function (e) {
    $("select").change(function () {
        var adultTicketsSubtotal = 0;
        var adultPrice = $("#price-adult").data("price");
        $("#ticket-select-adult").each(function () {
            adultTicketsSubtotal = adultPrice * parseInt($(this).val()).toFixed(2);
        })
        $("#adult-total .total").html(adultTicketsSubtotal);
    });
});

A: Here's one possible approach:
$(function() {
  var $subtotalView = $("#adult-total .total");
  var adultPrice = parseFloat( $("#price-adult").data("price") );
  // TODO: handle NaN case somehow: what if server sets this incorrectly?

  $('#ticket-select-adult').change(function() {
    var ticketsCount = parseInt( this.value, 10 );
    var subtotal = isNaN(ticketsCount) ?
      ' n/a ' :
      (ticketsCount * adultPrice).toFixed(2);
    $subtotalView.text(subtotal);
  });
});

Several minor changes here: the DOM traversals are minimized, this.value replaces $(this).val() etc. What's important is type fixation: adultPrice is always a float, ticketsCount always an int (or NaN for placeholder values, but this case is handled), and subtotal is always a string of the given format.

A: You need to use the .toFixed() method like:
$("#adult-total .total").html(adultTicketsSubtotal.toFixed(2));

A: In place of parseInt , Use parseFloat . Do multiplication and then use toFixed
parseInt changes the number to an integer.
adultTicketsSubtotal = (adultPrice * (parseFloat($(this).val()))).toFixed(2);

A: Try this:
adultTicketsSubtotal = adultPrice.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});


text:
Q: Setter method is odd, can someone explain I'm taking a look at the developer library for iOS. A property called masterBirdSightingList was created with type NSMutableArray.Thats fine, in the implementation they added this peice of code
- (void)setMasterBirdSightingList:(NSMutableArray *)newList {
    if (_masterBirdSightingList != newList) {
        _masterBirdSightingList = [newList mutableCopy];
    }
}

In order to

To implement a custom setter for the master list property ... (and) to override its default setter method to make sure that the new array remains mutable.

I'm not quite sure why this is fully necessary. Surely the array cannot suddenly change from a mutable array to something static. Is this method necessary?
Could you also help clarify whether the method setMasterBirdSightingList is called every time the masterBirdSightingList is set?
The tutorial I'm talking about is available here about halfway down the page.
Thank you

A:
Could you also help clarify whether the method setMasterBirdSightingList is called every time the masterBirdSightingList is set?

Yes, it is - in Objective-C, property access is implemented using getter and setter methods. No exception. The dot notation is just syntactic sugar for - (T)foo and - (void)setFoo:(T)arg.

I'm not quite sure why this is fully necessary.

Because if you just declared a copy property, then upon setting the array, it would be sent the copy message, and that returns an immutable copy (in Cocoa [Touch], it's a common convention that copy returns an immutable copy, even if the original object was mutable.)
This is why explicitly sending mutableCopy to the argument is needed.


text:
Q: On click sub menu not showing I am using .click to show sub menu. But when I perform a click on the menu the submenu ie. the second
 wont open. I don't know whats wrong Here is my code on JSfiddle.
Now, what I need is: when I click on the menu the sub menu should open and when second one is clicked, it should open, but first child should disappear.

A: Like this?
$(function () {
    //Hide all the sub menus
    $('li ul').hide();

    $("#leftmenuidfrmslt li").has("ul").click(function (e) {
        $("#leftmenuidfrmslt li ul:visible").slideUp("fast");
        $(this).children("ul").slideDown("fast");
    });
});

JSFIDDLE

A: UPDATED
See this fiddle.
$('li ul').hide();

$("#leftmenuidfrmslt li").click(function(e) {
    var submenu = $(this).children("ul");
    if (!$(submenu).is(":visible")) {
        hideSubMenus();
        submenu.slideDown("fast");
    } else {
        submenu.slideUp("fast");
    }
    e.stopPropagation();
});

$('html').click(function() {
    hideSubMenus();
});

A: You can try something like this :
$(function () {
   $('li ul').hide();

   $("#leftmenuidfrmslt li").has("ul").click(function(e) {
        var submenu = $(this);

        $("#leftmenuidfrmslt li ul:visible").slideUp("fast");

        submenu.children("ul").slideDown("fast");

   });
});

A: Have a look at This fiddle. It's a lot easier to label things with classes to denote their function, and makes for much more re-usable code. So for example:
.menu { /* my menu class */ }
.menu-item { /* a class for items in a menu */ }
.submenu { /* a class marking a submenu */ }

Then you can have your javascript code operate on those classes, rather than having to have convoluted code that follows hierarchies.
$(document).ready(function () {

    $(".menu > .menu-item").addClass("block-vertical-center");

    //Vertically center any blocks we are supposed to
    $(".block-vertical-center").wrapInner('');

    //Hide all the sub menus to start with
    $(".submenu").hide();

    $("#leftmenu .menu > .menu-item").on("click",function(e) {
        var submenu = $(e.target).find(".submenu");
        var isVisible = submenu.is(":visible");

        //Hide all the sub menus so we don't have multiples open
        $("#leftmenu .submenu").slideUp("fast");
        if (submenu.length > 0){
            if (!isVisible){
                submenu.slideDown("fast");
            }
            e.stopPropagation();
        }
    });
});

Also, for your vertical-alignment problem: Don't use line-height to vertically-align the contents of a block item. If your text goes to more than one line, it has issues. Instead, you can define a marker class (I often use "block-vertical-center" or something like that) do something like this:
span.table-span {
    padding:0;
    margin:0;
    border:0;
    vertical-align:middle;
    display:inline-table;
    height:100%;
    width:100%;
}

span.table-cell-span {
    padding:0;
    margin:0;
    border:0;
    vertical-align:middle;
    display:table-cell;
    height:100%;
    width:100%;
}

And then in your javascript, you can do:
$(".block-vertical-center").wrapInner('');

And then you simply define any block whose contents should be vertically centered that "block-vertical-center" class. What this does, is wrap the contents of your block in an inline-table. the vertical-align properties only really work properly in table cells, so we wrap a table around our content and it will magically vertically align, without having to worry about weird line-spacing issues.

A: I have updated the JS code as below
$(function() {
    $("li ul").hide();
    var submenu = $("li ul");

    $("#leftmenuidfrmslt li").on("click", function(e){
        if($(this).children("ul").length){
            submenu.slideUp("fast");
            $(this).children("ul").slideDown("fast");
        }
    });
});

Hope this help!


text:
Q: Check wrong input and stuck in infinite loop (C) I cannot use string or char input. If I use input like "c" then
int x,y,z;
while (1)
{
    z=scanf("%d%d", &x,&y);
    if(z == 0){
        printf("correct!\n");
    }
    else{
        printf("Incorrect!\n");
    }
}

A: Check properly against success, not 0.
On failure, consume characters until end-of line.  If scanf("%c", ...) or the like not allowed due to "I cannot use string or char input.", you are out of luck.
Exit the loop on success or end-of-file
do {
  z = scanf("%d%d", &x,&y);
  //if(z == 0){
  if (z == 2) {
    printf("correct!\n");`
  } else if (z != EOF) {
    printf("Incorrect!\n");
    char ch;
    while ( scanf("%c", &ch) == 1 && ch != '\n') {
      ;
    }
  }
} while (z != 2 && z != EOF);

A: I don't know what exactly you are looking for. I also don't know exactly what this code does, but if you want to stop the infinite loop, hope this helps.
#include <stdio.h>

int main () {
   int x,y,z;
    while (1) {
        z = scanf("%d%d", &x,&y);
        if(z == 0) {
            printf("correct!\n");
            break;
        } else {
            printf("Incorrect!\n");
        }
    }
}


text:
Q: Where to get Toshiba monitor driver software for MacBook Pro running OS 10.7.4 I am trying to connect my MacBook Pro running OS 10.7.4 to a Toshiba monitor. Where can I get  the necessary driver software?

A: You don't need a driver or any software for a monitor to work. Unless you have a touchscreen monitor, for instance.
As long as you have the right hardware connection, you're good to go.
If you don't know what connectors you're dealing with:
The MacBook Pros from 2008 till now all have Mini DisplayPort ports. In addition, the mid-2012 models also have an HDMI port: MacBook Pro on Wikipedia.
And for the monitor, I'd guess you probably have a VGA connector. But it could also be DVI, HDMI, or something else (post a picture?).
Anyway, you'll probably need an adapter to connect your monitor. I'd suggest http://www.monoprice.com/.


text:
Q: INNER JOIN with another table gives one field twice? I am very new to MySQL (sql in general) and I am trying to work something  out.
I have 2 tables, the first table contains a list of 'clients', the second table a list of 'users'. In the first table there are columns that contain the userID number of the 'contract manager' and the 'business development'. The ID is just a number, that references the ID number in the 'users' table. The users table then stores the First name, last name, etc of the user in question.
I am trying to run a query that will return the first and last names of both the contract manager, and the business development manager, and then use them in PHP.
I have the following query;
SELECT
    *
FROM
    clients
INNER JOIN
    tenantusers AS cm ON cm.tenusr_ID = clients.cli_ContractManager
INNER JOIN
    tenantusers AS bd ON bd.tenusr_ID = clients.cli_BusinessDevelopment
ORDER BY cli_Name;

Which in MySQL dashboard returns the correct results, however I can't use this in PHP because
$t = $row['tenusr_FirstName'] . " " . $row['tenusr_LastName'];

Returns the last result of the query, and not the previous. And truth told, I have no idea how to get them.  I've tried to use db.tenusr_FirstName and it throws errors.
Any help would be appreciated.
+--------+----------+------------------+---------------+----------------------+-------------------------+
: cli_ID : cli_Name : cli_AddressLine1 : cli_Town      : cli_ContractManager  : cli_BusinessDevelopment :
+-------------------------------------------------------------------------------------------------------+
: 1      : ACME     : On a street      : Makeuptington : 1                    : 2                       :
+--------+----------+------------------+---------------+----------------------+-------------------------+

+-----------+-----------------+-----------------+--------------+
: tenusr_ID : tenusr_Username : tenusr_LastName : tenusr_Email :
+--------------------------------------------------------------+
: 1         : Sam             : Smithers        : make@it.com  :
+--------------------------------------------------------------+
: 2         : Tom             : Watson          : tom@fake.net :
+--------------------------------------------------------------+

I've added the tables - top is the clients table, second the users.

A: You can't have columns with the same name in PHP. You'll want to SELECT only the columns you need, and alias the name columns with AS
SELECT
    cm.tenusr_Username AS contract_FirstName,
    cm.tenusr_LastName AS contract_LastName,
    bd.tenusr_Username AS business_FirstName,
    bd.tenusr_LastName AS business_LastName
    ....

You can then use
$t = $row['contract_FirstName'] . " " . $row['contract_LastName'];

A: The other answer is also right.  I left clients.* in which will select all rows from clients if you need them, but you should omit it if you don't need that.
SELECT
    clients.*,  cm.FirstName as CMFirstName, cm.LastName as CMLastName, bd.FirstName as BDFirstName, bd.LastName as BDLastName
FROM
    clients
INNER JOIN
    tenantusers AS cm ON cm.tenusr_ID = clients.cli_ContractManager
INNER JOIN
    tenantusers AS bd ON bd.tenusr_ID = clients.cli_BusinessDevelopment
ORDER BY cli_Name;

In PHP
$bd = $row['BDFirstName'] . " " . $row['BDLastName'];
$cm = $row['CMFirstName'] . " " . $row['CMLastName'];

If not all users will have a contract manager and business development person you should change your INNER JOIN to a LEFT JOIN so it will include clients without one or the other or without both.


text:
Q: Corte fixo no KCFinder No kcfinder quando você seleciona a imagem, ele mostra um corte na tela para você encaixar a foto.
Já procurei muito, fui no config em todos os arquivos e não descobri como alterar o width e o height deste corte.
Como faço para alterar estes tamanhos?


text:
Q: Check if at least one member variable of struct is true In my code I use the following type of struct that is initialized at program start.
struct Parameters
{
    Parameters()
    {
         bla = false;
         foo = false;
         bar = false;
         // and so on ...
    }
    bool bla;
    bool foo;
    bool bar;
    // and so on ...
};

The actual struct in my program contains about 100 boolean variables. During runtime the parameters of some variables may changed to true.
I would like to know if there is a simple way to check if at least one of the variables of my struct is true. Does C++ provide the functionality to iterate over a struct so that I can avoid checking about 100 variables manually?
I imagine something like
for (bool item : Parameters)
{
    if (item == true)
    {
        return true;
    }
}

A: Edit: I have completely changed this answer as I have been told the previous answer could lead to problems on some compiler settings.
The way you do this is by creating a pointer to member array of all struct members. This way you can easily loop through them all. Of course this isn't ideal because when you have a lot of members in a struct it can get quite long so I would suggest using a boolean map but if you really want a struct you do it like this.
First create a global pointer to member array of all members:
constexpr bool yourstruct::* arrName[<yourNumberOfElements>] = {
  &yourstruct::elem1,
  &yourstruct::elem2,
  &yourstruct::elem3,
  // continue until you have all your members here
};

Then you can create a function like this:
bool isAtLeastOneTrue(struct yourstruct* p1, int size){
  for(int i = 0; i<size;i++){
    if(p1->*arrName[i])
      return true;
  }
  return false;
}

And then you can call the function to see if any member is true.
isAtLeastOneTrue(&yourstructInstance, <yourStructSize>)

Here is some an example of how to use this
struct test{
  test(){
    a1 = false;
    a2 = false;
    a3 = false;
    a4 = false;
    a5 = false;
    a6 = false;
    a7 = false;
    a8 = false;
    a9 = true;
    a10 = false;
    a11 = false;
  }
  bool a1;
  bool a2;
  bool a3;
  bool a4;
  bool a5;
  bool a6;
  bool a7;
  bool a8;
  bool a9;
  bool a10;
  bool a11;

};

constexpr bool test::* ptma[11] = { // pointer to member array
  &test::a1,
  &test::a2,
  &test::a3,
  &test::a4,
  &test::a5,
  &test::a6,
  &test::a7,
  &test::a8,
  &test::a9,
  &test::a10,
  &test::a11
};

bool isAtLeastOneTrue(struct test* p1, int size){
  for(int i = 0; i<size;i++){
    if(p1->*ptma[i])
      return true;
  }
  return false;
}

int main() {
  test a;

  cout << isAtLeastOneTrue(&a, 11) << endl;
}


text:
Q: Is there a quick way to delete large Workflow Process history stack? Is there any quick way/trick to delete around 85K entries for the workflow process history? Trying from the GUI gives a storage issue and to resolve this issue need to bounce the box.
Also trying the PowerTool crashes after a long time. Thought to ask the wider community. appreciate for your thoughts.
Thanks
Vin

A: Which version of Tridion? 2011?
You could probably get away with a CoreService client app that does this regularly for you. By "PowerTool" I assume you mean the Purge tool?
Also - I would likely contact Customer Support about the errors you see, doesn't seem like using the GUI or the Purge Tool should fail.
If you're on 2011 SP1 you could use the following code:
using System;
using System.ServiceModel;
using System.Xml;
using Tridion.ContentManager.CoreService.Client;

namespace DeleteWorkflowHistory
{
    class Program
    {
        private const string NetTcpEndpoint =
            "net.tcp://localhost:2660/CoreService/2011/netTcp";
        private static readonly EndpointAddress EndpointAddress =
            new EndpointAddress(NetTcpEndpoint);

        static void Main(string[] args)
        {
            var binding = new NetTcpBinding
            {
                MaxReceivedMessageSize = 2147483647
            };

            var quota = new XmlDictionaryReaderQuotas
            {
                MaxStringContentLength = 2147483647,
                MaxArrayLength = 2147483647
            };
            binding.ReaderQuotas = quota;
            var client = new SessionAwareCoreServiceClient(binding, EndpointAddress);
            Log("Connected to Tridion Content Manager version: " + client.GetApiVersion());
            ProcessesFilterData filter = new ProcessesFilterData
            {
                BaseColumns = ListBaseColumns.IdAndTitle,
                ProcessType = ProcessType.Historical
            };
            foreach (IdentifiableObjectData data in client.GetSystemWideList(filter))
            {
                var processHistory = data as ProcessHistoryData;
                if (processHistory != null)
                {
                    Log("Deleting history: " + processHistory.Id + " / " + processHistory.Title);
                    client.Delete(processHistory.Id);
                }
            }
            client.Close();
        }

        private static void Log(string message)
        {
            Console.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss.fff"), message));
        }
    }
}

N

A: If you can't use the Core Service, have a look at this blog entry, which describes using the Powershell to force workflow processes to complete. With some very minor modifications, the same technique would work for deleting workflow processes.


text:
Q: Python pip install error shlex.py Can't install anything via pip install or pip3 install, it throws the following error:
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 179, in main
    status = self.run(options, args)
  File "/usr/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 255, in run
    with self._build_session(options) as session:
  File "/usr/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 93, in _build_session
    insecure_hosts=options.trusted_hosts,
  File "/usr/lib/python3.7/site-packages/pip/_internal/download.py", line 344, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/usr/lib/python3.7/site-packages/pip/_internal/download.py", line 108, in user_agent
    zip(["name", "version", "id"], distro.linux_distribution()),
  File "/usr/lib/python3.7/site-packages/distro.py", line 122, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/usr/lib/python3.7/site-packages/distro.py", line 677, in linux_distribution
    self.version(),
  File "/usr/lib/python3.7/site-packages/distro.py", line 737, in version
    self.lsb_release_attr('release'),
  File "/usr/lib/python3.7/site-packages/distro.py", line 899, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/usr/lib/python3.7/site-packages/distro.py", line 552, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/usr/lib/python3.7/site-packages/distro.py", line 1012, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/usr/lib/python3.7/subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "/usr/lib/python3.7/site-packages/run/__init__.py", line 145, in __new__
    process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell)
  File "/usr/lib/python3.7/site-packages/run/__init__.py", line 121, in create_process
    shlex.split(command),
  File "/usr/lib/python3.7/shlex.py", line 305, in split
    return list(lex)
  File "/usr/lib/python3.7/shlex.py", line 295, in __next__
    token = self.get_token()
  File "/usr/lib/python3.7/shlex.py", line 105, in get_token
    raw = self.read_token()
  File "/usr/lib/python3.7/shlex.py", line 136, in read_token
    nextchar = self.instream.read(1)
AttributeError: 'tuple' object has no attribute 'read'

I`m on Manjaro Linux, using KDE. Some more info, if needed:
NAME="Manjaro Linux"
ID=manjaro
ID_LIKE=arch
PRETTY_NAME="Manjaro Linux"
ANSI_COLOR="1;32"
HOME_URL="https://www.manjaro.org/"
SUPPORT_URL="https://www.manjaro.org/"
BUG_REPORT_URL="https://bugs.manjaro.org/"

A: I was searching on internet And i found the following useful information.
https://pip.pypa.io/en/latest/installing/
https://www.tecmint.com/install-pip-in-Linux/
The information suggest for correct pip function to have some additional requierements. Additionally dictates that get-pip.py does not coordinate with some operative systems.

A: Your Python installation is borked because of the subprocess.run package. If you have installed subprocess.run via pip, uninstall it:
sudo pip3.7 uninstall subprocess.run

If you didn't install it explicitly, find out what package owns the code:
pacman -Qo /usr/lib/python3.7/site-packages/run/__init__.py

then uninstall it:
sudo pacman -R pkgname

Related issue with the subprocess.run package (unresolved): https://github.com/xando/subprocess.run/issues/5


text:
Q: In Kotlin, are data structures such as stack, queue, heap, tree, etc. supported through standard library? In Kotlin, are data structures such as stack, queue, heap, tree, etc. supported through standard library?
As a person mostly familiar with Python but didn't use Java before jumping into Kotlin, this question came to my mind.
For example, if one wants to use Kotlin for competitive programming, or if one doesn't want to reinvent the wheel implementing the common data structures, are these supported through the standard library? Or are they not supported due to some design reason of Kotlin? At least I wasn't able to find these in the documentation. Then if one is using Kotlin on JVM, do people usually use the implementations from Java's library?

A: Adding to the above answer, Java's implementation of Heap is PriorityQueue, passing a comparator appropriately, and you can use it in Kotlin no problem.
Docs: https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
Check more: https://www.geeksforgeeks.org/priority-queue-class-in-java-2/

A: Kotlin mostly reuses Java's Collection API in this case, so you can utilize it freely. Collection API has 4 major interfaces:

*

*List - an ordered sequence of elements.

*Set - collection that has no duplicates.

*Queue - a collection designed for holding elements prior to processing. You can utilize it's FIFO interface. Also it is extended with Deque interface which supports elements' insertion and removal at both ends.

*Map - an object that maps keys to values.

Most of the needs can be satisfied with this interfaces' implementations.
Such as LinkedList as a classic implementation in terms of Doubly Linked List data structure; also it implements Deque. ArrayList implements List interface using array internally; it has much faster elements access due to arrays' indexed access efficiency nature (except of the case when you are accessing either first or last elements, because than it's identical), but insertions can really cost you on insertions not in the end or on insertions when the capacity of the internal array is exceeded, because it then should get reinitialized and refilled, which is a hit for both time and space. Java's internal System#arraycopy is internally relatively fast though.
Stack and Queue both can be also fulfilled with ArrayDeque, which is, again, an array-backed implementation, but in this case of Deque.
TreeMap uses Red-Black tree algorithm internally; TreeSet uses TreeMap internally is you need single elements rather than associations.
For hashtable-based implementations you can use HashMap for associations and HashSet for sole elements respectively (same story with reuse as for tree-based implementations).
For all the other things (thread-safe too - designed for concurrency or simple locking-applying decorators) you can search for an appropriate implementations of these interfaces actually - the standard library is big enough.


text:
Q: How to integrate a special font (.ttf) in an Android application? I want to add a file .ttf to be able to customize the font of my textView in my application.
I wonder how the exploited?
I download the file on DaFont.
Thank you in advance for your help!

A: First, copy the font to your /assets folder in your project, then to set the Typeface of your TextView, you can do the following:
Typeface myFont = Typeface.createFromAsset(getAssets(), "dafont.ttf");
myTextView.setTypeface(myFont);

Edit: corrected directory


text:
Q: What is the best practice to update a Vertex after is detached from DB with Tinkerpop Frames? Let's exemplify

*

*I receive a Vertex with Tinkerpop Blueprint, then I use Frames to convert it in an entity.

*I close the database (so from now the node is detached from the DB)

*and I show the node on a web page to let the user modify it.

The user makes some modifications, then  I shoud persist the changes.
The problem is that the Instance of the database is already closed, so the entity is detached from the database: What is the best practice (considering performance and memory usage too) to update the node?
This may be the code example:
 FramedGraph<OrientGraph> graph = factory.getFramedGraph();
 User user = graph.addVertex(null, User.class);
 graph.shutdown();

then I want to update later the node:
 user.name = "Donald Duck";
 user.... ?

Thank you,
Andrea

A: I found this way, that seems quite efficient:
public User persistUser(User user){

    FramedGraph<OrientGraph> graph = factory.getFramedGraph();

    user = graph.frame(user.asVertex(), User.class);
    factory.persist();
    graph.shutdown();

So the framework automatically merge back the entity to the database.
Then you have to persist.


text:
Q: Calculating sum and grouping of dynamic range I'm trying to create a Macro to select and group a certain amount of cells with implementation of some formulas, a simple example picture is included below. The only thing that should determine the range is column A.
Let's say the active cell is somewhere between row 2 and row 9, the Macro should be able to find out that row 1 and row 10 are the boundaries of that range because of the presence of values in column A and so creating and selecting a range going from row 2 till row 9.
I tried to loop through the cells going down to find the first row with an active value in column A.
After determining the range/group, a formula, calculating the product of those rows, and to finish it of, calculatie a sum of those products in the title row of that group (being the upper row with an active value in column A).
I've included my code so far below, after a bit of trial and error and googling/searching for similar problems on this forum, but my code still doesn't seem to work like I want it to. My not that great knowledge of VBA/scripting doesn't really help :)
A picture is included below with the wanted generated formulas colored in blue.
    Dim StartCell, EindCell As Range
    Dim teller As Integer
    Dim teller2 As Integer
Cells(Application.ActiveCell.Row, 1).Select
teller = 0
Do While Selection.Offset(teller, 0).Value = ""
    teller = teller - 1
Loop
Selection.Offset(teller, 0).Select
Set StartCell = ActiveCell
teller2 = 0
Do While Selection.Offset(teller, 0).Value = ""
    teller = teller + 1
Loop
Selection.Offset(teller, 0).Select

    Set EindCell = ActiveCell
    Range(StartCell, EindCell).Select
    Selection.Rows.Group

    Cells(Application.ActiveCell.Row, 8).Select
    ActiveCell.Formula = "=PRODUCT(RC[-4]:RC[-1])"
    Selection.NumberFormat = "0.00"
    Range(StartCell.Row + 1, 9).Formula = "=sum(cells(StartCell.row,8):Cells(EindCell.row,8))"

A: Please try this code.
Sub SumGroup()
    ' 12 Jan 2018

    Dim Rng As Range
    Dim Rstart As Long, Rend As Long
    Dim R As Long

    R = ActiveCell.Row
    If Len(Cells(R, "A").Value) Then R = R + 1
    Rstart = R
    Do Until Len(Cells(Rstart - 1, "A").Value)
        Rstart = Rstart - 1
    Loop
    Rend = R
    R = Cells(Rows.Count, "D").End(xlUp).Row
    Do Until Len(Cells(Rend + 1, "A").Value)
        Rend = Rend + 1
        If Rend = R Then Exit Do
    Loop

    Set Rng = Range(Cells(Rstart, "H"), Cells(Rend, "H"))
    With Rng
        .Formula = "=PRODUCT(RC[-4]:RC[-1])"
        .NumberFormat = "0.00"
        Cells(Rstart - 1, .Column + 1).Formula = "=SUM(" & .Address & ")"
        Cells(Rstart - 1, .Column + 1).NumberFormat = "0.00"
    End With
End Sub

A: This works for however many groups you have in one sheet. If the user selects a cell past the last used row then it'll assume they meant the last group
Sub tester()

    Dim myRow As Long
    Dim topRow As Long
    Dim botRow As Long
    Dim lastRow As Long

With ActiveSheet

    myRow = Selection.Row   ' get selected row
    lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row ' get last row in col A
    If lastRow <= myRow Then myRow = lastRow - 1 ' check that selected row is not past the last row

RETRY:
    topRow = myRow      ' initiate top and bottom row variables to same as select row
    botRow = myRow + 1

    Do While .Cells(topRow, 1).Value = "" ' cycle up until finds entry
        topRow = topRow - 1
    Loop

    Do While .Cells(botRow, 1).Value = "" ' cycle down until finds entry
        botRow = botRow + 1
    Loop

    topRow = topRow + 1 ' correct range
    botRow = botRow - 1

    If topRow - 1 = botRow Then myRow = myRow - 1: GoTo RETRY ' if user selected last entry in group in col A then it'll assume this was toprow, correct selection row and try again.

    With .Range(Cells(topRow, 8).Address, Cells(botRow, 8).Address)
        .Formula = "=PRODUCT(RC[-4]:RC[-1])"
        .NumberFormat = "0.00"
    End With

    .Range("I" & topRow - 1).Formula = "=SUM(" & Cells(topRow, 8).Address & ":" & Cells(botRow, 8).Address & ")"

End With

End Sub

A: I believe the code below will do what you expect:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your Sheet, change Sheet1 as required
LastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
'find the last row in column D
ws.Cells(1, 9).FormulaR1C1 = "=SUM(R[1]C[-1]:R[50]C[-1])"
'enter the Sum formula on row 1 column 9, Range I1
For i = 1 To LastRow 'loop from row 1 to last
    If ws.Cells(i, 7) <> "" Then ws.Cells(i, 8).FormulaR1C1 = "=PRODUCT(RC[-4]:RC[-1])"
    'if there is data on Column 7 (G) then add formula to column 8 (H)
Next i
End Sub


text:
Q: Save model to pickl module I used an extreme learning machine(ELM) for predicting video quality, and I want to save and load my model to pickle. I need to add python code to save and load my model to pickel library. Pleas any one can help me.
My code:
scaler = MinMaxScaler()
scaler_X = MinMaxScaler()
scaler_Y = MinMaxScaler()
# fit_transform for training data:
X_train = scaler_X.fit_transform(train.values[:,:-1])
y_train = scaler_Y.fit_transform(train.values[:,-1:])
#print(y_train)
# only transform for test (unseen) data:
X_test = scaler_X.transform(test.values[:,:-1])
y_test = scaler_Y.transform(test.values[:,-1:])

input_size = X_train.shape[1]

#---------------------------(Number of neurons)-------
hidden_size = 26

#---------------------------(To fix the RESULT)-------
seed =26   # can be any number, and the exact value does not matter
np.random.seed(seed)

#---------------------------(weights & biases)------------
input_weights = np.random.normal(size=[input_size,hidden_size])
biases = np.random.normal(size=[hidden_size])

#----------------------(Activation Function)----------
def relu(x):
   return np.maximum(x, 0, x)

#--------------------------(Calculations)----------
def hidden_nodes(X):
    G = np.dot(X, input_weights)
    G = G + biases
    H = relu(G)
    return H

#Output weights
output_weights = np.dot(pinv2(hidden_nodes(X_train)), y_train)

#------------------------(Def prediction)---------
def predict(X):
    out = hidden_nodes(X)
    out = np.dot(out, output_weights)
    return out
#------------------------------------(Make_PREDICTION)--------------
prediction = predict(X_test)
unscaler_prediction=prediction*(5-1)+1
unscaler_y_test=y_test*(5-1)+1


text:
Q: Return zero or positive number? I was initially thinking that the code below would return 0, my question, is there a function that I can use to only receive zero/positive results here?
NSUInteger pruneSize = 5 - 20; // Returns: -15

Currently I am just checking the result myself, but was wondering if I was missing something simpler.
NSUInteger pruneSize = 5 - 20;
if(pruneSize >= 0) {
    // Do zero/positive Stuff ...
}

A: pruneSize >= 0 is always true as pruneSize is unsigned. You should get a warning here. You need to change the type to NSInteger, that is the signed integer. If you want to clip the lower value to zero for a signed int then you can do this:
NSInteger pruneSize = 5 - 20; // signed int
pruneSize = pruneSize < 0 ? 0 : pruneSize;

A: You can use abs(pruneSize) which will return you positive or zero number in any case.
EDIT:
NSUInteger pruneSize = 5-20;
if(pruneSize < 0)
{
     pruneSize = 0;
}
NSLog(@"%d",pruneSize);

Hope this helps you.

A: If you want your function to return always zero if your result is in negative(less than 0) then return zero or else return result
int n=0;
if(result > 0){ //positive
   n = result
else
   n = 0
return n

or use the abs method


text:
Q: Compare string character per character, split strings by length would work also I have two strings and need to compare them AND state which characters are correct.
My code is:
char Palavra = "exemplo";
int Tamanho = strlen(Palavra),i;
printf("Which is your guess?\n");
char Palpite[Tamanho];
fgets(Palpite,Tamanho,stdin);
char Mensagem[50];
strcpy(Mensagem,"The following characters are correct: ");
    for(i=0;i<=Tamanho;i++){
        if(Palavra[i] == Palpite[i]) sprintf(Mensagem,"%s %i",Mensagem,i+1);
    }
    printf("%s",Mensagem);

I need to compare variables Palavra and Palpite, character per character and then say with one is correct.
Something like this:
Palavra = celular
Palpite = cilular
Answer should be: "The following characters are correct: 1 3 4 5 6 7"
But I am getting: "The following characters are correct: 1 3 4 5 6 8"
Any help would be greatly appreciated.

A: Maybe this is the issue:
int Tamanho = strlen(Palavra),i;
...
for(i=0;i<=Tamanho;i++){
   if(Palavra[i] == Palpite[i]) ... do something
}

Palvara[Tamanho] is going to be a null char.  Valid indices for Palvara with a non-null character are from [0..Tamanho-1].   This corrects the bug:
for(i=0; i < Tamanho; i++){
   if(Palavra[i] == Palpite[i]) ... do something
}

Also, don't forget that Palpite's length might be less than Palvara's length.  Make sure you break out of your for-loop before dereferencing Palpite[i] if i >= strlen(Palpite)
Better:
int len = strlen(Palpite);
int count = (Tamanho <= len) ? Tamanho : len;
for(i=0; i < count; i++){
   if(Palavra[i] == Palpite[i]) ... do something
}

A: Probably it does not work because you have assigned a pointer to an array to a char value.
Also it could be that you are stepping out of array bounds with for i<=Tamnho is causing some comparison problems/possibly crashes (if you are trying to change them).
But the logic behind the code is correct, so I don't see any other reason as to why it does not work

A: It worked as expected with this code, although that last if is a clear work around I am not really confortable using.
    int Tamanho = strlen(Palavra),i;
    printf("Which is your guess?\n");
    char Palavra = "exemplo";
    char Palpite[Tamanho];
    fgets(Palpite,Tamanho,stdin);
    char Mensagem[50];
    strcpy(Mensagem,"The following characters are correct: ");
    for(i=0; i<=Tamanho; i++) {
        if(Palavra[i] == Palpite[i]) {
            if(i==Tamanho) {
                sprintf(Mensagem,"%s %i",Mensagem,i);
            } else {
                sprintf(Mensagem,"%s %i",Mensagem,i+1);
            }
        }
    }
    printf("%s",Mensagem);

A: Code incurs undefined behavior (UB) due to attempting to access outside an array's range.
When i==Tamanho, Palpite[i] is bad.
char Palpite[Tamanho];
for(i=0;i<=Tamanho;i++){
  if(Palavra[i] == Palpite[i]) sprintf(Mensagem,"%s %i",Mensagem,i+1);
}

Code incurs undefined behavior (UB) due to attempting to access access and write to the same array with int sprintf(char * restrict s, const char * restrict format, ...);.  The restrict is a contract that the caller broke by using the destination as an later augment.
sprintf(Mensagem,"%s %i",Mensagem,i+1);
//      ^^^^^^^^         ^^^^^^^^  UB

Alternative code could have written to the end.
size_t len = strlen(Mensagem);
sprintf(Mensagem + len," %i",i+1);

Better code would use snprintf() to issue no buffer overrun.

A well warning enabled compiler would have warned about the type mismatch.  Save time, enable all warnings.
char Palavra = "exemplo";

UB for writing outside arrays bounds.  char Mensagem[50]; is too small for  "The following characters are correct:  1 3 4 5 6 8" which needs 51.
Consider scaling Mensagem[]; with a  more geneorus size and use snprintf() to avoid overflow.


text:
Q: How to remove the brackets at the beginning and the end of lines of csv files? [solved] (differences between writerow and writerows for array) The csv file is like below:
[0,0,0]
[]
[1,1]
[]
[]

I tried
with open('test.csv','r') as r, open('write.csv', 'w') as w:
    for line in r:
        line = line[1:-2]
        w.write(line + '\n')

but it outcomes
0,0,0
]
1,1
]
]

which should be:
0,0,0

1,1

That was weird for the empty list line, I have to do line[1:-3] to clean the line, but for the non-empty line with line[1:-2]
Here was how I wrote data into csv file:
list = [[0,0,0],[],[1,1],[],[]]

with open ('test.csv','a') as w:
    w = csv.writer(w, delimiter = '\n')
    w.writerow(list)
    w.close

A: Use rstrip() and lstrip() to remove specific characters from the dns.
line = line.lstrip('[').rstrip(']\n ')

This removes the [ at the beginning and the ] and newline at the end.

A: As mentioned, the problem is in the writing of the file in the first place. If this list only has a few base types (int, string, etc), you  can use ast.literal_eval to build the list again
>>> import ast
>>> with open("test.csv") as f:
...     mylist = [ast.literal_eval(line) for line in f]
...
>>> mylist
[[0, 0, 0], [], [1, 1], [], [], [0, 0, 0], [], [1, 1], [], []]


text:
Q: Need to insert space between inline elements I need to insert a dummy space between multiple span elements. ie; Need to insert a space between "Help" and "Feedback"
How can I do that?
http://jsfiddle.net/hsQ24/
HTML

    Help

    Feedback
    help

CSS
#header{
    background-color:red;
}

A: Give your span elements left and right margin:
#header span {
    margin: 0 10px;
}

JSFiddle demo.
If you're wanting to only add a space between the first and second span elements (ignoring the empty one in your example), you can make use of the :first-child selector to apply margin-right to the first span only:
#header :first-child {
    margin-right: 20px;
}

JSFiddle demo.
Alternatively you can modify your HTML to give your first span element a class which can be used instead of the :first-child selector.

A: you can use :before pseudo element as well. Check the DEMO.
CSS like
span:before{
    content:" ";
    display:inline-block;
    width:32px;
}

HTML Code

    Help

    Feedback
    help

In Addition if need to remove unnecessary span you can use :nth-of-type
#header span:nth-of-type(2)
{
  display:none;
  background-color:green;
}

Another JSBin link.

A: Use regular spaces or
http://jsfiddle.net/Quadraxas/hsQ24/5/

A: You can use padding
span {
    padding-left: 5px;
    padding-right: 5px;
}

..or just padding-right.

A: If you just want space before that specific element, give it a class and style that:

    Help
    Feedback
    help

#header{
    background-color:red;
}

.feedback {
    margin-left: 1em;
}

Updated example: http://jsfiddle.net/hsQ24/4/

A: span {
    padding-right: 50px;
}

A: I think &nbsp is the best answer for what you're searching, if you don't use divs to "store" that menus.
http://jsfiddle.net/AlphaCrack/hsQ24/8/

A: Wrap your elements inside a container then use CSS GRID, course and then use grid-gap:value that was created for your that specific purpose

span{
  border:1px solid red;
}
.inRow{
  display:grid;
  grid-template-columns:repeat(auto-fill,auto);
  grid-gap:10px /*This add space between elements, only works on grid items*/
}
.inColumn{
  display:grid;
  grid-template-rows:repeat(auto-fill,auto);
  grid-gap:15px;
}

  1
  2
  3

  4
  5
  6

As for your problem, you should use the row example

A: for parent div
display: inline-table;


text:
Q: show always scrollbar <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:fadeScrollbars="false" >
<Scrollview ...

i want to show the scrollbar always (android:fadeScrollbars="false")! I have also EditTexts on my screen, too. That is why I put (android:focusableInTouchMode="true" and android:focusable="true"). If i put this last 2 codes my scrollbar going to fade out, why? Do you have a solution?

A: please this in place of that one.
Achieved the desired result here and added in manifest for each activity
android:windowSoftInputMode="stateHidden"


text:
Q: How to fix this exercise with Endomorphic wrapper? This is a follow-up to my previous question.
Suppose I need to find an XML node by path. I can write a function to get a child node by name
import scala.xml.{Node => XmlNode}

def child(name: String): XmlNode = Option[XmlNode] = _.child.find(_.label == name)

I compose the child functions with kleisli; e.g.
scala> val a = <a0><a1><a2/></a1></a0>
a: scala.xml.Elem = <a0><a1><a2/></a1></a0>

scala> val find01 = Kleisli(child("a0")) >=> Kleisli(child("a1"))
findAB: scalaz.Kleisli[Option,scala.xml.Node,scala.xml.Node] = Kleisli(<function1>)

scala> find01(a)
res85: Option[scala.xml.Node] = Some(<a1><a2/></a1>)

Now I am using the endomorphic wrapper but it doesn't work:
 scala> List(child("a0"), child("a1")).foldMap(Endomorphic.endoKleisli[Option, XmlNode])
 res93: scalaz.Endomorphic[[α, β]scalaz.Kleisli[Option,α,β],scala.xml.Node] = Endomorphic(Kleisli(<function1>))

 scala> res93.run(a)
 res94: Option[scala.xml.Node] = None

Could you help to find the bug ?

A: In the first example, you are composing left-to-right (>=>).
But Endomorphic calls the compose method (a.k.a. <=<), which works right-to-left.
So your second example would capture <a1> first, then look for <a0> inside that, which clearly fails.
There are two ways to recover the left-to-right behavior. You can reverse the list before folding it, or wrap each element in a Dual.


text:
Q: Allow members to only see their own trips in Ruby on Rails App I have an app where members can create trips, but I need to limit access so that only the user that created their trip can see it, but it's not working as anticipated. I'm using the devise gem, so current_member is equivalent to @member or @suer.
This is the 'show' page for the trip:
<% if current_member.id == params[:member_id] %>

Here are your current trips

    <% @trips.each do |trip| %>
      <%= link_to trip.where, member_trip_path(current_member.id, trip.id) %>

    <% end %>
<% else %>

Sorry, this page isn't available.

<% end %>

This is the path:
member_trip GET    /members/:member_id/trips/:id(.:format)      trips#show

What I'm expecting is that if I have two member's: bob and susan. Susan can't see bob's trip show page by just typing the trip id in the url. She should see "Sorry, this page isn't available" on the page.

A: You need model associations.
Your members.rb model should have has_many :trips and trip.rb model should have belongs_to :member. You will need to have member_id column in your trips table.
In your controller, you will need to write:
@trips = current_member.trips # it will return trips created by the current member only.

You can read more about the has_many association here and the belongs_to association here.


text:
Q: Use of logical operators for recoding variables I'm currently creating a dummy variable to check for eligibility for data analysis. I want to create an additional factor variable to indicate the reason for ineligibility. But, when using the same logical operators for both variables, I can't seem to get matching results.
The first variable is the dummy:
data$elig <- factor(1, 1:2, labels = c("yes", "no"))

I first set all rows to yes, then recode ineligible rows with
data$elig[data$var1 == 20 | data$var2 > 1998 |
          (data$var2 == 1998 & as.numeric(data$var3) > 9) |
            (data$var2 == 1998 & is.na(data$var3)) | is.na(data$var4) |
             is.na(data$var5) | is.na(data$var6)] <- "no"

This gives me the following results for data$elig:
table(data$elig)
yes   no
2707  170

Now I create the second variable with some nested ifelses (btw, is there a simpler solution to do this?):
data$elig_cat <- ifelse(data$var1 == 20, 1,
                  ifelse(data$var2 > 1998 |
                           (data$var2 == 1998 & as.numeric(data$var3) > 9) |
                           (data$var2 == 1998 & is.na(data$var3)), 2,
                   ifelse(is.na(data$var2), 3,
                    ifelse(is.na(data$var4), 4,
                      ifelse(is.na(data$var5), 5,
                        ifelse(is.na(data$var6), 6, NA))))))

But table(data$elig_cat) only has 117 valid counts:
 1  2  4  5
75 22  9 11

My question is: Do I make a simple mistake anywhere (though I've looked for everything I could think of), or is this a problem of my approach? From my understanding, the second table should have 170 valid counts, as each logical operator used led to a no-count in the first variable.
If necessary, I can provide the data, but I think only the full dataset would make any sense. Maybe someone can point me to any irregularity I could look for in the data? I'm really at a loss here.


text: Q: How do you prove that for a fixed $k \in \mathbb{N}$, there is always $n,m \in \mathbb{N}$ such that $n^k - m^k$ is a prime number? I think I am understanding the question, generally since there are infinitely many primes, picking $m$ and $n$ will not help here. I was thinking that if we can show that there exists a natural number $n$ such that $n$ divides $n^k-m^k$ then that would be a counter example. But the statement seems true, does this proof require the fundamental theorem of arithmetic?


text:
Q: Transitioning child's CSS property I have following piece of CSS code:
#balancers div p {
  display: none;
}

#balancers div:hover p {
  display: block;
}

And markup:

ID

Description

It works as expected - when I hover over
 element, it'll show
 element. However, I'd like to use CSS transitions here (make
 slowly increase it's height, without manipulating height property).
How can I do that?

A: I made an example: CSS3 Transition Example
It is possible without JS.

A: You won't be able to create this sort of animation with basic CSS. You would need to use something like jQuery animate to get this effect:
http://api.jquery.com/animate/
$("div#balancers").hover(function(){
    $("div#balancers p").show();
    $("div#balancers p").animate({
        height:"200px"
    }, 1500);
});

A: you could use jQuery to achieve something like what your asking.
$("#balancers p").hover(function(){
   $(this).fadeOut(100);
   $(this).fadeIn(500);}
);

Ex: http://api.jquery.com/hover/

A: Your CSS markup is wrong. Correct would be:
div#balancers > p {
  display: none;
}

div#balancers:hover > p {
  display: block;
}

ID

Description


text:
Q: C# file copy error file is being used by another program I have a directory where i make/place some files.
When the filesystemwatcher sees a new file it copy's that file in a second directory.
But when i create a file directly in dir1 then it shuts down saying it is used by another program.
How do i get rid of this problem?
here is my code:
using System;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace ChaloSync
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private bool pause = false;
    String source = ConfigurationManager.AppSettings[@"Directory1"];
    String target = ConfigurationManager.AppSettings[@"Directory2"];

    private void start()
    {
        pause = true;
        Start.Text = "Pause";
        fileSystemWatcher1.EnableRaisingEvents = true;
    }

    static void config()
    {
        foreach (string key in ConfigurationManager.AppSettings)
        {
            string value = ConfigurationManager.AppSettings[key];
            MessageBox.Show(value);
        }
    }

    private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
            listBox1.Items.Add("File changed> " + e.FullPath + " -Date:" + DateTime.Now);
    }

    private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
    {
            listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
            File.Copy(e.FullPath , Path.Combine(target,e.Name));
    }

    private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
    {
            listBox1.Items.Add("File deleted> " + e.FullPath + " -Date:" + DateTime.Now);
    }

    private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
            listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
    }

    private void Start_Click(object sender, EventArgs e)
    {
        fileSystemWatcher1.Path = source;
        if (!pause)
        {
            start();
        }
        else
        {
            pause = false;
            Start.Text = "Start";
            fileSystemWatcher1.EnableRaisingEvents = false;

        }

        }
    }
}

A: If you have experienced locked issue when read or write a file, please check FileShare option.
Please kindly check this link.

A: Not the same problem, but caused by the same. The solution can be good for you.

A typical problem of this approach is that the file is still being
  copied while the event is triggered. Obviously, you will get an
  exception because the file is locked during copying. An exception is
  especially likely on large files.
As a workaround you could first copy the file and then rename it and
  listen to the renaming event.
Or another option would be to have a while loop checking whether the
  file can be opened with write access. If it can you will know that
  copying has been completed. C# code could look like this (in a
  production system you might want to have a maximum number of retries
  or timeout instead of a while(true)):

(Copied from here: File access error with FileSystemWatcher when multiple files are added to a directory)

A: Renaming and Creating are being done at the same time. So you can't copy it because it's already being used to rename it at that moment..


text:
Q: where is the function inet_ntoa really defined? I see this following line in /usr/include/arpa/inet.h:
extern char *inet_ntoa (struct in_addr __in) __THROW;

but where is it really defined?

A: The system headers merely declare the interface for invoking functions provided by the system. The actual implementation will be compiled into a (typically shared) library on the system. On some systems, the actual implementation is unavailable in source code form and  proprietary. Fortunately, on GNU/Linux, FreeBSD, and Mac OS X, one can actually find the original implementation of inet_ntoa.
For GNU/Linux, it the implementation is part of the GNU C Library (glibc).

A: It has been compiled and exists in Ws2_32.lib.
You could see what is a Library


text:
Q: Как присвоить selected select option по значению из массива PHP? Всем привет! Есть массив:
    Array (
[0] => Array ( [id] => 14 [c_name] => toto [url] => https://ranking.com [repetition] => 3 [ton] => 3 [type] => 2 [date] => 12.04.2018 )
[1] => Array ( [id] => 15 [c_name] => toto [url] => https://ranking.com [repetition] => 1 [ton] => 2 [type] => 4 [date] => 12.04.2018 )
[2] => Array ( [id] => 16 [c_name] => toto [url] => https://ranking.com [repetition] => 2 [ton] => 2 [ton] [type] =>4 [date] => 12.04.2018 ) )

Есть также таблица с селектами типа
echo "<select name=$arr[$i]['url'] class='custom-select ton' >
    <option  value='0' selected>Не определена</option>
    <option value='1'>Положительная</option>
    <option value='2'>Отрицательная</option>
    <option value='3'>Нейтральная</option>
    <option value='4'>Нерелевантная</option>
  </select>	";

В этом массиве есть [ton], значение которого должно быть значением option. Подскажите, пожалуйста, как сделать так чтоб селекту с этим значением был присвоен selected.
цикл и вывод таблицы мне не нужен. необходимо лишь разобраться с селектом

A: 1-й вариант - если вы уж прям вручную и никак по другому:
echo "<select name=$arr[$i]['url'] class='custom-select ton' >
  <option  value='0' <?if(empty($arr[$i]['ton'])){echo "selected";}?>>Не определена</option>
  <option value='1' <?if($arr[$i]['ton'] == 1){echo "selected";}?>>Положительная</option>
  <option value='2' <?if($arr[$i]['ton'] == 2){echo "selected";}?>>Отрицательная</option>
  <option value='3' <?if($arr[$i]['ton'] == 3){echo "selected";}?>>Нейтральная</option>
  <option value='4' <?if($arr[$i]['ton'] == 4){echo "selected";}?>>Нерелевантная</option>
</select>	";

а лучше все же определить массивчик:
$arr_z = array('Не определена', 'Положительная','Отрицательная','Нейтральная', 'Нерелевантная');
echo "<select name=$arr[$i]['url'] class='custom-select ton' >
   <?foreach($arr_z as $key => $val){?>
        <option  value='<?=$key?>' <?if($arr[$i]['ton'] == $key){echo "selected";}?>><?=$val?></option>
   <?}?>
</select>	";


text:
Q: Qual a relação entre JPA e ORM? Queria saber a relação entre JPA e ORM pois fiquei na duvida, se ambos ,tratam do mesmo assunto.

A: A API de Persistência do Java (JPA - Java Persistence API) é uma especificação de como o Mapeamento Objeto-Relacional (ORM - Object-Relational Mapping) deve ser implementado na plataforma JavaEE.
Portanto:

*

*ORM é um conceito geral

*JPA define um padrão de ORM, ou seja, como isso deve funcionar em Java na prática

*Hibernate, EclipseLink, Toplink, OpenJPA são implementações do padrão JPA

A: Resumo: JPA é uma especificação e ORM é a ferramenta (Hibernate, Entity, etc).
No contexto das aplicações Java, para facilitar o processo de transformação dos dados que trafegam entre as aplicações e os bancos de dados, podemos utilizar algumas ferramentas de persistência como o Hibernate ou o EclipseLink.
Essas ferramentas funcionam como intermediários entre as aplicações e os bancos de dados, automatizando diversos processos importantes relacionados à persistência dos dados. Elas são chamadas de ferramentas ORM (Object Relational Mapping).
Com o intuito de facilitar a utilização dessas ferramentas e torná-las compatíveis com os outros recursos da plataforma Java, elas são padronizadas pela especificação Java Persistence API (JPA).
Fonte: Apostila de Java - Persistência com JPA 2 e Hibernate


text:
Q: Go Lang: Can't change children's stdin I want to completelly drop STDIN in parent and children processes.
CONTEXT:
I am spawning children process from main Go process. It is spawned in Go routine. Somehow FDs (stdin in this case) are inherited by children process. My goal is to set stdin of children process to nil, in order to forbid any stdin to the children process.
I tried:
os.Stdin = nil

os.Stdin = os.NewFile(uintptr(syscall.Stdin), "/dev/null")

Only "solution" which I found is dirty:
func init() {
    go func() {
        for {
            io.Copy(os.Stdout, os.Stdin)
        }
    }()
}

Does anybody know better solution?
UPDATE:
os.Stdin = nil won't work if Go program is reading from /dev/tty
I am spawning FFUF
go func() {
    tty, err := os.Open("/dev/tty")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer tty.Close()

    inreader := bufio.NewScanner(tty)
    inreader.Split(bufio.ScanLines)

    started <- true
    for inreader.Scan() {
        fmt.Printf("handle: " + inreader.Text())
    }
}()

A: I found a solution. You need to spawn a process without TTY.
To do it, it is necessary to perform syscall SysProcAttr with Setsid and Setctty parameters.
cmd := exec.Command("echo")

cmd.SysProcAttr = &syscall.SysProcAttr{
    Setsid:  true,
    Setctty: false,
}

cmd.Start()

cmd.Write([]byte("hello grep\ngoodbye grep"))
cmd.Close()

cmd.Wait()