text:
Q: RecyclerView и OnClick() как кликнуть по одному элементу? Вообщем, есть проблема.
Есть RecyclerView, со вложенным макетом CardView. При клике на кнопку, по понятным причинам нажимаются сразу несколько кнопок ( я так понял по position ). Как это обойти, сделать так, чтобы при нажатии - нажималась одна кнопка? В гугле копал, но не докопал, документацию читал, но уровень у меня не особо высокий, поэтому не могу определиться. Может кто помочь? Объяснить и наглядно показать как сделать ,чтобы было правильно, рассказать как ребенку почему и как? Огромный плюс от меня.
Структура кода: ( Все к минимуму приведено, берегу ваши глаза :) )
 @Override
public CardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    int layoutIdListItem = R.layout.fragment_card;
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(layoutIdListItem, parent, false);    // Подключение к card
    CardViewHolder cardViewHolder = new CardViewHolder(view);
    init();
    return cardViewHolder;
}

private void init() {
    //retrofit                  // это просто масиив инициализации, чтобы красиво все было

}

@Override
public void onBindViewHolder(@NonNull CardViewHolder holder, int position) {

    if (partnerArrayList.size() == numberItems) {    // условие , если true , то изменяй CardView
        holder.bind(partnerArrayList.get(position));   // переход в изменение CardView
    }

}

@Override
public int getItemCount() {
    return numberItems;              // сколько элементов cardView?
}

class CardViewHolder extends RecyclerView.ViewHolder {

    private Button favorite;                // Вот допустим кнопочка, которую нужны клацать

    public CardViewHolder(@NonNull View itemView) {

        favorite = itemView.findViewById(R.id.favorite);

    void bind(final Partner partner) {

        favorite.setOnClickListener(new View.OnClickListener() {   // и вот тут я кнопочку клацаю
            @Override                                      // но кнопочка клацается на всех CardView
            public void onClick(View v) {               // Укажите пожалуйста прям тут, что делать :)
                StateApp.setFavorite(partner.getId());
                favorite.setBackgroundResource(R.drawable.favorite_star_on_click);

Спасибо за ответы друзья, буду очень благодарен вам за помощь в такую трудную минуту для мня :(

A: Первое. RecyclerView не должен хранить в себе никакой логики, единственное что он должен уметь это показывать то что вы ему передали, на этом зона ответственности его заканчивается.
Второе. У вас действительно очень странно написан адаптер, и я бы рекомендовал вам его переписать с нуля, что-то вроде такого:
class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {

    private final ItemClickListener listener;
    private final List<YourData> items = new ArrayList<>();

    public YourAdapter(ItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(parent.getContext()).inflate(viewType, null, false);
        return new ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(items.get(position), listener);
    }

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

    public void update(List<YourData> items){
        this.items.clear();
        this.items.addAll(items);
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private Button buttonOne;
        private Button buttonTwo;

        ViewHolder(View itemView) {
            super(itemView);
            buttonOne = itemView.findViewById(R.id.button_one);
            buttonTwo = itemView.findViewById(R.id.button_two);
        }

        void bind(YourData data, ItemClickListener listener){
            buttonOne.setOnClickListener(v -> listener.onClickButtonOne(data));
            buttonTwo.setOnClickListener(v -> listener.onClickButtonTwo(data));
        }
    }
}

Интерфейс OnItemClickListener. Его должна реализовать ваша View в которой находится ваш адаптер.
interface ItemClickListener {

    void onClickButtonOne(YourData data);

    void onClickButtonTwo(YourData data);
}

Любые обновления RecyclerView должны происходить с помощью метода update()


text:
Q: HTML5 resumable and chunked upload of large files (> 500MB) Is it possible to implement resumable and slice (chunked) upload for large sizefiles (>500MB) using HTML5 (BLOB API)?
I tried to use https://github.com/blueimp/jQuery-File-Upload.
In documentation its said that is supports:
Resumable uploads:
Aborted uploads can be resumed with browsers supporting the Blob API.
Chunked uploads:
Large files can be uploaded in smaller chunks with browsers supporting the Blob API.
But it seems that it tries to load file in RAM and that even hangs my system.  Did anyone come across such problem what were the solutions? Maybe HTML5 is inappropriate here?

A: Try one of these:

*

*Plupload

*fineuploader

*resumable
I think they all support chunking/slicing, and at least several of them support resuming. At least plupload and fineuploader have jQuery plugins.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Switch inside switch alternative I have this pseudocode:
switch (true) {
  case (cond_1 < 0):
    return 'c1 < 0';
  case (cond_1 === 0):
    switch (true) {
      case (cond_2 < 0):
        return 'c2 < 0'
      case (cond_2 === 0):
        return 'c2 === 0'
      default:
        return 'c2 > 0'
    }
  default:
    return 'c1 > 0';
}

Is there a better way to write this code, without using switch inside other switch statement?

A: These if/else conditions are more compact, and the flow is easier to read:
if (cond_1 < 0) return 'c1 < 0';
if (cond_1 === 0) {
  if (cond_2 < 0) return 'c2 < 0';
  if (cond_2 === 0) return 'c2 === 0';
  if (cond_2 > 0) return 'c2 > 0';
}
return 'c1 > 0';


text:
Q: How to choose a row for specific column I have a table like this:
ID   Course1   Course2
S1    A1        A2
S1    A1        B1
S2    D1        B1
S2    C1        B1

I need to select first row for each ID. I mean a table like this:
ID  Course1    Course2
S1    A1        A2
S2    D1        B1

It would be appreciated if any body help.
Thanks

A: For your example, i guess the easiest way (imo) to select the first row for each ID is do a group by and you shoul get what you want.
SELECT *
   FROM YourTable
  GROUP BY ID;
Picture of the result
Hope this help you.


text:
Q: How to get started with Visual Basic for Applications? I'm a little intimidated by the wealth of knowledge displayed on the front page of this website, but it gives me hope that I'm talking to the right people.  I had a pretty rotten experience with one of our programmers today, and I'm hoping that you might be able to offer some advice.
I'm an office admin (primarily clerical), and one of our macros in Microsoft Excel broke today (I apologize if that description makes me sound like a "dumb user").  Our manager called our IT department and they sent up 2 programmers.  The first guy was nice and asked if I'd be interested in watching him fix the problem -- but the 2nd guy spoke up and said "She's just clerical, she'll never get it."
Yeah, it hurt -- but to make a long story short, I asked my husband (who is a "perl" programmer) what I could do to show these guys what I'm made of, and he recommended something called "VBA" because I work with Microsoft Office a lot.  He wasn't quite sure if "VBA" was right, so he recommended I get involved with the community at this website (he says he finds a lot of answers to questions here).
I've researched "VBA" on google, but there are literally THOUSANDS of results. I just want to be able to record and edit macros for Microsoft Office products, and possibly get good enough to show that programmer I'm not just a "stupid female admin".  Can any of you pro's please give me your advice on the following items?

*

*Is "VBA" actually what I'm looking for to create Macros and automation?

*If not "VBA", what is a more suitable starting point?

*A good book or website with lessons?

*Anything else you think would be helpful?  Do they offer college classes for things like this?

A: If you get reasonably proficient with VBA, you won't have to call IT for these matters.  That may be against your company's policy, but I'll leave that ethical dilemma to you.  If I wanted to learn VBA, I would study these three books in order
VBA for Excel for Dummies (Walkenbach)
Power Programming for Excel VBA (Walkenbach)
Professional Excel Development (Bullen, Bovey, et al)

Concurrent with that study, you need to start solving real-world problems.  Go to social.msdn.microsoft.com and start reading the VBA forums.  Answer whatever questions you can.  The ones you can't, wait for someone else to answer it then reproduce the problem and solution so you know it.  Do the same with stackoverflow questions by following the vba tags.  If any question seems too complicated, just skip and go to the next one.
Read Excel VBA blogs http://www.dailydoseofexcel.com/dicks-blogroll/ Start with http://datapigtechnologies.com/blog/ and http://blog.contextures.com/ for sure.  They're not just VBA, but they're very well written.
Here's what will happen:  In 3-6 months you will have discovered a whole new world.  You will have written simple macros for yourself and your coworkers that eliminates some of the drudgery from your day.  You'll start looking for wasteful process you can eliminate with simple code.  In 6-12 months you will have become reasonably proficient.  You won't need IT to fix minor problems for you.  You will be the go-to Excel person in your office (learning VBA will make you better at Excel). You will have helped thousands of people here and on the msdn forums all while helping yourself.
After 2 years you'll probably start being recognized by MS and the community as an expert.  You'll get sick of answering the same questions over and over on the forums so you'll start a blog and direct people there.  You'll have arguments with your husband about whether VBA is a "real" language, but he'll be secretly proud of you for what you've accomplished. After 5 years you'll have co-authored an Excel book, quit your job to be an Excel consultant, and learned C#.  YMMV of course.

A: VBA (Visual Basic for Application) is what you are looking at, incase you are interested in macros...
In my opinion it is far more easier to understand if you have good experience in Ms-Office, though for mastering it, you might need some programming skills.
The easy way to learn is start with a problem.  Take a problem in hand and try to record the macro for automating your task...  Then you can take a look at what got recorded in the Visual Basic Editor of the Ms-Office Suite...
Try to read and understand each line of code that got generated as a response to your actions... At first everything will be greek and latin... But if you continue to do it, you will easily understand it in no time...
Then you can search for materials and all those search results will be of great meaning to you.
Have a nice time..

A: Actually I started out programming by recording macrosin Excel and reviewing the code created by the recorder.  Figure out a simple task and then record a macro.  Recording macros in Excel 2007 can be found under the view tab under the Macros button on the far right.  One of my first tasks I figured out was to filter several rows of data with autofilter then print the filtered section.  After printing I remove the filter and select cell A1.
Before recording a macro figure out each click of the mouse in order.  Everytime you click or type the macro records it. So reduce the chatter code recorded, by rehearsing the macro.  You might even write out, by hand, a play script like in broadway play would have .  Don't worry about how long it takes to record.  The recorder has no concept of time.  To best understand the VBA, record the macro several times. Throw in an extra click and see what it does.  Compare the code in each macro.  To get to the code view the macro with the same button mentioned above. select the macro and edit it.  When you feel adventerous modify the code in the editor.  ALWAYS record and play around on a copy a document not the real thing.  This way you can delete the file if it gets to messed up.  FYI - the stop button for the macro is often in the bottom left corner of the Excel window.
Happy learning,
--J Man

A: I thought I would share my experience in how I learned VBA macros within Excel (mainly) and Access.
I needed to automate a lot of tasks in Excel and I knew all about recording macros. You can record macros from the Tools|Macros menu in Excel 2003 (I'm not sure what it is in 2007/2010).
Then I decided I needed to alter them slightly, so I thought I'd have a look at the recorded code. Pressing Alt-F11 brings you into the VBA Integrated Development Environment (IDE). You can then look at the macros you have recorded and see what they do.
I would then edit them slightly and see what happened. If I needed to do somthing and I wasn't sure how, I would search the help or google and find excellent answers all over the web.
I now work as a VBA developer and I often still have things that I need to find out. Having a strong background in computers and Office applications (especially Excel) will help. Having a husband that does Perl will mean you can ask him about general programming things like syntax and variables and programming concepts that might need some extra explaining. I had been programming before on and off so these concepts weren't new to me.
Good luck and remember to ask heaps of questions on Stack Overflow and you'll be a Pro in no time.

A: Excellent question!
VBA stands for Visual Basic for Applications and is the macro / automation tools that comes with Office (the macro that you talk about in your post will be written in VBA).
VBA sounds like a perfect match:

*

*VBA is targeted at non-techies and so is designed to be forgiving and easy to pick up.

*Google contains a wealth of information on the subject, all targeted people in your situation (people without a technical background who simply want to produce an Office macro that helps them)

*Using Office every day will give you an opportunity to use and practice what you learn.

*VBA has a fantastic macro recording function which is incredibly useful (especially when you are trying to learn VBA)

Like I said, Google has a wealth of information and introductory articles on the subject (e.g. Getting Started Using VBA, to pick a good looking example).  I recommend reading through one of those to get a quick overview and then just have a go and see what you can get it to do:

*

*Use the macro recorder! If you can't work out how to do something then just record a macro of you doing it and see if you can figure out how to do it from the code it generates.

*Give yourself problems to solve.

*Ask questions here! :-)
Also, many places will offer courses on VBA which I'd definitely recommend - guides on Google will be excellent for showing you the syntax and how to do do certain actions (like how to select a certain cell, or how to do loops), however they won't be as good at teaching the problem solving aspects of programming - for this you really need to learn from a person which is where a course will be very helpful.
As a final note, I would advise against trying to understand macros that other people have written (for example the macro you mention in your question) - understanding code is far more difficult that writing it, besides if those programmers coding skills are anything like their social skills its probably not code you want to be learning from anyway...
Good luck!

A: Everyone's comments are great, I wanted to make one small point.
VBA is like a gateway drug.  ASP classic and VB6 have the nearly the same syntax.  I've ported code from one to the other with very minimal changes.
VB.NET has a similar syntax.  What this means is that by learning VBA, you may be able to not only learn VBA but then go on to leverage those skill to do much more than you ever thought was possible.  You may even learn that you have a natural affinity to programming, and pursue it as a career.
Who knows, you may wind up being the rude programmer's boss one day.  That would be sweetly ironic.

A: *

*Yes. VBA stands for Visual Basic For Applications.

*VBA is what you want, if you're interested in learning how to automate office applications.

*I recommend a book by John Walkenbach. In particular, Power Programming with VBA.

*Don't know about college classes, but you probably don't need one: I'm pretty sure Power Programming assumes zero programming experience. (But it's been a long time since I read it.)

Keep in mind, it may take some time before you grasp enough of the concepts to impress your coworkers. Good luck. And remember, there are always jerks like that. Don't let them get to ya. :)

A: Lots of useful resources mentioned in above articles. Yeah! VBA is the thing in which you can actually code logic of macros. I would just like to add an article of mine about MS Word/Excel macros. Some of the basic and tricky tutorials are mentioned there.

A: Jordan's answer is a fine one, but your problem runs deeper than whether or not you know VBA.  Basically, you have rude coworkers and, if you hope to impress them, becoming a neophyte in an area in which they are highly skilled is unlikely to help.
The better way (IMO) to deal with this sort of thing is to tell the rude one "leave my office [/cubicle/whatever], now.  No discussion", then have a word with his boss about how he interacts with his coworkers.
If his boss won't give you a satisfactory answer, take it up with HIS boss.  Etc., until you get to the CEO, if that's what it takes.
If nobody up your chain of command thinks that the behaviour you describe from #2 programmer is a problem, the you have to consider whether or not the company you work for is worthy of your particular skill set.
And if you don't think you bring any particularly valuable skills to the company, then you probably shouldn't worry too much about whether or not the others respect you, although (a) you still shouldn't have to take the sort of abuse you describe and (b) your idea to extend your skills is admirable.
...But, if you're not a "natural born programmer", don't try to force your round peg into a square hole.
If it were me, I'd focus on being the kick-ass-est office admin anyone had ever seen.  Oh, another tack: if #2's boss doesn't give you a satisfactory response, ask YOUR boss to take it up with him.  Explain that you don't think that people should be subjected to that sort of behaviour in civilized society.  Again, if he's not open to your complaint, you have to decide if you're going to work for that kind of company.
Good luck!
Leave us comments letting us know how it comes out.

A: VBA stands for Visual Basic for Applications. I recommend reading the Wikipedia article on it, then checking out some video tutorials like this one. I also like the "For Dummies" series when you want to learn about something you've never touched before. When you have specific questions, you can post them on this site.

A: In answer to your questions...

*

*VBA Is the language which is used to drive office automation. As Jordan said, it stands for Visual Basic (for) Applications

*VBA is a suitable starting point if you just want to impress the office Dev. If you actually want to learn how to program (as your husband does) then start out learning another language called C++ but be warned... its hectic stuff. I suggest you google the phrase 'STarting out with VBA' or 'VBA for beginners' and the like. You will find some helpful tutorials

*Instead of trying to find a book and learn it all, set yourself a task, such as 'Create a macro that will find all cells in a spreadsheet that have my name in them and replace them with 'I WIN'. You will rapidly come up with more specific questions as you try that

*Classes are offered, most classes in Excel and other office courses will offer an advanced section for macro programming

*Ask specific questions. Instead of asking 'how do i write this program' ask 'how do i find a particular cell in a spreadsheet'. You get much better responses that way

A: Note that there are many styles of VBA, as code from Excel/VBA is going to look different from code in Access/VBA. The reason is the usage is different (cells vs databases). Look at vb-helper for books, links and code.

A: Many useful resources here for VBA, one of the most useful points though is that when you turn on the Macro Recorder in Excel the Macros created are VBA code. Excel is huge, trying to learn all the nuances of VBA will take a fair time, OTOH recording a macro takes seconds and you'll get a quick idea of how the language works.

A: you better get hold copy of MS Office and start using MS Excel. Ms Excel as well as MS Word allows you manage spreadsheets and documents using VBA.
Open MS Excel and do your desired task while recording a Macro. Macros are great place to start learning VBA.  In the background all these Macros are stored in VBA format. You can record as many as Macros on your various day to day tasks. Thus you will be more efficient in getting the task done thru MS Excel as well as you will get to learn more about macros and VBA. You will soon learn to tinker this macros for better results.


text:
Q: UISelector.text() different behavior between OS versions I have found some weird behavior regarding UiAutomator's UISelector.text() method.
Let's take this sample code:
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
device.wait(Until.hasObject(By.pkg(resolveInfo.activityInfo.packageName).depth(0)), 1000)

device.findObject(UiSelector().text("Some text"))

And suppose I have a Button in my first activity that looks like this:
<Button
        android:id="@+id/my_button"
        android:layout_width="match_parent"
        android:layout_height="@dimen/my_button_height"
        android:text="Some text"
        android:textAllCaps
        />

When trying to target buttons with properties like textAllCaps the behavior of this method changes depending on the Android version of the device.
For android versions Nougat (api level 24) or higher, this method expects the string passed as parameter to be in caps, as it is rendered (e.g. "SOME TEXT"), while for lower versions it expects the string to be the text assigned to that button's android:text attribute.
Has anyone come up with this? How do you write UITests that run for every android version (let's say minSDKVersion = 19)?
(I know I can use UISelector.description() and UISelector.resourceId() but I would like to be able to use UISelector.text() when desired)


text:
Q: MYSQL 5.6 Cluster / chain points by distance to any other point without millions of calculations? I have a table of approx 10,000 - 20,000 dynamic points across the globe stored as lon/lat points. I want to cluster any point within (roughly) 3km of any other point into one point (and return the averaged center point of each cluster if possible). Unlike some other solutions I have seen, I do not just want points within 3km of the central cluster point, it is fine to have a point within each cluster many kilometres away from the central cluster point as long as there is a chain of points within 3km of each other joining the points together into a single chain/cluster.
The only way I can think of doing this is looping over every point, finding any other points within 3km of that point, and then recursively each of those points etc until i find all in that perticular chain/cluster, and then repeat for all the remaining un-clustered points - this would result in millions of calculations. Is there an easier way of doing this? Preferably with MYSQL 5.6 geospatial abilities, but im open to any viable solution.

A: This spatial sql example will do exactly as you ask.  Ignore the fact that the question asks for linear groups, it works fine with non-linear groups as well.
Group by cluster example


text:
Q: log-in/password issues I'm runnung LM 18.3X "live". Never needed to "log-in", however, after running some upgrades, a different version splash screen showed up and now it's prompting for a log-in/password...which I don't have. How can I get passed this obstruction?
Rick


text:
Q: How to put shell command line output to a variable on Ubuntu with Python 2.7 I use the id user command and I get user's info for example, I get output of uid=1000(user), gid=1000(user), groups=1000(user), 4(adm), 24(cdrom), 27(sudo), 30(dip), 46(pugdev), 113(lpadmin), 128(sambashare) What I wanna do is, somehow put each of the numbers into a different variable (or array) and then use them as variables, which later I would translate those numbers in program to words, so you could understand user's info, for example take the group's number and translate it to group number, take user id and translate it if it's admin or standard user etc.

A: You don't need to use the shell to spawn id user and so on, because Python has a module for this: grp.  See here: https://docs.python.org/2/library/grp.html
And for user info, pwd: https://docs.python.org/2/library/pwd.html

A: It will be easier to parse the output of 'id' command from within python. you can pass the value from the shell into the python script using a command substitution like shown below,
PARAMETER="$(id user)"
python script.py $PARAMETER

then from the script, you can clean out the values doing something like(you may need to change this according to your exact requirement),
import sys

lst=list()
args=sys.argv[1:]
print args
for i in args:
    if '=' in i:
        lst.append(i[i.find('=')+1:i.find('(')])
    else:
        lst.append(i[:i.find('(')])

print lst


text:
Q: Using dict keys in python as values in a different dict I would like to create a "translator" type of dict that would assign values that are keys in different dicts, which are nested, to keys in a dict that I created.  The problem I run into is that I can't create a value that represents a nested dict key without having to convert that to a string or some other data type, and when I try to use a string as an index to the nested dict, I get an index error.  Ideally, my dict would look something like this:
new_dict{
    "new_key_1" : ['subdict1']['subdict2']['old_key_1'],
    "new_key_2" : ['subdict1']['subdict2']['old_key_2'],
    "new_key_3" : ['subdict1']['subdict3']['old_key_3']
    }

Then, for each nested dict, I could generate a new dict object with a simple for loop:
for key, value in new_dict.items() :
    user_dict_1[key] = OldDict[value]

The nested dicts are very large and I only need a few fields from each, otherwise I could just use the .copy() function to work with the old dicts.
PS- Any help in rewriting this question to be more readable also appreciated.

A: You're going to need reduce() for this one...
attrmap = {
  "new_key_1": ('subdict1', 'subdict2', 'old_key_1'),
   ...
}

print reduce(lambda x, y: x[y], attrmap[somekey], old_object)

A: Are you talking something like this?
from pprint import pprint as pp
subdict1 = {'subdict1_item1':1, 'subdict1_item2':2}
subdict2 = {'subdict2_item1':3, 'subdict2_item2':4}
subdict3 = {'subdict3_item1': 5, 'subdict3_item1':6}
olddict = {
    'old_key_1': [subdict1, subdict2],
    'old_key_2': [subdict1, subdict2],
    'old_key_3': [subdict1, subdict3],
    }

newdict = {
    'new_key_1': olddict['old_key_1'].append('old_key_1'),
    'new_key_2': olddict['old_key_2'].append('old_key_2'),
    'new_key_3': olddict['old_key_3'].append('old_key_3'),
    }

or this
newdict = {
    'new_key_1': 'old_key_1',
    'new_key_2': 'old_key_2',
    'new_key_3': 'old_key_3',
    }
def getnew(newkey, newdict, olddict):
    if newkey in newdict:
        oldkey = newdict[newkey]
        if oldkey in olddict:
            preitem = olddict[ oldkey ] # returns a list with two items
            item = []
            item.append([preitem[0]]) # makes subdict1 wrapped in a list
            item.append([preitem[1]]) # makes subdict2/3 wrapped in a list
            item.append([oldkey])
            return item
        else:
            raise KeyError('newdict has no matching olddict key')

results to:
pp( getnew('new_key_1', newdict, olddict) )
print
pp( getnew('new_key_2', newdict, olddict) )
print
pp( getnew('new_key_3', newdict, olddict) )
[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict2_item1': 3, 'subdict2_item2': 4}],
 ['old_key_1']]

[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict2_item1': 3, 'subdict2_item2': 4}],
 ['old_key_2']]

[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict3_item1': 6}],
 ['old_key_3']]


text:
Q: What is the maximum error of this ADC? I've read every article on the first two pages of Google trying to understand DNL and INL. Not a single lesson gave a specific example I could relate to, so now I'm still wildly confused and have no idea how to calculate this value.
I'm thinking about using the MCP3221 ADC. Here are the specs:

My reference voltage will be 5 V, so each step will be 5/4093 = 1.22 mV. It states that there will be no codes missing.
What will the mV tolerance on my readings be? I'm not so interested in how it works, just how to apply it practically. Would you please share any formulas used?
What I saw +/- 1LSB DNL, which I think means +/- 1.22mV variance.

A: Should be the sum of offset + gain + integral nonlinearity, or +/-7 LSB which is +/-8.5mV.
Plus any error in your 5V reference. A 1% error in your 5V reference would result in an additional +/-50mV error at or near full scale.

A: From this reference, and this (Note that this one assume "adding" % errors ... in § Final Thoughts (worst case),

TOTAL UNADJUSTED ERROR
TUE is defined as the maximum deviation between the actual and the ideal transfer curves. It is a parameter that specifies the total errors that can occur causing maximum deviation between the ideal digital output and actual digital output. It is the maximum deviation recorded between the ideal expected value and the actual value obtained from the ADC for any input voltage.
TUE is represented as ET.
TUE is not the sum of:
EO (Error Offset), EG (Gain Error), EL (ILE or INL), ED (Differential Error).
The offset error affects the digital result at lower voltages whereas the gain error affects the digital output for higher voltages.

See also the paragraph: Using error parameters

Using error parameters

*

*The TUE is NOT the sum of all the errors EO, EG, EL, ED.
It is the maximum error which can
occur between ideal and expected digital values. It can be the effect of either a single error
or two errors occuring simultaneously.

*As ILE is the integral of DLE, it can be considered as indicative of maximum error. Do not add both DLE and ILE together to calculate the maximum error which can occur at any digital step.

*Integral Linearity Error is the maximum deviation between any actual transition and the end point correlation line. So it represents the linearity of the ADC.

*ILE and DLE are dependent on the ADC design. It is difficult to calibrate them.

*The ILE and DLE can be minimized by doing multiple conversions and then averaging.

*Offset and Gain errors can be easily cancelled / compensated using software techniques.

*The maximum values for errors specified in datasheet are the worst error values measured in the laboratory test environment for full voltage range.

*As already mentioned, all the ADCs provide the digital converted output in ratio with the reference voltage. To convert analog voltage accurately, the ADC needs to have an accurate
VAREF otherwise the digital output received may not be the correct value.


text:
Q: Summernote - Custom dropdown for ordered and unordered list I am using Summernote editor v0.8.9 for quite a long time. I have created a custom dropdown button for Ordered List and Unordered List by using below code
let orderedList = function (context)
        {
            let ui = $.summernote.ui;

            // create button
            let button = ui.buttonGroup([
                ui.button({
                className: 'dropdown-toggle',
                contents: '',
                container: false,
                tooltip: 'Ordered List',
                data: {
                    toggle: 'dropdown'
                }
                }),
                ui.dropdown({
                    className: 'dropdown-style',
                    contents: "

1

1)

I

A

a)

a

i

",
                    callback: function ($dropdown) {
                        $dropdown.find('li').each(function () {
                            $(this).click(function() {
                                selectedListType = orderedListMap[$(this).attr('data-value')];
                                $(context).summernote('editor.insertOrderedList');
                            });
                        });
                    }
                })
            ]);

            return button.render();   // return button as jquery object
        };

And also I get the dropdown attached to the toolbar as shown in the image

I have changed some code in the summernote.js to change the list style type after clicking on the dropdown item.
I am adding following code in the Bullet.prototype.wrapList method as follows
//for bullets and numbering style
if (selectedListType != 'NA') {
     listNode.setAttribute('style', 'list-style-type:' + selectedListType);
 }

I have also added the following code in the method "function replace(node, nodeName)" of "dom" object.
//for bullets and numbering style
if ((nodeName == 'OL' || nodeName == 'UL' ) && selectedListType != 'NA') {
    $(newNode).css('list-style-type', selectedListType);
}

When I click on the dropdown item I am calling below code.
$(context).summernote('editor.insertOrderedList');

At first instance everything is working fine. I can change ordered list to unordered list as well as to other types of lists. But the problem arises when I am trying to create a new list. When I try to create a new list below the existing list (note : after double entering new line, existing list closes, hence a new list is created after double entering new line),

the focus does not stay on the current line. Instead it goes to the old list and old list style (Ordered/unordered) is getting changed.

I have also kept the default UL/OL in the toolbar for deugging and I can see that the document.selection() in the method WrappedRange.prototype.nativeRange is giving proper selection for default UL/OL but is giving wrong selection for my dropdown UL/OL.
Please help.
Let me know if any info is needed from my side

A: I solved this problem.
The problem was with the custom dropdown I created.
The dropdown needs to be in the following structure in the 'contents' attribute inside 'ui.dropdown'

'a' tag inside 'li' tag


text:
Q: Android error: Application is not installed on your phone I am getting this error when trying to install my exported unsigned application on tablet pc (running Android 4.04. version). App is normally installing and running in Android emulator in Eclipse. I tried removing and reinstalling it, but that didn't help either. Atached is my AndroidManifest.xml since problem is often there (but I can't see any duplicate code).
<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="hr.punctum.LociranjePonudaProizvoda"
        android:versionCode="1"
        android:versionName="1.0">

        <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="16" />

        <application
            android:label="@string/app_name"
            android:icon="@drawable/ic_launcher"
            android:theme="@style/AppTheme">
            <activity
                android:label="@string/app_name"
                android:name=".ListaProizvoda" >
                <intent-filter >
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <activity android:name="DetaljiProizvoda"></activity>
            <activity android:name="GMapsActivity"></activity>

        <uses-library android:name="com.google.android.maps" />

        </application>

        <uses-permission android:name="android.permission.INTERNET"/>

    </manifest>

A: The only thing suspicious I see is the uses-library tag, do you have the Google Maps lib in your tablet? (if yes then you should have the following files in it)
/system/etc/permissions/com.google.android.maps.xml
/system/framework/com.google.android.maps.jar

Without the lib the apk installation will fail with INSTALL_FAILED_MISSING_SHARED_LIBRARY error.


text:
Q: Swift: Can't synchronize data to table view using Firebase I was working on a grocery list app. When I tried to synchronise data to table view using Firebase, the grocery item can not be shown on the table view. However, when I reset the simulator, items added before can be shown on the table view, but when I add another item, it can't be shown on the table view. I double checked the code and found nothing wrong. Could you help me fix it?(e.g. In the following two images, the coffee item can not be shown)
Part of code in GroceryListViewController.swift
 override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//Attach a listener to receive updates.
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in

    var newItems = [GroceryItem]()

    for item in snapshot.children
    {
        let groceryItem = GroceryItem(snapshot: item as! FDataSnapshot)
        newItems.append(groceryItem)
    }
    self.items = newItems
    self.tableView.reloadData()
    })
}

A: 1 - You are using observeSingleEventOfType (* This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned.) From the doc. So your listener is called once and stop listening. Use observeEventType instead
2 - You should do the reloadData of your tableview on the main thread like this :
 NSOperationQueue.mainQueue().addOperationWithBlock({
      self.tableView.reloadData()
 })

The reason is that you cannot / must not interact with UI from a background thread. Since Firebase is asynchronous the completion block is on a background thread

A: Maybe it's obvious, but it happen to me. I was debugging and the code was stopped in a breakpoint, and data was not in the console in firebase. Then I realized that I had to let it run completely to refresh. Maybe it can help...

A: Add this code once touch the button "+":
 self.items.append(groceryItem)
  let row = self.items.count - 1
  let indexPath = NSIndexPath(forRow: row, inSection: 0)
  self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

This ensures the interaction with  UI.


text:
Q: Hibernate error with #new I get this error with Hibernate 5.1 with JPA 2.1 on WildFly 12:

Caused by: org.hibernate.PropertyNotFoundException: Could not locate setter method for property [rs.co.bora5.programs.sevid.model.Klijent#new]

And i have implemented all getters setters, no-args constructor...

A: In the end, it was problem with mapped superclass...
I added method
public Boolean isNew() {
return id == null;
}

that was supposed to tell me if object was persisted and somehow Hibernate asked for setter for field new because of that. After i deleted method isNew() everything was ok.


text:
Q: jQuery Regular Expression does not work properly I am trying to increase security on Email/Password input fields using regular expressions but I am having bad time because I cannot find what I am doing wrong. So basically I'm creating 2 variables where I'm storing my Regex pattern and after that I want to use jquery to catch the submit button and when .on('click') if there is added correct information by users to redirect them to next page for example. I have been testing my regular expression and they are matching my requirements -  they are returning true for Email/Password after testing with .test().
Here is my code example of what I am trying to build:
  var userValidation = /^[\w-]+@[\w-]+\.[A-Za-z_-]{2,4}$/;
  var passValidation = /((?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,15})/gm;
  console.log(userValidation.test('test@gmail.com')); // testing
  console.log(passValidation.test('12345678Kksad')); // testing

Actual code which I am trying to run
$('.button').on('click', function(){
    if ($('#user') === userValidation && $('#pass') === passValidation){
        window.location.replace("http://stackoverflow.com");
    }else{
        console.log('not working properly');
    }
})

Every time when I enter email and password in both input fields it returning the else statement does not matter if the information is correct or not according my regular expressions.

A: There is several issue in your code.
Here is a complete example.
CSS :
<form id="form" action="/validate" method="POST">
    <input type="text" name="email"/>
    <input type="password" name="password">
    <button type="submit" >Submit</button>
</form>

JS :
var emailRegex = /^[\w-]+@[\w-]+\.[A-Za-z_-]{2,4}$/;
var passRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,}$/;

$('#form').submit(function(event) {
    event.prevendDefault();
    // get email and password value
    var email = $(this).find('input[name=email]').val();
    var password = $(this).find('input[name=password]').val();
    // validate email and password
    if (emailRegex.test(email) && passRegex.test(password)){
        window.location.replace("http://stackoverflow.com");
    } else {
        console.log('not working properly');
    }
});

A: Alternatively, you could make a minor change to your existing event handler function to match the input field values with your regular expressions;
$('.button').on("click", function () {
  if ($('#user').val().match(userValidation) && $('#pass').val().match(passValidation)) {
      window.location.replace("http://stackoverflow.com");
  } else {
      console.log('not working properly');
  }
});


text:
Q: How do I compile a static binary of Subsurface on MacOSX? I am trying to make a static binary on Subsurface on MacOSX, so that we can provide a simple binary download.  I'm clueless as to solve the problems I get, but that might just be because I suck at C.
Here's what I do.  I have already installed gconf and gtk2 from MacPorts, and I'm building without libusb for simplicity:
git clone git://libdivecomputer.git.sourceforge.net/gitroot/libdivecomputer/libdivecomputer
cd libdivecomputer
autoreconf --install
./configure
make LDFLAGS="-static"
sudo make install
cd ..
git clone git://subsurface.hohndel.org/subsurface.git
cd subsurface
make LDFLAGS="-framework CoreFoundation -static"

The result is this:
gcc -framework CoreFoundation -static -o subsurface main.o dive.o profile.o info.o equipment.o divelist.o parse-xml.o save-xml.o libdivecomputer.o print.o uemis.o gtk-gui.o statistics.o macos.o  -L/opt/local/lib -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lxslt -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lpangocairo-1.0 -lXext -lXrender -lXinerama -lXi -lXrandr -lXcursor -lXcomposite -lXdamage -lgdk_pixbuf-2.0 -lpangoft2-1.0 -lgio-2.0 -lXfixes -lcairo -lX11 -lpng14 -lpango-1.0 -lm -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lglib-2.0 -lintl    /usr/local/lib/libdivecomputer.a  -lpthread
/usr/bin/ld_classic: can't locate file for: -lcrt0.o
collect2: ld returned 1 exit status
make: *** [subsurface] Error 1

Now, if I symlink /usr/lib/crt0.o to /usr/lib/crt1.o, I get this instead:
gcc -framework CoreFoundation -static -o subsurface main.o dive.o profile.o info.o equipment.o divelist.o parse-xml.o save-xml.o libdivecomputer.o print.o uemis.o gtk-gui.o statistics.o macos.o  -L/opt/local/lib -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lxslt -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lpangocairo-1.0 -lXext -lXrender -lXinerama -lXi -lXrandr -lXcursor -lXcomposite -lXdamage -lgdk_pixbuf-2.0 -lpangoft2-1.0 -lgio-2.0 -lXfixes -lcairo -lX11 -lpng14 -lpango-1.0 -lm -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lglib-2.0 -lintl    /usr/local/lib/libdivecomputer.a  -lpthread
ld: warning: ignoring file /usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/libgcc_static.a, file was built for archive which is not the architecture being linked (x86_64)
ld: warning: unexpected dylib (/System/Library/Frameworks//CoreFoundation.framework/CoreFoundation) on link line
ld: warning: unexpected dylib (/opt/local/lib/libxml2.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libz.dylib) on link line
ld: warning: unexpected dylib (/usr/lib/libpthread.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libiconv.dylib) on link line
ld: warning: unexpected dylib (/usr/lib/libm.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libxslt.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgtk-x11-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgdk-x11-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libatk-1.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libpangocairo-1.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXext.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXrender.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXinerama.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXi.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXrandr.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXcursor.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXcomposite.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXdamage.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgdk_pixbuf-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libpangoft2-1.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgio-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libXfixes.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libcairo.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libX11.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libpng14.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libpango-1.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libfreetype.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libfontconfig.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgobject-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgmodule-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libgthread-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libglib-2.0.dylib) on link line
ld: warning: unexpected dylib (/opt/local/lib/libintl.dylib) on link line
Assertion failed: (_pointerLocations.size() == 0), function size, file /SourceCache/ld64/ld64-123.2.1/src/ld/LinkEditClassic.hpp, line 961.
0  0x10226171c  __assert_rtn + 76
1  0x1023233f5  ld::tool::ExternalRelocationsAtom<x86_64>::size() const + 149
2  0x1022d8a17  ld::tool::OutputFile::updateLINKEDITAddresses(ld::Internal&) + 583
3  0x1022d1aae  ld::tool::OutputFile::write(ld::Internal&) + 142
4  0x102261caa  main + 1178
5  0x1022502b4  start + 52
collect2: ld returned 1 exit status
make: *** [subsurface] Error 1

And if I build libdivecomputer and subsurface with "-arch i686" instead, I get this:
gcc -framework CoreFoundation -arch i686 -static -o subsurface main.o dive.o profile.o info.o equipment.o divelist.o parse-xml.o save-xml.o libdivecomputer.o print.o uemis.o gtk-gui.o statistics.o macos.o  -L/opt/local/lib -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lxslt -lxml2 -lz -lpthread -liconv -lm -L/opt/local/lib -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lpangocairo-1.0 -lXext -lXrender -lXinerama -lXi -lXrandr -lXcursor -lXcomposite -lXdamage -lgdk_pixbuf-2.0 -lpangoft2-1.0 -lgio-2.0 -lXfixes -lcairo -lX11 -lpng14 -lpango-1.0 -lm -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lglib-2.0 -lintl    /usr/local/lib/libdivecomputer.a  -lpthread
/usr/bin/ld_classic: /usr/lib/crt0.o incompatible, file contains unsupported type of section 2 (__IMPORT,__pointers) in load command 0 (must specify "-dynamic" to be used)
/usr/bin/ld_classic: incompatible flag -framework used (must specify "-dynamic" to be used)
collect2: ld returned 1 exit status
make: *** [subsurface] Error 1

I'm on MacOSX Lion with XCode 4.2.1.

A: The solution was not to build this thing statically, but to include the libraries in the .app bundle.  Both the binary and the library needed to be updated with install_name_tool to use relative paths:
$ otool -L subsurface
subsurface:
    /opt/local/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.8.0)
    /opt/local/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.7)
    ...
$ install_name_tool -change /opt/local/lib/libxml2.2.dylib \
  @executable_path/../Resources/lib/libxml2.2.dylib subsurface
$ otool -L subsurface
subsurface:
    @executable_path/../lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.8.0)
    /opt/local/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.7)
    ...

gtk-mac-bundler can be used to automate this process.  More details in the Subsurface macosx packaging directory.

A: Unless the gtk libraries have .la (libtool) meta-files, and .a (static) builds, I don't know if this can be done easily - or at least automatically. At a minimum, add: --disable-shared to ./configure
Could try: env LDFLAGS="-static-libtool-libs" ./configure --disable-shared, instead of setting it in the make invocation.
There's no point trying to link CoreFoundation, libgcc, etc., as static libraries, even if they exist, since they'll always be present.


text:
Q: Bash - extract an indented code block into new file I have a bunch of LilyPond files in the following format:
\score {
  \new StaffGroup = "" \with {
    instrumentName = \markup { \bold \huge \larger "1." }
  }
  <<
    \new Staff = "celloI" \with { midiInstrument = #"cello" }

    \relative c {
      \clef bass
      \key c \major
      \time 3/4

      \tuplet 3/2 4 {
        c8(\downbow\f b c e g e)
      } c'4                                         | %01
      \tuplet 3/2 4 {c,8( b c e f a) } c4           | %02
      \tuplet 3/2 4 { g,8( d' f g f d) } b'4        | %03
    }
  >>
  \layout {}
  \midi {}
}

How would one extract the \relative c {...} block into a new file, so it would look like this:
\relative c {
  \clef bass
  \key c \major
  \time 3/4

  \tuplet 3/2 4 {
    c8(\downbow\f b c e g e)
  } c'4                                         | %01
  \tuplet 3/2 4 {c,8( b c e f a) } c4           | %02
  \tuplet 3/2 4 { g,8( d' f g f d) } b'4        | %03
}

A fix of the indentation is not necessarily needed in this case. Would that be an awk or csplit task? What would it look like?

A: You might want to think about what to do with the output, like use the input name with an extension for the output. Modifying indentation should not be hard.
This script lists any number of files named on the command line, and any number of such blocks in one file.
This is the output from your sample:
Paul--) ./LilyPond Lily.txt
    \relative c {
      \clef bass
      \key c \major
      \time 3/4

      \tuplet 3/2 4 {
        c8(\downbow\f b c e g e)
      } c'4                                         | %01
      \tuplet 3/2 4 {c,8( b c e f a) } c4           | %02
      \tuplet 3/2 4 { g,8( d' f g f d) } b'4        | %03
    }

This is the script.
Paul--) cat LilyPond
#! /bin/bash

function Relative {

    local AWK='''
BEGIN { reRel = "[\\\\]relative[ ]+c"; }
function cntBrace (tx, Local, n) {
    n += gsub ("{", "{", tx);
    n -= gsub ("}", "}", tx);
    return (n);
}
$0 ~ reRel || nBrace > 0 { print; nBrace += cntBrace( $0); }
'''
    awk -f <( echo "${AWK}" ) "${@}"
}

#### Script Body Starts Here.

    Relative "${@:--}"


text:
Q: How to convert grouped bar chart from vertical to horizontal How can this vertical grouped bar chart be changed to a horizontal bar chart (grouped, and stacked)? I need help to alter the code such that the bars are displayed horizontally instead of vertically.
import matplotlib.pyplot as plt
import numpy as np

N = 9
labels = ['L', 'S', 'S', 'M', 'W', 'W', 'S', 'R', 'C']
M_means = [1, 45, 28, 11, 4, 7, 1, 0.02, 0.3]
PO_means = [3, 58, 17, 8, 3, 8, 1, 0.06, 1]
K_means = [1, 44, 30, 11, 3, 7, 1, 0.01, 0.5]

x = np.arange(len(labels))  # the label locations
width = 0.30  # the width of the bars

fig, ax = plt.subplots(figsize=(15, 9))
rects1 = ax.bar(x - width, M_means, width, label='M S and K', color=('#b02a2a'))
rects2 = ax.bar(x, PO_means, width, label='P O S and K', color=('#055cad'))
rects3 = ax.bar(x + width, K_means, width, label='M K', color=('#0b7d53'))

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('% of workday', fontsize=32)
#ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels, fontsize=32, rotation=15)
ax.legend(loc='upper right', frameon=False, fontsize=32, markerscale=2)

ax.bar_label(rects1, size = 32, padding=20, rotation=90)
ax.bar_label(rects2, size = 32,  padding=20, rotation=90)
ax.bar_label(rects3, size = 32,  padding=20, rotation=90)
plt.xticks(ha='center')
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(32)
for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontsize(32)
plt.ylim(0, 100)
plt.gca().spines['right'].set_color('none')
plt.gca().spines['top'].set_color('none')
#fig.tight_layout()
plt.show()

A: Functionally, only two changes are needed:

*

*Change ax.bar to ax.barh

*Swap set_x* methods with set_y* methods, e.g. set_xticks() -> set_yticks() and so on

Semantically, the variables x and width should also be renamed to y and height.
import matplotlib.pyplot as plt
import numpy as np

N = 9
labels = list('LSSMWWSRC')
M_means = [1, 45, 28, 11, 4, 7, 1, 0.02, 0.3]
K_means = [2, 40, 21, 18, 3, 3, 2, 0.52, 0.3]
PO_means = [3, 58, 17, 8, 3, 8, 1, 0.06, 1]
K = [1, 44, 30, 11, 3, 7, 1, 0.01, 0.5]

# rename x/width to y/height
y = np.arange(len(labels))
height = 0.30

fig, ax = plt.subplots()

# use ax.barh instead of ax.bar
rects1 = ax.barh(y - height, M_means, height, label='M S and K', color='#b02a2a')
rects2 = ax.barh(y, PO_means, height, label='P O S and K', color='#055cad')
rects3 = ax.barh(y + height, K_means, height, label='M K', color='#0b7d53')

# swap set_x* methods with set_y* methods
ax.set_xlabel('% of workday')
ax.set_yticks(y)
ax.set_yticklabels(labels)
ax.legend(loc='upper right', frameon=False, markerscale=2)

ax.bar_label(rects1, padding=10)
ax.bar_label(rects2, padding=10)
ax.bar_label(rects3, padding=10)

# ...

A: *

*The easiest solution is to load the data into a pandas.DataFrame, and then use pandas.DataFrame.plot with kind='barh'. This is easier because pandas uses matplotlib as the default plotting backend, and the API groups the bars automatically.

*

*This reduces the code to 14 lines (not including imports).

*When using 'barh', xlabel= applies to the y-axis. Therefore, xlabel='' removes the y-axis label.

*Adjust figsize=(12, 10) if planning to use smaller / larger font sizes.

*See Adding value labels on a matplotlib bar chart for additional details about using .bar_label.

*Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1
import pandas as pd
import matplotlib.pylot as plt

# data
labels = ['L', 'S', 'S', 'M', 'W', 'W', 'S', 'R', 'C']
M_means = [1, 45, 28, 11, 4, 7, 1, 0.02, 0.3]
PO_means = [3, 58, 17, 8, 3, 8, 1, 0.06, 1]
K_means = [1, 44, 30, 11, 3, 7, 1, 0.01, 0.5]

# create a dict with the keys as the desired legend labels
data = {'labels': labels, 'M S and K': M_means, 'P O S and K': PO_means, 'M K': K_means}
# create dataframe
df = pd.DataFrame(data)

# plot: specify y=[...] if only certain columns are desired
ax = df.plot(kind='barh', x='labels', width=.85, figsize=(12, 10), xlabel='', color=['#b02a2a', '#055cad', '#0b7d53'])
ax.set_xlabel('% of workday', fontsize=15)
ax.set_xlim(0, 100)

ax.legend(loc='upper right', frameon=False, fontsize=15, markerscale=2)

for c in ax.containers:
    ax.bar_label(c, label_type='edge', padding=1, size=15)

ax.tick_params(axis='both', which='both', labelsize=15)

ax.spines[['top', 'right']].set_visible(False)

Stacked

*

*To manually create the stacked bar without pandas, see Horizontal stacked bar chart in Matplotlib

*Use the parameter stacked=True

*Some bar patches are to small for the label, so custom labels have been passed to the labels= parameter in .bar_label

*

*Using := requires at least python 3.8. Otherwise use labels = [f'{v.get_width():.0f}' if v.get_width() > 1 else '' for v in c]
ax = df.plot(kind='barh', x='labels', width=.85, figsize=(12, 10), xlabel='',
             color=['#b02a2a', '#055cad', '#0b7d53'], stacked=True)
ax.set_xlabel('% of workday', fontsize=15)
ax.set_xlim(0, 100)

ax.legend(loc='upper right', frameon=False, fontsize=15, markerscale=2)

for c in ax.containers:
    # custom labels only show label size for values greater than 1
    labels = [f'{w:.0f}' if (w := v.get_width()) > 1 else '' for v in c]
    ax.bar_label(c, labels=labels, label_type='center', padding=1, size=15)

ax.tick_params(axis='both', which='both', labelsize=15)

ax.spines[['top', 'right']].set_visible(False)


text:
Q: How to not display ASP MVC ValidationSummary in case when errors already displayed field by field? I would not like to display the ValidationSummary in case it only displays already displayed field related errors. However I do need ValidationSummary when custom server side validation error occurs like:
if (!UserManager.IsEmailConfirmed(user.Id))
{
    AuthenticationManager.SignOut();
    ModelState.AddModelError("", "You need to confirm your email.");
    return View(model);
}

A: Use @Html.ValidationSummary(excludePropertyErrors: true).
This overload, when excludePropertyErrors is true, hides property errors like your "The Email field is not a valid e-mail address." and "The Password field is required." from the validation summary. See also @Html.ValidationSummary(true) - What's the true do?.
It doesn't detect whether you print those though @Html.ValidationMessageFor(), so if you forget any of those, you can get failing form submissions that don't tell you why they fail.
To manually add non-property validation errors, call ModelState.AddModelError("", "Custom error") (note the empty string) as explained in Add error message to @Html.ValidationSummary and ASP.NET MVC Html.ValidationSummary(true) does not display model errors.

A: like @CodeCaster say Simple add

@Html.ValidationSummary(true).

If the bool parameter is true then only model-level errors are displayed. If the parameter is false then all errors are shown. reference


text: Q: How can I import facebook contacts to my Macbook? This has been a classic question but the answers have been outdated. I'm currently using Mojave. Adding facebook account to internet account group doesn't seem possible now. Does any one know how I can import my facebook contacts? I know iphone has an app called Sync but it requires paid membership.


text:
Q: Using array_intersect on a multi-dimensional array I have two arrays that both look like this:
Array
(
    [0] => Array
        (
            [name] => STRING
            [value] => STRING
        )

    [1] => Array
        (
            [name] => STRING
            [value] => STRING
        )

    [2] => Array
        (
            [name] => STRING
            [value] => STRING
        )
)

and I would like to be able to replicate array_intersect by comparing the ID of the sub arrays within the two master arrays.  So far, I haven't been successful in my attempts.  :(

A: Use array_uintersect() to use a custom comparison function, like this:
$arr1 = array(
           array('name' => 'asdfjkl;', 'value' => 'foo'),
           array('name' => 'qwerty', 'value' => 'bar'),
           array('name' => 'uiop', 'value' => 'baz'),
        );

$arr2 = array(
           array('name' => 'zxcv', 'value' => 'stuff'),
           array('name' => 'asdfjkl;', 'value' => 'foo'),
           array('name' => '12345', 'value' => 'junk'),
           array('name' => 'uiop', 'value' => 'baz'),
        );

$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);

function compareDeepValue($val1, $val2)
{
   return strcmp($val1['value'], $val2['value']);
}

which yields, as you would hope:
Array
(
    [0] => Array
        (
            [name] => asdfjkl;
            [value] => foo
        )

    [2] => Array
        (
            [name] => uiop
            [value] => baz
        )

)

A: function compareDeepValue($val1, $val2)
{
   return strcmp($val1['value'], $val2['value']);
}

Be sure that val2 key is existing in val1 array, because the function is ordering array first. Very strange.

A: you can use embedded function with array_uintersect php function. ex:
$intersectNames = array_uintersect($arr1, $arr2, function ($val1, $val2){
    return strcmp($val1['name'], $val2['name']);
    });

$intersectValues = array_uintersect($arr1, $arr2, function ($val1, $val2){
    return strcmp($val1['value'], $val2['value']);
    });

print_r('namesIntersected' => $intersectNames, 'valuesIntersected' => $intersectValues)


text:
Q: new to programming - it takes 17 bits to store 5 digits - how? I was reading this question which stated it takes 17 bits to store 5 digits, how is that possible? Here is what I understand:
I used the following calculator and entered the number 99999.
I got this huge number:
11000000111001110000110100111111100001101001111111000011010011111
From what I understand, each 0 and 1 represents one bit. As you can see, there are more than 17 bits!
Am I understanding this wrong?
Also, it was also stated:

"Now the first binary value which allows you to fit 99999 numbers is 131072,"

Huh? I thought binary values are ONLY 0 and 1? What am I missing here?

A: 99 999 in binary is 11000011010011111, exactly as your calculator says. I don't know what you entered but clearly you made a typo somewhere.
17 bits can store a number up to 2^17, hence = 131072, while 16 bits can only store up to
2^16 = 65536.
So you do need at least 17 bits to store 99 999, not any more, not any less.

A: 2^16 = 65,536, so to capture every 5 digit number, you'd need 2^17 = 17 bits.
The part about "first binary value ..." makes no sense to me

A: Well, 16 bits can store a number as high as 2^16 - 1 = 65535. That's assuming unsigned numbers (non-negative), which means it is not enough to represent of 5 digits decimal numbers.
With 17 bits you can get represent unsigned numbers as high as 2^17 -1 = 131071.

A: I think your main problem is finding your way through the imprecise language typically used between persons equally experienced within a domain. The number 131072 is 217, and that is the smallest power of two which exceeds five digits in decimal notation. In other words, to store any 5 decimal digits, you need those 17 bits because that's the smallest number of bits which covers the range 0-99999.
In the quote you present the author assumes familiarity with the number 131072, the fact that it is a power of two, therefore a round number in binary notation, and the fact that, for any n, there are exactly 2n distinct n-digit binary numbers.

A: Rather then using an online calculator, I would use Java and Integer.toBinaryString(int) with something like -
int val = 99999;
String binaryString = Integer.toBinaryString(val);
System.out.printf("%d is binary %s and %d binary digits long", val,
        binaryString, binaryString.length());

And the output is
99999 is binary 11000011010011111 and 17 binary digits long

A: Consider the possibilities for storing a 5 digit decimal number:
00000
11111
22222
33333
44444
55555
66666
77777
88888
99999

For each digit, you have 10 (i.e. "base 10") possible values, and with 5 digits you have 10*10*10*10*10 = 10^5 = 100000 (0 is counted) possible values.
For a 17 digit binary number:
00000000000000000
11111111111111111

Using the same logic, you have 2*2*...*2 = 2^17 = 131072 possible values ranging from 0 to 131071.  As to why you need 17 bits? Well, 2^16 = 65536, which can't hold 99999.


text:
Q: How to check if a string contains a string from a list? I want to check if a string the user inputted contains one of the strings in a list.
I know how to check if the string contains one string but I want to know how to check if a string contains either this string, or that string, or another string.
For example, if I am checking the user's input to see if it contains a vowel.. there can be 5 different choices when we're talking about vowels (a, e, i, o, or u). How can I check to see if the string the user inputted has one of those?

A: Using any:
>>> vowels = 'a', 'e', 'i', 'o', 'u'

>>> s = 'cat'
>>> any(ch in vowels for ch in s)
True
>>> s = 'pyth-n'
>>> any(ch in vowels for ch in s)
False

A: >>> vowels = set(['a', 'e', 'i', 'o', 'u'])
>>> inp = "foobar"
>>> bool(vowels.intersection(inp))
True
>>> bool(vowels.intersection('qwty'))
False

A: This is the basic logic you want:
def string_checker(user_input_string, vowels):
    for i in vowels:
       if i in user_input_string:
          return 'Found it'
    return 'Sorry grashooper :('

print string_checker('Hello',('a','e','i','o','u'))

The short cut way to do this is by using the built-in any() method; which will return true if any of the items in it returns a truth value.
Here is how it would work:
any(i in user_input_string for i in vowels)

The difference is that instead of returning a custom string, this method will return True or False; we can use it the same way in our loop:
if any(i in user_input_string for i in vowels):
    print('Found it!')
else:
    print('Oh noes! No vowels for you!')

A: Checking the strings sequentially works, but if it's too inefficient for your case, you can use Aho-Corasick algorithm.

A: You can use this syntax
if myItem in list:
# do something

also look at the functions:
http://docs.python.org/2/library/functions.html


text:
Q: Balloon tooltip with close button - C# How do I create a ballon tool tip with a close button.
I can show a tooltip:
TaskbarIcon.ShowBalloonTip(10000);

but I can't do the opposite:
TaskbarIcon.CloseBalloonTip();

Or even a way to show a close box on a Balloon Tip.
I saw this question posted on another site but with no (free) answer.
Thanks in advance

A: I was able to find a simple answer. Instead of using:
TaskbarIcon.ShowBalloonTip(10000);

I could use the second form of this function:
TaskbarIcon.ShowBalloonTip(10000,"Title","Message",ToolTipIcon.None);

This actually adds a close box to the balloon tip!

A: You might find this interesting:
http://www.tooltips.net/
This question has a helpful answer on closing the balloon.
Unless you need to hook an event on close, you don't need a button on the balloon, and even if you do, you can hook the balloon's click event to accomplish the same thing.
There are flags that allow you to do things like put an X in the upper right hand corner of the balloon so that the user can dismiss it.  See here for more info:
http://msdn.microsoft.com/en-us/magazine/cc188923.aspx


text:
Q: Values dissapear in cascading dropdown (Ionic React) I generated a "double" cascading dropdown to choose values from and everything works well, the values get saved as they should and are also displayed as they should, but as soon as I refresh (which needs to happen automatically) the 2nd and 3rd value just disappear (but are still there inside the storage).
Inside the cascading dropdowns I save every chosen value to the storage and afterwards the next can be picked. And I just don´t know why it is not showing the values, because they are saved and with other values it is working fine…
In other dropdowns I just access the data via the value inside the IonSelect like this value={this.props.photoObject.id}, but it is just working until it refreshes…
The object holding all the values is sent to the dorpdown component to access it like this:
<Select photoObject={photo} />

The Select Component is right here:
class Select extends React.Component {

  constructor() {
    super();
    this.state = {
      DDL1: [],
      DDL2: [],
      DDL3: [],
      selectDDL1:"",
      selectDDL2:"",
      selectDDL3:"",
    };
  };

  componentDidMount() {
    this.setState({
      DDL1: parkData
    });
  };

  async handleChangeDDL1(target) {
    console.log("DDL1:",target);
    this.setState({selectDDL1: target});
    this.setState({DDL2: this.state.DDL1.find(x => x.bezirk === target).DDL2});

    const {value} = await Storage.get({key: PHOTO_STORAGE });
    let array = JSON.parse(value);
    let index = array.findIndex((array) => array.filepath === this.props.photoObject.filepath);
    if(index !== -1) {
      array[index] = {
          time: array[index].time,
          part: target,
          park: array[index].park,
          id: array[index].id,
        }
    } else {
        console.log("error");
    };
    await Storage.set({key: PHOTO_STORAGE, value: JSON.stringify(array)})

  }

  async handleChangeDDL2(target) {
    console.log("DDL2:",target);
    this.setState({selectDDL2: target});
    this.setState({DDL3: this.state.DDL2.find(x => x.objekt === target).DDL3});

    const {value} = await Storage.get({key: PHOTO_STORAGE });
    let array = JSON.parse(value);
    let index = array.findIndex((array) => array.filepath === this.props.photoObject.filepath);
    if(index !== -1) {
      array[index] = {
          time: array[index].time,
          part: array[index].part,
          park: target,
          id: array[index].id,
        }
    } else {
        console.log("error");
    };
    await Storage.set({key: PHOTO_STORAGE, value: JSON.stringify(array)});

  }

  async handleChangeDDL3(target) {
    console.log("DDL3:",target);
    this.setState({selectDDL3: target});

    const {value} = await Storage.get({key: PHOTO_STORAGE });
    let array = JSON.parse(value);
    let index = array.findIndex((array) => array.filepath === this.props.photoObject.filepath);
    if(index !== -1) {
      array[index] = {
          time: array[index].time,
          part: array[index].part,
          park: array[index].park,
          id: target,
        }
    } else {
        console.log("error");
    };
    await Storage.set({key: PHOTO_STORAGE, value: JSON.stringify(array)});

  }

  render() {
    return (
      <div>
        <IonItem>
          <IonLabel position="stacked">City</IonLabel>
          <IonSelect name="part" placeholder="Bitte wählen" value={this.props.photoObject.part} onIonChange={e => this.handleChangeDDL1(e.detail.value)}>
            {this.state.DDL1.map((x, index) => {
              return <IonSelectOption value={x.bezirk} key={index}>{x.ortsteil}</IonSelectOption>
            })}
          </IonSelect>
        </IonItem>
        <IonItem>
        <IonLabel position="stacked">Park</IonLabel>
        <IonSelect name="park" placeholder="Bitte wählen" value={this.props.photoObject.park} onIonChange={e => this.handleChangeDDL2(e.detail.value)}>
            {this.state.DDL2.map((x, index) => {
                return <IonSelectOption value={x.objekt} key={index}>{x.park}</IonSelectOption>
            })}
          </IonSelect>
        </IonItem>
        <IonItem>
        <IonLabel position="stacked">ID</IonLabel>
        <IonSelect name="id" placeholder="Bitte wählen" value={this.props.photoObject.id} onIonChange={e => this.handleChangeDDL3(e.detail.value)}>
            {this.state.DDL3.map((x, index) => {
                return <IonSelectOption value={x} key={index}>{x}</IonSelectOption>
            })}
          </IonSelect>
        </IonItem>
      </div>
    );
  }
}

The data to be displayed inside the cascading dropdowns comes from a external file with an array:
export let parkData = [
    {
        ortsteil: "city1",
        bezirk: "01",
        DDL2: [
          {
            park: "park12",
            objekt: "0112",
            DDL3: [1,2,3,4,5,6,7],
          }
        ],

    },
        {
        ortsteil: "city2",
        bezirk: "22",
        DDL2: [
          {
            park: "park07",
            objekt: "2207",
            DDL3: [1,2,3,4,5,6,7,8,9],
          }
        ]
    },
]

Btw this was the video for cascading dropdown in React I used for mine if someone is looking for one: https://www.youtube.com/watch?v=dwMorR0KyZ4&ab_channel=HarithaComputers%26Technology


text:
Q: long text doesn't fit in a textview i have a simple question but i didn't how to solve i tried some stuff but didn't helpso i wanna know if i display a long text into a textview and it doesn't fit they just cut the last word i want to put "..." in the end if the text if it is too big for the textview.
this is the textview code
 <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="60dp"
    android:layout_marginTop="15dp"
    android:layout_marginBottom="65dp"
    android:layout_weight="0.5"
    android:autoSizeTextType="uniform"
    android:clickable="true"
    android:gravity="left"
    android:text="TextView"
    android:textColor="#000"
    android:textSize="13sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

enter image description here

A: You can add below code in your TextView
android:ellipsize="end"
android:maxLines="1"


text:
Q: How can I create a graph from an equation with two unknowns with python? I want to create a probably plot with a equation and two unknowns but I didn't success...
Here is my script
from numpy import exp, sqrt, linspace
from matplotlib import pyplot as plt
from pylab import meshgrid, cm, imshow, contour, clabel, colorbar, axis, title, show

plt.rcParams["figure.figsize"] = [10, 5]
plt.rcParams["figure.autolayout"] = True

def f(x, y):
return (1 / sqrt(x)) * exp(-y / 50) * (1 - exp(-x / 1097) * (2 * exp(-y / (2 * 50)) - 1))

x = linspace(10, 1000, 990)
y = linspace(10, 50, 40)
X, Y = meshgrid(x, y)
Z = f(X, Y)

Thank you so much !!
I would like to have a x value between 10 and 1000 and y value between 10 and 50 for example. And obtain this kind of plot.

A: As explained in This Link You can use matplotlibs 3d plotting api. Here's an example:
fig = plt.figure()
ax = plt.axes(projection='3d')
plt.xlim(10, 1000)
plt.ylim(10, 50)
# Some Different Types of Plots That You can Use:
ax.scatter3D(X, Y, Z, c=Z, cmap='Greens')
# ax.plot_wireframe(X, Y, Z, color='black')
# ax.plot3D(X.flatten(), Y.flatten(), Z.flatten())
# ax.contour3D(X, Y, Z, 990, cmap='binary')
plt.savefig('test.png')


text:
Q: custom claims in Azure AD to add windows AD groups I would like to know how can I add a windows AD group into a custom claim on Azure AD? I am looking to use AD groups for applications running on a platform that uses role-claims or custom claims to enable applications to have access groups or AD groups separately.

A: •   You can add the custom group claims in a token configuration for your application deployed in Azure AD as follows. Also, since you are adding AD groups, it is considered that those groups are synchronized from on-premises AD through Azure AD Connect to be used as group claims in token configuration.

*

*To configure group claims, go to your configured application in Azure AD  enterprise applications, click on the application and select 'Single Sign On'  User Attributes & Claims  Add a group claim  Use the radio buttons to select the 'Security groups' option as below

*To emit groups using Active Directory attributes synced from Active Directory instead of Azure AD objectIDs select the required format from the drop-down. Only groups synchronized from Active Directory will be included in the claims.

*To configure the group claim as a custom claim role by giving it a custom claim name, select the box 'Customize the name of the group claim' as below while also checking the box 'Emit groups as role claims' to use the group as a role claim in your application. Please take into consideration that if the option to emit group data as roles is used, only groups will appear in the role claim. Any Application Roles the user is assigned will not appear in the role claim.

Thus, you can configure AD groups as role claims for an application in Azure AD. Please find the documentation link for reference: -
https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-fed-group-claims#add-group-claims-to-tokens-for-saml-applications-using-sso-configuration


text:
Q: How to analyse and work with a Android Project without Documentation? I got a Project from my Company without Documentation. Now I have to add some things to this Project like new Add features etc. But I have no clue how this Project is organized and where it starts... Does anyone know how to work with a Project like this? Can I analyse it with a shema?
How can i find the startpoint of this application?
and is there a way to debug from A to Z?

A: Look in the manifest file for the main activity.
While others may chime in with Android-specific answers, you should think of handling this project as "legacy code" -- created by someone else, with poor or no documentation, and little idea (initially) of how things were implemented.
Check out Working Effectively with Legacy Code by Feathers if you'd like a decent book on your problem. Also relevant, but not Android-specific, is advice in the ebook "Rails Rescue" and the "Legacy Code" chapter in Rails Test Prescriptions. Though Rails-related, the advice the authors give is directly applicable to most projects.
In a nutshell:

*

*get the project under version control if it isn't already (and if it is, you're in luck, as you can review the commit history to get a feel for things)

*get the test suite running cleanly. No test suite? Get a simple test stub started

*commit yourself to creating tests for every new feature you implement

Lastly, read the code. You're going to have to bite the bullet and familiarize yourself with the implementation -- there's no way around that.

A: The start point (The main activity) of the application can be found in the manifest file:
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Whichever activity has this intent-filter is the entry point of the app

A: check in Manifest.xml the <activity> lines someone should got
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

this is where the apk starts
then i would start at the onCreate() method of this class. You should also check for a Service that maybe starts when the device boots.
Check for a BroadcastReceiver and something like this
 if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))

A: As JesperB said, find the start activity in the manifest.
Then I would run the app in debug mode and just follow where everything leads as you use the app, making notes along the way.
You might also try running the view heirarchy viewer on it, that could provide some direction too.


text:
Q: How to access internal storage using Expo.FileSystem to save file in any directory that i wish? I am using Expo.FileSystem here and I have to download file from my api and save it to my Videos folder in internal storage.
I have to save the file to my videos folder and not in FileSystem.documentDirectory folder.
downloadFile(){
    FileSystem.downloadAsync(
      'http://192.168.1.7:4200/video',
      FileSystem.documentDirectory + 'yellow.mp4'
    ).then(({ uri }) => {
       console.log('Finished downloading to ', uri);
      })
     .catch(error => {
        console.error(error);
     });
 }

If I put any other location instead of FileSystem.documentDirectory + 'yellow.mp4' then it shows this location is not writable.
please help...


text:
Q: Custom Pipeline Component to inherent Flat File Disassembler We will be receiving the CSV file from the receive port with header and body, and I am creating a Custom Pipeline component to check if the body schema has any records if it has any records it will be doing just disassembling and if it has no records it will have to construct a new message and that will be used in sending notifications.
I understand that we can inherit the FFDasmComponent for doing disassemble the received CSV file and convert them in to XML for doing further mapping. But I get below error


text:
Q: Ember - Set a Dynamic Page Title per route I have set up my Ember app to use the pod structure. I've created a topbar-nav component which I display on the main page. In the topbar-nav component I have set up the page title, which I would like to set automatically per route so for the dashboard route the title should be Dashboard, for the dashboard/categories the title should be categories and so on.
Here's my app structure:

*

*app

*

*application

*components

*

*topbar-nav

*dashboard

*categories

The app router - router.js
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('dashboard', function() {
    this.route('categories');
  });
});

export default Router;

And the templates:
application/template.hbs

    {{sidebar-nav}}

        {{topbar-nav}}

    {{outlet}}

components/topbar-nav/template.hbs

{{title}}

{{yield}}

components/topbar-nav/component.js
import Ember from 'ember';

export default Ember.Component.extend({
    title: 'Component title'
});

As you can tell already the title I get rendered is 'Component title'
The most accurate answer I got by now is this one:
Ember dynamic titles
though after trying a lot of different approaches I couldn't find a good solution.
Is there a clean and easy way of doing this? Any ideas and solutions are much appreciated.

A: I wanted a similar dynamic title and found this page. So here is my solution based on @AcidBurn's note that the application controller has a currentRouteName property.
If you want the last child route:
screen_title: Ember.computed('currentRouteName', function () {
    let route = this.get('currentRouteName').split('.');

    // Return last route name (e.g. categories from dashboard.categories)
    return route[route.length - 1];
}),

If you want the parent route:
screen_title: Ember.computed('currentRouteName', function () {
    let route = this.get('currentRouteName').split('.');

    // Return parent route name (e.g. reports from reports.index)
    return route[0];
}),

A: ember-page-title seems better than ember-cli-document-title now (better docs+api)


text:
Q: Authorize/Capture for PayPal Using PayPal IPN, can we implement delayed payment. Perfect example is Groupon where card is charged only when deal is tipped. Can someone throw light on implementation part using PayPal IPN and also how multiple cards can be charged at once when deal is tipped.

A: For Authorize And Capture:
To make a payment authorize you will have to pass "authorization" in paymentmethod parameter instead of "sale"
  <input type="hidden" name="paymentaction" value="authorization" />

So, For this type of payment, paypal will not charge the sender immediately but will wait till receiver confirmation. To capture this payment two methods are available:

*

*Receiver will either click on capture button in account

*It can be done via a API - to capture the payment use DoCapture and void the payment use DoVoid


text:
Q: C# propertyGrid - how to specify which constructor it uses for structs? I have a simple problem: I have a struct Coordinates3D which is basically a 3D Point, but it also checks for boundaries. It has static maxX and minX and so on members, and checks the assigned coordinate value to fit the boundaries. It also has a boolean _check_boundaries, if this is false then it wont check boundaries and allow any values for coordinates. It looks basically like this
  struct Coordinate3D {
    public bool _check_boundaries;
    private int _x;
    public int X{
      get{ return _x;}
      set {
        if (_check_boundaries)
        {
          ... check min/max ...
        }
        _x = value;
      }
    }
    ... y and x follow...
  }

I want to edit this object in propertyGrid (it is a property of a class). However, some classes have coordinates that are bounded, some not. So, for some classes, boundaries must be checked, but not for others. However, when i change this struct's property in propertyGrid, it seems to create a new struct each time. Therefore, it is either "check boundaries" for all cases or "do not check boundaries" for all cases, depending on what's set in the constructor.
Is there any way around this?


text:
Q: CentOS 7 and MariaDB issue I have recently moved to DigitalOcean, and installed Centos7 along with its default MysQl server (MariaDB).
But I am facing since first install.
MySql is exiting down spontaneously and there is no memory issue. I checked using:
egrep -i "out of memory|oom" /var/log/dmesg
egrep -i "cannot allocate memory|can't allocate" /var/log/mysql*/error.log

I am worried that why mysql is not restarting itself after closing ?
is this a MariaDB bug ? how can I fix it ?
Anyway to check why its closing ?
Currently I am using crontab -e for restarting MySql, but that did not helped a lot.
Thanks for the help
found some logs in mariadb.log:
150105  7:20:03 [Note] Plugin 'FEEDBACK' is disabled.
150105  7:20:03 [Note] Server socket created on IP: '0.0.0.0'.
150105  7:20:03 [Note] Event Scheduler: Loaded 0 events
150105  7:20:03 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.5.40-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server
150105  7:21:25 [Note] /usr/libexec/mysqld: Normal shutdown

150105  7:21:25 [Note] Event Scheduler: Purging the queue. 0 events
150105  7:21:25  InnoDB: Starting shutdown...
150105  7:21:26  InnoDB: Shutdown completed; log sequence number 1619889
150105  7:21:26 [Note] /usr/libexec/mysqld: Shutdown complete

150105 07:21:26 mysqld_safe mysqld from pid file /var/run/mariadb/mariadb.pid ended

A: ... assuming you have enough RAM to run mysqld, try running MySQLTuner-perl by major and tweak your my.ini.


text:
Q: how do you create buttons in swift? I am currently developing a game using swift with xCode and I'm not quite sure how to make a button "pressable". I usually do something like this:
var button = SKSpriteNode(imageNamed:"sample")
button.xScale = 1
button.yScale = 1
button.name = "pressHere"

and then in the touchesBegan function I do this:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    var touch: UITouch = touches.anyObject() as UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)

    if (node.name == "pressHere") {
        //whatever I want the button to do
    }
}

I've found that if I do this method a lot my game will crash. Perhaps this isn't really what causes the issue, but it's always helpful learning a new way :)

A: Swift Spritekit Adding Button Programaticly
This Link posted by Gavidi Harikrishna answered my question completely. I hope it also reaches who ever seeks the same answer


text:
Q: Uphold the original numeration when using 'skip rows between index' I have the same table (with n rows) several times and I want to highlight some rows.
But I need to skip some rows in each case (i.e. 'skip row 0,...,x'   or 'skip row x,...,n' etc.).  That means pgfplotstable is changing the numeration.
How can I uphold the original numeration, here in row 3 for example.

\documentclass{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.17}
\usepackage{colortbl}

\pgfplotstableread[]{
A    B     C
0   x     x
1    x     x
2    x     x
3    x     x
4    x     x
5    x     x
}{\mytable}

\begin{document}
\section{The row with Number 3 should be highlighted in both Tables}
\subsection{Good}
\pgfplotstabletypeset[string type,
every row no 3/.style={   before row=\rowcolor{yellow}},
skip rows between index={5}{6}
]{\mytable}

\subsection{Bad}
\pgfplotstabletypeset[string type,
every row no 3/.style={   before row=\rowcolor{yellow}},
skip rows between index={0}{2}
]{\mytable}
\end{document}

A: It seems not hard to make pgfplotstable work with tabularray package. And with tabularray it is easy to change the styles of the tables.

New Solution
\documentclass{article}

\usepackage{pgfplotstable}
\pgfplotsset{compat=1.17}

\usepackage{tabularray}

\pgfplotstableread[]{
  A    B     C
  0    x     x
  1    x     x
  2    x     x
  3    x     x
  4    x     x
  5    x     x
}{\mytable}

\newcommand{\MyGobble}[1]{}

\begin{document}

\section{Highlight rows with number 3 with tabularray}

\subsection{Good}

\pgfplotstabletypeset[
  string type,
  skip coltypes,
  begin table=\begin{tblr}{
    stretch = 0,
    rowsep = {3pt},
    columns = {c},
    row{5} = {yellow9},
    row{7} = {rowsep=0pt,cmd=\MyGobble},
  },
  end table=\end{tblr},
]{\mytable}

\subsection{Also Good}

\pgfplotstabletypeset[
  string type,
  skip coltypes,
  begin table=\begin{tblr}{
    stretch = 0,
    rowsep = {3pt},
    columns = {c},
    row{5} = {yellow9},
    row{2-3} = {rowsep=0pt,cmd=\MyGobble},
  },
  end table=\end{tblr},
]{\mytable}

\end{document}

Old Solution
\documentclass{article}

\usepackage{pgfplotstable}
\pgfplotsset{compat=1.17}

\usepackage{tabularray}

\pgfplotstableread[]{
  A    B     C
  0    x     x
  1    x     x
  2    x     x
  3    x     x
  4    x     x
  5    x     x
}{\mytable}

\newcommand{\MyGobble}[1]{}

\NewTblrEnviron{mytblra}
\SetTblrInner[mytblra]{
  stretch = 0,
  rowsep = {3pt},
  row{5} = {yellow9},
  row{7} = {rowsep=0pt,cmd=\MyGobble},
}

\NewTblrEnviron{mytblrb}
\SetTblrInner[mytblrb]{
  stretch = 0,
  rowsep = {3pt},
  row{5} = {yellow9},
  row{2-3} = {rowsep=0pt,cmd=\MyGobble},
}

\begin{document}

\section{Highlight rows with number 3 with tabularray}

\subsection{Good}

\pgfplotstabletypeset[
  string type,
  begin table=\begin{mytblra},
  end table=\end{mytblra},
]{\mytable}

\subsection{Also Good}

\pgfplotstabletypeset[
  string type,
  begin table=\begin{mytblrb},
  end table=\end{mytblrb},
]{\mytable}

\end{document}


text:
Q: Error on using weka library on android (Want to Implement Machine Learning in an Android Application) For implementing Machine Learning in an Android Application, I am using 'WEKA Tool' which I have included it on the Project 'libs' and compile it from the 'gradle' of project.
But while running on the phone when that functions invoked which doing the classification (calling 'RandomForest Classifier'), my app goes crashed.
I am getting this 'Runtime Error'. Can anyone help me please?
   Unable to create WEKA_HOME (/wekafiles)
   Unable to create packages directory (/wekafiles/packages)
   Unable to create repository cache directory (/wekafiles/repCache)
   D/AndroidRuntime: Shutting down VM
   E/AndroidRuntime: FATAL EXCEPTION: main
          Process: com.example.weirdmyth.testapp, PID: 31474
          java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/GraphicsEnvironment;
               at weka.core.packageManagement.PackageManager.setProxyAuthentication(PackageManager.java:191)
               at weka.core.WekaPackageManager.establishWekaHome(WekaPackageManager.java:377)
               at weka.core.WekaPackageManager.<clinit>(WekaPackageManager.java:162)
               at weka.core.Utils.readProperties(Utils.java:174)
               at weka.core.Capabilities.<init>(Capabilities.java:275)
               at weka.classifiers.AbstractClassifier.getCapabilities(AbstractClassifier.java:508)
               at weka.classifiers.trees.RandomTree.getCapabilities(RandomTree.java:602)
               at weka.classifiers.trees.RandomForest.getCapabilities(RandomForest.java:182)
               at weka.classifiers.meta.Bagging.buildClassifier(Bagging.java:701)
               at com.example.weirdmyth.testapp.MainActivity.showExtractData(MainActivity.java:68)
               at com.example.weirdmyth.testapp.MainActivity.access$000(MainActivity.java:18)
               at com.example.weirdmyth.testapp.MainActivity$1.onClick(MainActivity.java:35)
               at android.view.View.performClick(View.java:4794)
               at android.view.View$PerformClick.run(View.java:19905)
               at android.os.Handler.handleCallback(Handler.java:739)
               at android.os.Handler.dispatchMessage(Handler.java:95)
               at android.os.Looper.loop(Looper.java:139)
               at android.app.ActivityThread.main(ActivityThread.java:5298)
               at java.lang.reflect.Method.invoke(Native Method)
               at java.lang.reflect.Method.invoke(Method.java:372)
               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
         Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.GraphicsEnvironment" on path: DexPathList[[dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-weka_24a0e957b7a2bd7b1eca884c1d1fe17134d04e02-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-support-annotations-24.2.0_1d91a870686be0d9b2c0cad6f095599608f8ea8b-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-internal_impl-24.2.0_e60a43d4d67966d22f555860d8f3ea89bf40a00d-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-internal_impl-24.2.0_bab1238d93c9b1e214aa74253243e0e0a1179d1b-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-internal_impl-24.2.0_ac3ce21dd47241b373379a2a2250d916ddec89f2-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-internal_impl-24.2.0_86622e6ad735878a3262fd8fb6bc9c316447f2bd-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-internal_impl-24.2.0_024d25ee6599778d6213941fb989deeaa23d0a37-classes.dex", dex file "/data/data/com.example.weirdmyth.testapp/files/instant-run/dex/slice-com.android.support-support-vector-drawable-24.2.0_a300254740b0ce696848c36d6b2c7e26898aba9c-classes.dex", dex file "/data/data/com.example

A: try using this one: https://github.com/rjmarsan/Weka-for-Android
As writer says: and 100% functionality is not promised.  However, it's sure better than nothing.


text:
Q: Product Access for Partner Community Did anybody have experience with enabling Partner Community users with create/edit access for Product objects. I know you can't assign these permissions using the  Partner Community Profile, but are there any good workarounds?

A: I'm assuming you mean Product records as I know of no way for someone to create a new sObject from a Community.
If you did mean records, because of the permissions required, the only way one could do this would be to create a "mirror" object and use triggers to pass record inserts and updates back and forth between the Partner Community and your Org. This would be something to do with great caution.