Data structure for sorting/retrieval strings

Question: I have multiple arrays of strings, I used a comparison function to sort them in a priority queue. I overlooked the fact that I need to iterate through the strings..
What other data structure would you recommend? Perhaps something that allows a comparison function so that I get a sorted set of strings
I could effectively pop the elements from the priority queue but that means I would need auxiliary space before pushing them back onto the priority queue
It would be ideal if a vector allows a comparison function. Would an STL "set" work? I have a fixed number of elements (about 450).
Edit: Confirming that STL's set is working.. even without defining my own comparison function for strings.
Comment: You can use `std::sort` on a `std::vector`, and you can pass in a comparison function to define the sort order.  Do you need anything besides being able to iterate in order?
Comment: The comparison function is not a property of the container, but of the sort algorithm; any ordered container with random-access iterators will work fine with `std::sort`, which in turn allow a custom comparison functor.
Answer: I'm not really sure on what you need. I assume that by "I need to iterate through the strings" you mean that you need to iterate over the remaining (not "popped") strings in unsorted order and in addition need to access them using a priority queue (through "pop"). If you need to iterate over a sorted sequence, you should sort the input strings up front (e.g. through std::set) and not use a priority queue (priority queues doesn't necessarily fully sort all of the items right away, it sorts the sequence "on demand").
std::priority_queue uses an underlying container (defaults to std::vector). By inheriting this class you could get access to the container. The protected member variable is defined in the standard, and this should in theory be safe to do (don't bet that it is in real life though). However, inheriting STL containers is frowned upon.
An alternative is to create you're own priority queue, e.g. based on std::vector and std::make_heap, std::pop_heap and std::push_heap. std::priority_queue uses these functions internally.
Answer: A set would work, but you could just make a vector, reserve enough capacity, and then use sorted inserts using lower_bound. Since strings are cheap to swap, this should be fine (and in any case 450 is a tiny number).
A vector has constant-time lookup and random access, so if you don't need to insert and erase a lot, it's a better choice.


Connecting Nest thermostat to this power adapter

Question:
My question is probably simple for those in the know. I've looked at the manual, and researched and Googled, however I'm still not confident. I tested this and got 24v on the red wire in bottom left when system was on heat and cool. I got nothing on the blue wires on the right. However, something just doesn't feel right. I'm trying to connect the C wire part on the Google Power Adapter. My system is a PGB030075-1.
So does anybody know which wire I need to connect the C on the Power adapter to?
Answer: The lower right (grounded) terminal is the C connection on the 24V side.
Comment: This is right but don't connect your C wire to the ground lug behind the transformer or to any of the terminals there.  It's too close to the **open** live 120V wires, and any home-made connections you do with tape etc could end up touching those by accident.  Follow those other two wires from that terminal to wherever they go, and look for somewhere convenient and safe to connect your C wire at the other end.  Or cut one of them.  Just keep your connection away from the 120V side.
Comment: So I should connect to the yellow wire in this case?
Comment: No, not the yellow. Follow one of the other two wires to where they connect, and add your C to that connection, or cut one of those wires and splice in your C connection.


Does it make any difference if I choose the Bird or the Cage?

Question: I was wondering, does choosing the Bird or Cage Pendant in Bioshock Infinite change the game in ANY way (aside from which pendant Elizabeth wears around her neck for the rest of the game)?

I've read some people say that they didn't notice any differences, but does anyone know for sure?
Comment: +1 since this question is apparently found through google much more often than the other one (this one has a much better title)
Comment: It changes the short dialogue between the gentleman and the lady immediately thereafter (about which one of them guessed right), but I suppose that's not what you meant.
Answer: I found an answer: No. It seems to make no difference to the story or the characters :-/
Update:
An anonymous user offered the following:
"I believe it changes the Gear that you find. When I picked the Bird I noticed that the Gear I picked up all complimented my firearms. But when I chose the Cage, I got gear that complimented my Vigors. I have played the game through like 6 times."
I believe this wrong, however, as I've noticed that the gear you find seems randomised.


Python Google Slides API How to insert a text with hyperlink?

Question: I have looked through the documentation of Google Slides API, but I can't seem to find the section where you can insert a text with hyperlink. I am using python for integrating the API.
Answer: There are 2 methods to add links to a Google Slide, you can use TextStyle which is under the Text for presentations.pages or you can use UpdateTextStyleRequest under the Method: presentations.batchUpdate.
Here is a sample using UpdateTextStyleRequest, I first create a shape textbox, inserted the text New URL link added!, and update the style to hyperlink for the words URL link:
from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/presentations']

# The ID of the presentation
PRESENTATION_ID = 'SlideID'

def main():

    creds = None

    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('slides', 'v1', credentials=creds
        element_id = 'MyTextBox_10'
        page_id = 'g1e436298788_0_0'
        pt = {
            'magnitude': 200,
            'unit': 'PT'
        }
        requests = [
            {
                'createShape': {
                    'objectId': element_id,
                    'shapeType': 'TEXT_BOX',
                    'elementProperties': {
                        'pageObjectId': page_id,
                        'size': {
                            'height': pt,
                            'width': pt
                        },
                        'transform': {
                            'scaleX': 1,
                            'scaleY': 1,
                            'translateX': 50,
                            'translateY': 100,
                            'unit': 'PT'
                        }
                    }
                }
            },

            # Insert text into the box, using the supplied element ID.
            {
                'insertText': {
                    'objectId': element_id,
                    'insertionIndex': 0,
                    'text': 'New URL link added!'
                }
            },

            # Insert the URL for in the speficy range.
            {
                'updateTextStyle': {
                    'objectId': element_id,
                    'textRange': {
                        'type': 'FIXED_RANGE',
                        'startIndex': 4,
                        'endIndex': 12
                    },
                    'style': {
                        'link': {
                            'url': 'www.google.com'
                        }
                    },
                    'fields': 'link'
                }
            }

        ]

        # Execute the request.
        body = {
            'requests': requests
        }
        response = service.presentations() \
            .batchUpdate(presentationId=PRESENTATION_ID, body=body).execute()
        create_shape_response = response.get('replies')[0].get('createShape')
        print(f"Created textbox with ID:"
              f"{(create_shape_response.get('objectId'))}")

    except HttpError as err:
        print(err)

if __name__ == '__main__':
    main()

And it'll look like this:

You can also review the following Google guide Editing and Styling Text


How to show/hide elements based on radio selection

Question: I'm working on an Angular project and I want to create a structure in which a visitor can click through a number of questions. Depending on the selected radio button another element should show.
In AngularJS you could use
<input id="first1" type="radio" name="content" ng-model="contentTemplate" value="first">

and

This is the first content!

to show the element but this doesn't seem to be working in Angular2.
I've created a Plunkr
Answer: I can't use Plunkr (corporate proxy) but you need to bind your radio to your model like so
<input type="radio" [(ngModel)]="yourBoolean">

Don't forget to import FormsModule to make ngModel work
Comment: Do you mean `import { FormsModule }   from '@angular/forms';  `? or another sort of ngForms? Can't find much on Google about ngForms.
Comment: I'm sorry, I'm not very clear, I mix things up with angularJS. I meant `FormsModule`
Comment: Nice ! Remember to mark your topic as resolved then.


How much damage does Purification Nova do?

Question: The protoss have gained a new unit in their arsenal called the Disruptor.
New Unit: Disruptor

A light-mechanical unit from the Robotics Facility that can use Purification Nova.
Ability – Purification Nova: Once activated, the Disruptor becomes invulnerable and gains increased movement speed. After 4 seconds, the Disruptor emits a massive blast dealing AoE damage in a circle and immediately becomes vulnerable again, also losing its speed boost.

I've seen it on a few public streams now and it seems to kill anything within that damage range, however it doesn't list how much actual damage the blast does. How much damage does the blast do?
An example comparison, we know that the Yamoto Cannon of a battle cruiser does 300 damage.
Answer: 145 damage. That thing costs 300 gas, so it's one giant baneling.


Can I store an xml string in a resources file (.resx), without it getting encoded with < and >?

Question: In Visual Studio, I can put an xml string into the "Value" field. However, when I open up the actual .resx file, I see that it has been encoded to have < and >. I want the .resx file to be able to be edited manually without using the Visual Studio UI, and obviously this is messy with the > and <s. Could I somehow do this without the encoding?
Answer: My solution for the time being: use JSON for the value.
Answer: I'm not sure if this is what you're looking for, but I usually wrap values in my resx files in CDATA if I don't want to deal with < and >. Of course this is a mess too if you have CDATA in your xml string. Also as soon as you edit with the Visual Studio UI again, it will revert back to < >


How to get EditText values and show them as a html file in a Web view?

Question: How I can get the EditText values and show values as a html file in a Web view?  Please help me. Very thanks.
Answer: You don't need any file if what you want is to show the value in the WebView. Use:
mWebView.loadData("text: " + mEditText.getText().toString() + "", "text/html", null);


$\cos$ not a contraction on $\mathbb R$

Question: I know that $\cos$ is a contraction mapping on $[0, a]$ with $a<\pi/2$.
I also know that the proof of this uses the mean value theorem and it fails on $\Bbb R$.
However, this is not a proof to the fact that $\cos:\mathbb R\to \mathbb R$ is not a contraction.
How would one prove that? Is there a counter example?
Thank you!
Comment: @elRosca : see the answer below plus take $x_1$ to be $0$.
Answer: If $\cos$ is defined from $\mathbb R\to \mathbb R$, it is not a contraction mapping, i.e there is no $L\in (0,1)$ such that $|\cos x_1-\cos x_2|\le L|x_1-x_2|$ for all $x_1,x_2\in \mathbb R$. If this is not the case, we could let $x_2\to x_1$ and get that
$$
\lim_{x_2\to x_1}\frac{|\cos x_1-\cos x_2|}{|x_1-x_2|}=|\sin x_1|\le L<1,
$$
for any $x_1\in \mathbb R$. This is a contradiction as $\sin$ function achieves $1$ in $\mathbb R$ .

$\cos$ not a contraction on $\mathbb R$


Associate one column to another to create a third one in R

Question: 1  1          2         3      740      780      780      780
2  1          4         0      890      890      890      890
3  2          3         5      550      550      550      550
4  2          5        10      890      250      250      400
  wage_may wage_jun wage_jul wage_aug wage_sep wage_oct wage_nov
1      780      780      780      780      780      780      780
2      890      890      890      890      890      790      250
3      550      550      550      550      550      550      550
4      500      890      600      750      890      300      300
  wage_dec
1      780
2      300
3      550
4      300

structure(list(id = c(1L, 1L, 2L, 2L), hire_month = c(2L, 4L,
3L, 5L), sep_month = c(3L, 0L, 5L, 10L), wage_jan = c(740L, 890L,
550L, 890L), wage_feb = c(780L, 890L, 550L, 250L), wage_mar = c(780L,
890L, 550L, 250L), wage_apr = c(780L, 890L, 550L, 400L), wage_may = c(780L,
890L, 550L, 500L), wage_jun = c(780L, 890L, 550L, 890L), wage_jul = c(780L,
890L, 550L, 600L), wage_aug = c(780L, 890L, 550L, 750L), wage_sep = c(780L,
890L, 550L, 890L), wage_oct = c(780L, 790L, 550L, 300L), wage_nov = c(780L,
250L, 550L, 300L), wage_dec = c(780L, 300L, 550L, 300L)), class = "data.frame", row.names = c(NA,
-4L))

I would like to create a column for last wage in the following way:
If sep_month is 3, I would like this new column to give last_wage as the one in wage_mar;
if sep_month is 4, I would like this column to give last_wage as the one in wage_apr and so forth.
I basically want to associate the sep_month to its respective wage depending on the month.
Comment: And what happens when, as in your example data, `sep_month` is `0`?
Comment: Sorry, then it would be wage_dec
Comment: Wouldn't `sep_month` by `12` for December? Are the values for October, November, and December 10, 11, and 12?
Comment: Yes, the values 1, 2, ... correspond to the months January, February, etc. However if there was no separation (ie, sep_month = 0), I would merely like to take the last wage on the year, which is wage_dec
Answer: You could do this with mutate() and case_when() from the dplyr library:
df %>%
  mutate(last_wage =
    case_when(
      sep_month == 0 ~ wage_dec,

      sep_month == 1 ~ wage_jan,
      sep_month == 2 ~ wage_feb,
      sep_month == 3 ~ wage_mar,
      sep_month == 4 ~ wage_apr,
      sep_month == 5 ~ wage_may,
      sep_month == 6 ~ wage_jun,
      sep_month == 7 ~ wage_jul,
      sep_month == 8 ~ wage_aug,
      sep_month == 9 ~ wage_sep,
      sep_month == 10 ~ wage_oct,
      sep_month == 11 ~ wage_nov,
      sep_month == 12 ~ wage_dec,

      TRUE ~ NA_integer_
    )
  )

Comment: Thank you very much! It worked perfectly! However, when I tried to add "sep_month == 0 ~ wage_dec,", I got an error.
Comment: OK, I just saw your last comment about using the last wage in the table, i.e., December. I've modified my code and it should work for you now.
Answer: Another option would be to pivot to long form and make the calculation then pivot back to wide form with tidyverse. I also added in converting 0 to 12, but then converted it back at the end.
library(tidyverse)

df %>%
  mutate(rowid = row_number()) %>%
  pivot_longer(-c(id, hire_month, sep_month, rowid), names_to = c(".value", "month"), names_sep = "_") %>%
  mutate(sep_month = ifelse(sep_month == 0, 12, sep_month),
         month_num = match(str_to_title(month),month.abb),
         last_wage = ifelse(sep_month == month_num, wage, NA) ) %>%
  select(-month_num) %>%
  pivot_wider(id_cols = c(id, hire_month, sep_month, last_wage), names_from = "month", names_glue = "{.value}_{month}", values_from = wage) %>%
  group_by(id, hire_month, sep_month) %>%
  fill(everything(), .direction = "downup") %>%
  slice(1) %>%
  mutate(sep_month = ifelse(sep_month == 12, 0, sep_month))

Output
     id hire_month sep_month last_wage wage_jan wage_feb wage_mar wage_apr wage_may wage_jun wage_jul wage_aug wage_sep wage_oct wage_nov wage_dec
  <int>      <int>     <dbl>     <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>
1     1          2         3       780      740      780      780      780      780      780      780      780      780      780      780      780
2     1          4        12       300      890      890      890      890      890      890      890      890      890      790      250      300
3     2          3         5       550      550      550      550      550      550      550      550      550      550      550      550      550
4     2          5        10       300      890      250      250      400      500      890      600      750      890      300      300      300


Adding multiple ID's to javascript

Question: I'm a Javascript newbie, and am trying to add multiple ID's to this script that adds plus/minus symbols to my bootstrap accordions:
jQuery(function ($) {
  var $active = $('#accordion .panel-collapse.in').prev().addClass('active');
  $active.find('a').append('');
  $('#accordion .panel-heading').not($active).find('a').prepend('');
  $('#accordion').on('show.bs.collapse', function (e)
  {
    $('#accordion .panel-heading.active').removeClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
    $(e.target).prev().addClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
  });
  $('#accordion').on('hide.bs.collapse', function (e)
  {
    $(e.target).prev().removeClass('active').find('.glyphicon').removeClass('glyphicon-minus').addClass('glyphicon-plus');
  });
});

Right now this code only works on one accordion, and not all four that I have on the page: #accordion, #accordion2, #accordion3, #accordion4.
Any help is appreciated!
Comment: 1) replace ID with something like `data-role="accordion"`, 2) replace each 'inner lookup' (like `$('#acc .panel-heading.active')`) with `$(this).find('.panel-heading.active')` etc.
Comment: Im not really sure what u are trying to do.. U wanna loop trough all id's or just wanna add same function to each id..
Comment: You could try: `$('[id*="accordion"]')` more info: [How do you select all id tags that contain a certain string in javascript?](http://stackoverflow.com/questions/8126218/how-do-you-select-all-id-tags-that-contain-a-certain-string-in-javascript)
Comment: I think add the same function to each ID
Comment: @DIEGOCARRASCAL Looks like your solution works! Thanks for sending over.
Answer: This may work:
    $('[id*="accordion"]').click(function(){
      let active = $('#'+$(this).attr("id")+' .panel-collapse.in').prev().addClass('active');
      $active.find('a').append('');
      $('#'+$(this).attr("id")+' .panel-heading').not($active).find('a').prepend('');
      $(this).on('show.bs.collapse', function (e)
      {
        $('#'+$(this).attr("id")+' .panel-heading.active').removeClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
        $(e.target).prev().addClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
      });
      $(this).on('hide.bs.collapse', function (e)
      {
        $(e.target).prev().removeClass('active').find('.glyphicon').removeClass('glyphicon-minus').addClass('glyphicon-plus');
      });
    });

I try to target all elements which contain "accordion" in their id and then modify your code to target the clicked "accordeon" by its ID.
Answer: You can use a loop to iterate through each of your id's and add the number to the end of each selector, the JS would operate as follows:
jQuery(function ($) {
for (var i =1; i<=4; i++) {
  // Example code
  $('#accordion'+i+'').css('background','#ff0000');
}
});

See this fiddle:
https://jsfiddle.net/6fk8qk6d/
Answer: One of the engineers I work with did the following, which seems to work well:
jQuery(function () {
jQuery( ".accordion" ).each(function( index ) {
var i = index+1;
var jQueryactive = jQuery('#accordion'+i+' .panel-collapse.in').prev().addClass('active');
jQueryactive.find('a').append('');
  jQuery('#accordion'+i+' .panel-heading').not(jQueryactive).find('a').prepend('');
  jQuery('#accordion'+i).on('show.bs.collapse', function (e) {
jQuery('#accordion'+i+' .panel-heading.active').removeClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
jQuery(e.target).prev().addClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
  } );
  jQuery('#accordion'+i).on('hide.bs.collapse', function (e) {
jQuery(e.target).prev().removeClass('active').find('.glyphicon').removeClass('glyphicon-minus').addClass('glyphicon-plus');
  } );
});
});

Thanks to everyone who tried to help!

Adding multiple ID's to javascript


Find a value, return the cell below it (or up to 4 below it) where the first value starts with a 1

Question: I have a word file imported in Excel. The file is in column A, up to 400-500 rows long. To illustrate as an example:
<code>Type application
0 shortcut
1 Client installation (standalone)
0 Client installation with data on the network (fileshare needed)
0 Client/server (server needed)
0 Webbased without dependancies
0 Webbased with dependancies
Importancy
0 Company critical
1 Important
0 Supportive
</code>
And many other fields of interest. Now I have a formula that searches for a certain text value, for example "Product manager" and returns the value below it (the name). To illustrate:
<code>=INDEX(A:A;MATCH("Product manager";A:A;0)+2;1)
</code>
Here, the +2 returns the name of the product manager.
The problem I need YOUR help with!
The problem is as follows. In the big block of code above you see a bit value, with the 1 corresponding with the check box clicked in the word file. Now I want to search on Type application and return only the value corresponding with the 1, so in this case 1 Client installation (standalone).
The above solution with INDEX and MATCH doesn't work because it only returns a certain row below the search query (so row +1, or row +5). I want to find the value Type application, serach in the 6 rows below it and return the only 1 value it will find.
Answer: Following the example of my more illustrious colleagues, I have started trying to use INDEX for this sort of question, so the answer would be something like this:-
<code>=INDEX(INDEX(B$1:B$10,MATCH(D2,B$1:B$10,0)):B$10,MATCH(1,INDEX(A$1:A$10,MATCH(D2,B$1:B$10,0)):A$10,0))
</code>
so it finds the string (e.g. charlie) in column B, and searches the rest of the range in column A for a '1'.

If all the values are in one column as in the question, the formula becomes
<code>=INDEX(INDEX(A$1:A$10,MATCH(D2,A$1:A$10,0)):A$10,
MATCH("1*",INDEX(A$1:A$10,MATCH(D2,A$1:A$10,0)):A$10,0))
</code>

To put a limit on the range and error handling should be something like this:-
<code>=IFERROR(
INDEX(INDEX(A:A,MATCH(D2,A:A,0)):
INDEX(A:A,MATCH(D2,A:A,0)+4),
MATCH("1*",INDEX(A:A,MATCH(D2,A:A,0)):
INDEX(A:A,MATCH(D2,A:A,0)+4),0)),
"No entry")
</code>
If you wanted to search more than one column in the same way, you could use the same sort of formula but it wouldn't be practical without using helper columns. So copy it across (say) two columns, then display the first match.
Set up the start of search in E2:-
<code>=MATCH(D2,A$1:A$20,0)+1
</code>
End of search in F2 could just be E2+4, but you can also search up to the next 'subheading' using:-
<code>=MATCH(1,INDEX((INDEX(A$1:A$20,E2):A$20>"2")+(INDEX(A$1:A$20,E2):A$20=""),),0)+E2-2
</code>
The search for a cell starting with "1" in G2:-
<code>=IFERROR(MATCH("1*",INDEX(A$1:A$20,$E2):INDEX(A$1:A$20,$F2),0),"")
</code>
and pull across into H2 and I2.
Get the first of the three matches in J2:-
<code>=MIN(G2:I2)
</code>
And find which columns it applies to in K2:-
<code>=IF(J2=0,"",MATCH(J2,G2:I2,0))
</code>
Finally get the matching cell using the row and column in J2 and K2:-
<code>=IF(K2="","No entry",INDEX(INDEX(A$1:A$20,E2):C$20,J2,K2))
</code>
Comment: Thank you so much for your input and hard work for a complete stranger! I really dig this site. One last question and then I'm out. What if I want to put a search range of, for example +4 rows when it found a certain key? My scenario contains the second image. Some keys may have no 1, in this case I want it to return a certain value (for example, "no entry"). At the moment it searches till it finds a row that returns a 1, while I only want it to search in the next 3 of 4 or 5 rows.
Comment: Have added to my answer. Would be nice if it could search up to the next 'key', but don't know how to do this :-)
Comment: Thanks alot Tom Sharpe for your help so far. I have one more question I just can't figure out and I really hope you can shed some light upon this problem.

The thing: I want to search in a specific RANGE of cells and columns. For example, I search on the term "Application". Once it is found, I want to search FROM that cell (for example, A30) up to 5 rows down and 2 columns right (so from A30 to C35) for the FIRST value that returns a one. I want that first 1 to be returned with the corresponding text following it (using the 1 as a wildcard).... I hope you can help me!
Comment: That would be really tough. Because MATCH can only deal with one column, you'd probably need a different approach using an array formula or VBA. Will come back to you if I think of anything.
Comment: Actually it is OK to do it but will need some helper columns because too much to do with one formula. Will add to my answer.
Answer: Say we have data like:

and we want to:

find Puck
return the first value starting with "1" below Puck

Using Match() with a wildcard can locate the row with Puck.  So in C5, we enter:
<code>=MATCH("*Puck",A1:A9999,0)
</code>
then we use Match() again to find the row below that that starts with "1".  So in C6 we enter::
<code>=INDEX(A1:A9999,MATCH("1*",INDIRECT("A" & C5 & ":A9999"),0)+C5-1)
</code>

Naturally this 2-cell approach can always be combined into one cell.
Comment: Thanks alot Gary for your input, it is much appreciated! I choose the solution provided by Tom Sharpe, but I still have an unsolved solution. It's posted under his solution, do you maybe have an idea on how to do this?


unique_ptr arguments. error C2664

Question: I recently just heard of the new unique_ptr in C++11 and wanted to try it.
I changed this code :
void CreateDummySpell(uint32 id)
{
    const char * name = "Dummy Trigger";
    SpellEntry * sp = new SpellEntry;
    memset(sp, 0, sizeof(SpellEntry));
    sp->Id = id;
    sp->Attributes = 384;
    sp->AttributesEx = 268435456;
    sp->AttributesExB = 4;
    sp->CastingTimeIndex=1;
    sp->procChance=75;
    sp->rangeIndex=13;
    sp->EquippedItemClass=uint32(-1);
    sp->Effect[0]=3;
    sp->EffectImplicitTargetA[0]=25;
    sp->NameHash=crc32((const unsigned char*)name, (unsigned int)strlen(name));
    sp->dmg_multiplier[0]=1.0f;
    sp->StanceBarOrder=-1;
    dbcSpell.SetRow(id,sp);
    sWorld.dummyspells.push_back(sp);
}

to this
void CreateDummySpell(uint32 id)
{
    const char * name = "Dummy Trigger";
//  SpellEntry * sp = new SpellEntry;
    std::unique_ptr<SpellEntry> sp(new SpellEntry);
    memset(sp, 0, sizeof(SpellEntry));
    sp->Id = id;
    sp->Attributes = 384;
    sp->AttributesEx = 268435456;
    sp->AttributesExB = 4;
    sp->CastingTimeIndex=1;
    sp->procChance=75;
    sp->rangeIndex=13;
    sp->EquippedItemClass=uint32(-1);
    sp->Effect[0]=3;
    sp->EffectImplicitTargetA[0]=25;
    sp->NameHash=crc32((const unsigned char*)name, (unsigned int)strlen(name));
    sp->dmg_multiplier[0]=1.0f;
    sp->StanceBarOrder=-1;
    dbcSpell.SetRow(id,sp);
    sWorld.dummyspells.push_back(sp);
}

Now I'm getting this error :
error C2664: 'void *memset(void *,int,size_t)': cannot convert argument 1 from 'std::unique_ptr<SpellEntry,std::default_delete<_Ty>>' to 'void *'
2>          with
2>          [
2>              _Ty=SpellEntry
2>          ]
2>  ..\..\src\arcemu-world\SpellFixes.cpp(29): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
2>..\..\src\arcemu-world\SpellFixes.cpp(43): error C2664: 'void DBCStorage<SpellEntry>::SetRow(uint32,T *)': cannot convert argument 2 from 'std::unique_ptr<SpellEntry,std::default_delete<_Ty>>' to 'SpellEntry *'
2>          with
2>          [
2>              T=SpellEntry
2>          ]
2>          and
2>          [
2>              _Ty=SpellEntry
2>          ]
2>  ..\..\src\arcemu-world\SpellFixes.cpp(43): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
2>..\..\src\arcemu-world\SpellFixes.cpp(44): error C2664: 'void std::list<SpellEntry *,std::allocator<_Kty>>::push_back(const _Ty &)': cannot convert argument 1 from 'std::unique_ptr<SpellEntry,std::default_delete<_Ty>>' to 'SpellEntry *&&'
2>          with
2>          [
2>              _Kty=SpellEntry *
2>  ,            _Ty=SpellEntry *
2>          ]
2>          and
2>          [
2>              _Ty=SpellEntry
2>          ]
2>  ..\..\src\arcemu-world\SpellFixes.cpp(44): note: Reason: cannot convert from 'std::unique_ptr<SpellEntry,std::default_delete<_Ty>>' to 'SpellEntry *'
2>          with
2>          [
2>              _Ty=SpellEntry
2>          ]
2>  ..\..\src\arcemu-world\SpellFixes.cpp(44): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

It seems like I can pass sp as arguments. How do you pass sp as argument using unique_ptr smart pointers?
Thanks in advance.

too short message...
Comment: The other error is that `std::unique_ptr` is a move only type, when you call `push_back` in a list, the parameter would be copy. In you really want to storage `std::unique_ptr` in the container (not this case), you need to `std::move` the unique_ptr.
Answer: You should probably reconsider using memset (and just value-initialize it e.g new SomeClass() ) but in the general case if you want to pass the internal pointer of a unique_ptr (e.g to a legacy function) use its get function.
Comment: memset(sp.get, 0, sizeof(SpellEntry));
Like this?
Comment: @user3781185: `memset(sp.get(), 0, sizeof(SpellEntry));`
Comment: @dyp Oh sorry, good catch, I'll use the "it's late here" excuse :). Any other hiccups ?

unique_ptr arguments. error C2664


Jquery code performance on '.on' method

Question: Does the following code make any impact on application's performance?
$("body").on('click','#id',function () {
   //code to be executed
});

if so, could any one please explain why?
Comment: Yes - but an infinitesimal one. Probably single figure milliseconds. Instead of the event being trapped on the `#id` element directly you have to wait for the event to bubble up to the `body` element. Note that this difference is not caused by the use of `on()` directly, but because you're using a delegated event handler.
Comment: Thanks for your reply!,  so what would be the alternate for this in order to target future elements?
Comment: There isn't one - the code you have used is the best for this purpose.
Comment: Okey, in that case if i use the nearest parent's Id instead of 'body' would help the performance?
Comment: Yes, that would follow best practice
Comment: @RoryMcCrossan thanks for clearing me dude :)
Answer: Yes, but slight. The reason is that it would capture every click on the document's body, then evaluate whether that bubbled up from #id, and exit if it is not. It is a good policy to attach the handler to the most tightly defined element that will contain all of your events, as you rarely need to go as wide as body - for example, $("#stuffgoeshere").on('click','#id',function...). And if you actually know the ID of the element and that element exists, it would be even better to attach the handler directly to the element, using $('#id').on('click', function...).
Comment: thanks for the answer,  if my understanding is right, i can use the most nearest 'container's' id instead of 'body', right?

Jquery code performance on '.on' method


Is the concept of a mobile site becoming irrelevant?

Question: Mobile sites were originally conceived for very limited devices with extremely throttled download speeds. They are usually* hideous affairs with barely-functional drop-down lists, that leave out any branding or style that may be present on the main site. Most of the time there is absolutely no useful information on the front page, meaning that a user has to click-through before there is any arresting content.
Nowadays, there is very little gap between the net speeds of desktop and mobile devices. The only reason I can see to produce a mobile version of the site is to compensate for the smaller screens, and even then, that issue can be mostly avoided by good, clean, reflowable, uncluttered site design.
For myself, I always view mobile versions of a site as a nuisance, and click through to the desktop version as soon as possible.
With that said, are there any outstanding reasons to produce a mobile version of a site that is substantially different than the desktop version?

*I know better than to make universal statements, but this seems to be the rule, not the exception.
Comment: "Nowadays, there is very little gap between the net speeds of desktop and mobile devices."  In terms of device hardware performance, perhaps.  However one of the major factors to take into a mobile site from an implementation standpoint is the bandwidth limitations inherent with mobile networks.  Downloading large image assets or other unnecessary files to the mobile device will decrease responsiveness, which will hurt the user experience.
Comment: Welcome to the ux stack exchange!
Answer: The standard today is to have one website that responds to the device it is being viewed on. The experience should be tailored for that device. For example, a website being viewed on mobile might respond to use a fly-out side menu, instead of a drop down horizontal menu in the header.
Also, mobile sites should have everything the desktop version of the site has. Responsive does not mean taking things away.
Doing the old "m.whatever.com" is not really being done anymore.
Comment: I agree that responsiveness is important, but I must sadly disagree with your last statement. m.whatever.com with design from the early noughts is all too common still with smaller companies.
Comment: @EmmettR. - I haven't seen the m. in a while and I know many companies (including mine) that are doing away with it. If they are still out there, then you are right - that is sad.
Answer:
With that said, are there any outstanding reasons to produce a mobile version of a site that is substantially different than the desktop version?

Antiquated corporate product management and development processes and out-of-date developer skills and/or technology infrastructure.
In many (most?) cases that's what it boils down to. Why do we have two versions of our site? Because we've always had two versions of our site. Why don't we make one responsive site? Because there is no budget/demand to redo our site. Etc.
Answer: Mobile devices have very different UX requirements to desktop/laptop computers. Here are a couple of examples from the top of my head:

Touch interfaces need a few-mm gap between links to avoid the fat-finger problem
Touch interfaces have no "hover" state
Phone interfaces are designed to be read top to bottom
If you have multiple layers of menu on a phone interface, they fill the entire above-the-fold viewport, and you can't tell what page you're on.
Large dropdown navigation menus are common and useful affordance on desktop interfaces, these are physically impossible to replicate in 320 horizontal pixels.

For these, and several dozen other, reasons it's usually a good idea to have different  ways of showing a page on desktop and mobile devices.
Comment: You make good points about interface design, but it seems like most garden variety mobile sites are designed with only data usage in mind. For example, those drop-down lists tend to be extremely narrow and easy to mis-click.
Comment: I'll admit that many mobile sites are poorly designed, but that doesn't mean that we should just force everybody to use desktop sites on mobile, even when that offers poor ux. It means we should design mobile sites that work.
Comment: I don't agree with all the bullets (for example, for accessibility you need space between links on desktop as well) and issues such as the mega-menus can still be selectively shown via one site with some responsive logic put into the mix. I don't think the bullets add up to justification that you always need separate sites.
Comment: @DA01 I wasn't suggesting that you need separate sites, I'm all for responsive design, I'm just saying that you need separate presentation on different devices.
Comment: Ah! That makes sense. I agree.
Answer: From my perspective there are two things to consider here:

What does the user expect of a website viewed on a mobile device in terms of what he wants to achieve there
What does the user epect of a website viewed on a mobile device in terms of performance

With regard to 1 I would say you are right, generally one can assume that the goals a user wants to achieve when viewing a site on mobile do not really differ from when viewing the page on a desktop / Laptop or other device.
However, the tolerance for performance and loading times of "mobile" users is actually quite low, as users are used to using native apps on these devices that offer a very fluid experience. This is where adaptive design is very strong, i.e. serving different assets and a structurally different html to mobile users.
Why? Becauses while mobile networks are becoming increasingly powerful in terms of raw throughput, signal run times are still a lot higher than on other broadband connections, thus optimizing an adaptive site for less http-requests for mobile users can increase performance a lot. Combine this with a lower patience of mobile users and you got yourself a pretty good reason of optimizing your responsive / fluid design for mobile.
I recommend this article on serverside optimized responsive design for further information:
http://mobile.smashingmagazine.com/2013/04/09/improve-mobile-support-with-server-side-enhanced-responsive-design/
Comment: Absolutely, that same impatience is why the old model of mobile site is so harmful. It is true that among the very best mobile sites, backed by major corporations, designs for mobile sites are full-featured and well optimized. However, most blogging services, small companies, and personal sites are still stagnated a decade in the past, with that harmful gateway list, and bland, content-free presentation. What I suppose I'm asking is why there isn't a new paradigm for the casual web-user? Is there another basic format for the non-savvy that is less than actively harmful?


Javascript crossdomain widget

Question: I want to create javascript widget similar to linkedin Member profile. https://developer.linkedin.com/plugins/member-profile-plugin?button-type-inline=true
On my site the user can manage some data.
I want to allow for user to copy some HTML code and insert in his site HTML to display the data.
I want HTML code looks like:
<code><script src="http://mysite.com/code.js?userid=123"></script>
</code>
And if user inserts this code in his site then javascript code is loaded and data are displayed (widget displayed)
How to do this? I know about crossdomain restrictions. But in case of linkedin this is not the problem. Their widget works fine.
Thanks.
UPDATE.
As i understand from comments, it is not the problem to display any data in page that includes my javascript file. I am going to do tests.
Comment: Just code it ***! But seriously, if a user embeds your script, it works, if you want the script to load external data, use JSONP. That's all.
Answer: Either the data is embedded inside the script, or it is loaded via JSON-P

Javascript crossdomain widget


Query - select multiple rows based on condition

Question: I'm a bloody beginner (working with Access). Suppose that I have two tables with data:

list of students
list of extracurricular activities

I have a third table that links these two tables as shown below:

I want to construct a query that gives me the list of all students that are participating in the same activity as a selected student.
E.g. if I choose Mike, I want to have four rows:

Mike - Basketball - 2016
Lisa - Basketball - 2021
Mike - Football - 2018
John - Football - 2020

sample data

students

studentFirstName
studentLastName

John
Mayers

Lisa
O'Reilly

Mike
Thompson

activities

activityName

Basketball

Chess

Football

linking table

studentFirstName
studentLastName
activityStartYear

John
Chess
2017

John
Football
2020

Lisa
Basketball
2021

Lisa
Chess
2019

Mike
Basketball
2016

Mike
Football
2018

desired result
a) Input: John
Output: all students that share a common activity with John

studentFirstName
studentLastName
activityStartYear

John
Chess
2017

John
Football
2020

Lisa
Chess
2019

Mike
Football
2018

b) Input: Lisa
Output: all students that share a common activity with Lisa

studentFirstName
studentLastName
activityStartYear

John
Chess
2017

Lisa
Basketball
2021

Lisa
Chess
2019

Mike
Basketball
2016

Is there any way to do this?
Comment: Do you wanna know it from a SQL perspective?
Comment: Please include a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) with sample data and desired results.
Answer: what about:
SELECT /*b.studentFirst, */
     a.studentFirstName,
     a.activity,
     a.year
FROM third_table a
JOIN student_table b
ON a.activity = b.activity
/* AND a.year = b.year -- if needed */
WHERE b.studentFirstName IN ('Mike'...)

notes:

/* */ parts kind of depends on what you really want to do
as you see activity table is not needed but you could add a join
to ensure it exists  JOIN activities c ON a.activity = c.activity
but this is only needed if you need to check the existence
of the activity
Comment: Some suggestions to improve your answer: As indicated in the output example, the author does not want to match year, so the `-- if needed` part will make it more confusing. Avoid `a.*` and list the fields for good practices. Move the `FROM` clause to a separate line for readability.
Comment: Thanks mate, your proposed solution works perfectly! (:
Answer: Something like this would work:
SELECT
   name
   ,activity
   ,year
FROM linkingtable
WHERE activity IN (SELECT activity FROM linkingtable WHERE name = 'Mike')

It will return all the activities from the linkingtable based on Mike.
SQL Fiddle


How to change the value of a XML tag using Perl

Question: Let us assume that my XML file is like:
<code><? xml version="1.0" encoding="iso-8859-1" ?>
  <Body>
    <RequiredTag>
      #VALUE#
    </RequiredTag>
  </Body>
</code>
How can I change the value of the required tag using Perl?
E.g.:
<code>$XmlHandle->{XML}->{Body}->{RequiredTag} = "RequiredValue";
</code>
Answer: With XML::Twig::
<code>#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new( twig_handlers =>
                  { RequiredTag => sub { $_->set_text( 'RequiredValue') } },
                pretty_print => 'indented',
              )
         ->parsefile( 'my_file.xml')
         ->print;
</code>
Comment: Have a look at the doc ;--) You can use a more complex expression in the handler trigger, like `Body/RequiredTag`, or `/XML/Body/RequiredTag`; and instead of `print`, you can use `print_to_file( 'updated.xml')`
Comment: 1.  Incase we have more than one "RequiredTag" which is nested under different parent tags.  How can we differentiate ?
2.  And, how to save the xml file after the modification ?
Comment: print_to_file(FILE) will save the document once i close my Tkx application. Can we save the file dynamically and reload as my Tkx application still running ?
Comment: I am not sure what you mean here. print_to_file writes the document to disk as soon as you call the method. If you need the XML for the document, use `sprint`, which returns the XML string for the entire doc.
Comment: I am using GUI application developed in GUI.  I pick a button so that it will write the value into the XML file.  But the modification will taken into effect if and only if i close the application and re-launch it.  With-Out closing the GUI application, the change is not reflected when i try to retrieve the value..  And when i check the documentation, In the doc, "print_to_file ($filename, %options)" %options are not described..
Comment: the docs say : `options: see "flush"`, and `flush` lists the only option as `pretty_print`, so that's not what you are looking for. Beyond that, I can't really help you, I don't know what your code does with the XML. I am pretty sure the file is written when you call `print_to_file` though, you could check that. If the file is used to configure the application itself, then it is possible that you need to restart it, or there may be a way to re-load the config from inside the code. I don't know.


How to stop some games blowing fuse

Question: I've been gaming for a while now. When playing certain games this PC goes into overdrive. The fan/fans start/s to sound like a jet engine it/they get/s so busy. Also I have smelt burning when this has happened. The fuse blew on the 4 socket adapter I was using recently.
On the following thread someone said this could be due to the PSU not being strong enough to handle the load, in what it seems could be a related issue someone had, although the person who posted this question did say that blowing a fan on their PC stopped it crashing in that case: http://www.tomshardware.co.uk/answers/id-2047543/gtx-650-overheating-issue.html.
This is exactly what they said:

Your GPU isn't overheating. 70+ before it would shutdown and cause a restart. Make sure your PSU is strong enough to handle your new system at load and possibly run Memtest to check your RAM (although not BSOD'ing and just shutting down points to the PSU).

This (the PSU part) makes more sense to me than it being to do with dust etc, since it seems a more plausible explanation of why the fuse blew.
The PC has no problems except when playing certain games: i.e. TERA Rising and WoW with add-ons (I think WoW is ok as long as I don't have more than 1 add-on (Healers Have To Die)). I'm just wondering if anyone knows or can suggest what I might be able to do to be able to play these games without this problem occurring.
The PC's spec is this:
Display: NVIDIA GeForce GTX 650
8GB RAM (6 available)
Processor: AMD FX (tm) - 8120 Eight-Core Processor - 3.1 GHz, 4 Cores, 8 Logical Processors
I have also asked this question on superuser.com. Here is a link to it:
https://superuser.com/questions/767113/gaming-blew-fuse-and-causes-funny-smell-how-to-overcome/768159?noredirect=1#comment996554_768159.
I clicked delete to remove the question here on gaming.stackexchange.com, but a message appeared which said that the deletion of questions which have answers is discouraged and leads to a question ban if it happens repeatedly, so I won't be deleting the question, as I don't want to do something that is discouraged or move closer to a question ban.
There has been quite some progress on the superuser post, although I don't feel ready to accept any of the answers at this stage.
Comment: This sounds more like a generic PC issue than anything really gaming-specific.  I'd recommend perhaps asking this on SuperUser.
Comment: Whats the wattage on your PSU?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/15060/discussion-between-george-tomlinson-and-eyeofthehawks).
Answer: I used to have issues only when playing WoW. All of the addons plus 25-man raiding really put a strain on the CPU, but it didn't used to. I saw that my CPU was really pushing its limit and multiple times I'd get a BSOD in the middle of raiding.
I used an application to check the temperature of the CPU and it was very high. Cleaning the dust out of my PC and re-seating the CPU with thermal paste got it running like new, again.
If your PC used to be able to handle WoW and has only been recently having issues, there's probably just a lot of dust buildup. I know it's easy to get caught up in the digital aspects of your PC, but don't forget about the physical aspects, like I did. It's an investment of maybe an hour to fully clean all of the dust out of your PC and re-seat your CPU.
Comment: Thanks for your answer. I opened the PC up yesterday and couldn't see much dust at all to be honest, although I didn't disconnect any of the components inside. I've posted this question on Superuser now and someone has said that I need a voltage stabilizer or UPS in their answer.
Comment: Ah, okay. When it comes to general "my computer is going slower" questions, it could be any number of things. I think it's very useful that this answer is out in the open as I had never seen it when troubleshooting my own issue. Be sure to update us on what fixes it for you!
Comment: You may need to look it up on Superuser, where I've posted the same question, as I'm being told this question is off-topic and needs to be moved.
Comment: Here's the question on superuser: http://superuser.com/questions/767113/gaming-blew-fuse-and-causes-funny-smell-how-to-overcome
Comment: Could you please let me know if you see the link to the question in my last comment, as I've been told to move this question to hardware, which I guess means deleting it, but I wanted to make you aware of where to find the question, as you expressed a desire to be kept posted on developments.
Comment: @GeorgeTomlinson I saw the link. Feel free to delete!
Comment: Thanks. I clicked delete, but got the message that it's not recommended that questions with answers be deleted as it can deprive users of knowledge or something similar and it can lead to a question ban, so I'll leave it.

How to stop some games blowing fuse


How to make gcc/g++ accept expressions like LOBYTE(v15) = someExpression?

Question: I have a decompiled function and want to compile its source. The problem is with LOBYTE statements:
get "error: lvalue required as left operand of assignment" on every line like that:
LOBYTE(v9) = ((_BYTE)v12 + (v7 ^ v13)) & 0x1F;

Tip a workaround, please.
Comment: How would we possibly know what `LOBYTE` is?
Comment: In particular, it reasonably could be the least significant bits of v9, or the byte with the lowest address. On big-endian systems, those are at opposite ends.
Answer: Assuming v9 is an object of an arithmetic type (the question does not explicit the declarations of the different identifiers / macros involved) and the system is little-endian:
#define LOBYTE(x)  (*(unsigned char *) &(x))

would allow LOBYTE on the left hand side of the = operator.
Answer: I don't think LOBYTE is some variable in which you can strore some value. It's a MACRO which returns a value itself. In effet you're writing something simmilar to [after preprocessing]
5 = 2 * 3
which is not possible. You'll need some writable memory on the LHS of the assignment = operator.
In your case, a possible implementation of LOBYTE is #define LOBYTE(x) ((unsigned char) ((x) & 0xff)), which is not a lvalue. That's why the error is there.

EDIT:
Regarding the "how to solve" part [sorry for missing in first answer], you need to provide the lvalue as an outcome of LOBYTE.
Just to add to ouah's answer, you can do do something like
#define LOBYTE(x)  (*(uint8_t *) &(x))

to produce the required lvalue .
Comment: @MattMcNabb Sorry sir, did not get your point. Can you please elaborate a bit?
Comment: to use a variable on the left of equal sign, you need it to be an lvalue
Comment: @LưuVĩnhPhúc Sir, thank you for explaining. However, I wanted to show the particular implementation of `LOBYTE` which might have caused the error in OP's case. In that case, am I correct?
Comment: that's not your initial wording. and don't call me sir
Comment: @LưuVĩnhPhúc As you wish !! As per the latest edit, my answer is correct, right?
Comment: the OP asked *how*, not *why*


add css class to jeditable input field

Question: How can i add a simple class tag to a jeditable input field? On the developer's website (http://www.appelsiini.net/projects/jeditable), under "How to style elements?", he says this can be done this way:
$('.editable').editable('http://www.example.com/save.php', {
    cssclass : 'someclass'
});

Unfortunately this will add the class to the form tag instead of the input.
Answer: I had the same question and did the following to style the 'input' element.
JAVASCRIPT
$('.editable').editable('http://www.example.com/save.php', {
    cssclass : 'someclass'
});

CSS
.someclass input {
    width: 100%;
    ...
}

add css class to jeditable input field


Localization doesn't work using "Bundle Assemblies into Native Code" in release mode

Question: I followed the documentation and using resx files with displaying correct language, with DI on Android, I am able to change language within my app.
Basically in Android, I added platform specific code as described in the article
<code>`[assembly:Dependency(typeof(UsingResxLocalization.Android.Localize))]

namespace UsingResxLocalization.Android
{
    public class Localize : UsingResxLocalization.ILocalize
    {
        public void SetLocale(CultureInfo ci)
        {
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
        }
        public CultureInfo GetCurrentCultureInfo()
        {
            var netLanguage = "en";
            var androidLocale = Java.Util.Locale.Default;
            netLanguage = AndroidToDotnetLanguage(androidLocale.ToString().Replace("_", "-"));
            // this gets called a lot - try/catch can be expensive so consider caching or something
            System.Globalization.CultureInfo ci = null;
            try
            {
                ci = new System.Globalization.CultureInfo(netLanguage);
            }
            catch (CultureNotFoundException e1)
            {
                // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
                // fallback to first characters, in this case "en"
                try
                {
                    var fallback = ToDotnetFallbackLanguage(new PlatformCulture(netLanguage));
                    ci = new System.Globalization.CultureInfo(fallback);
                }
                catch (CultureNotFoundException e2)
                {
                    // iOS language not valid .NET culture, falling back to English
                    ci = new System.Globalization.CultureInfo("en");
                }
            }
            return ci;
        }
        string AndroidToDotnetLanguage(string androidLanguage)
        {
            var netLanguage = androidLanguage;
            //certain languages need to be converted to CultureInfo equivalent
            switch (androidLanguage)
            {
                case "ms-BN":   // "Malaysian (Brunei)" not supported .NET culture
                case "ms-MY":   // "Malaysian (Malaysia)" not supported .NET culture
                case "ms-SG":   // "Malaysian (Singapore)" not supported .NET culture
                    netLanguage = "ms"; // closest supported
                    break;
                case "in-ID":  // "Indonesian (Indonesia)" has different code in  .NET
                    netLanguage = "id-ID"; // correct code for .NET
                    break;
                case "gsw-CH":  // "Schwiizertüütsch (Swiss German)" not supported .NET culture
                    netLanguage = "de-CH"; // closest supported
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }
            return netLanguage;
        }
        string ToDotnetFallbackLanguage(PlatformCulture platCulture)
        {
            var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually);
            switch (platCulture.LanguageCode)
            {
                case "gsw":
                    netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }
            return netLanguage;
        }
    }
}`
</code>
In PCL code I have
<code>namespace myApp.Resx
{

    /// <summary>
    /// Implementations of this interface MUST convert iOS and Android
    /// platform-specific locales to a value supported in .NET because
    /// ONLY valid .NET cultures can have their RESX resources loaded and used.
    /// </summary>
    /// <remarks>
    /// Lists of valid .NET cultures can be found here:
    ///   http://www.localeplanet.com/dotnet/
    ///   http://www.csharp-examples.net/culture-names/
    /// You should always test all the locales implemented in your application.
    /// </remarks>
    public interface ILocalize
    {
        /// <summary>
        /// This method must evaluate platform-specific locale settings
        /// and convert them (when necessary) to a valid .NET locale.
        /// </summary>
        CultureInfo GetCurrentCultureInfo();

        /// <summary>
        /// CurrentCulture and CurrentUICulture must be set in the platform project,
        /// because the Thread object can't be accessed in a PCL.
        /// </summary>
        void SetLocale(CultureInfo ci);
    }

    /// <summary>
    /// Helper class for splitting locales like
    ///   iOS: ms_MY, gsw_CH
    ///   Android: in-ID
    /// into parts so we can create a .NET culture (or fallback culture)
    /// </summary>
    public class PlatformCulture
    {
        public PlatformCulture(string platformCultureString)
        {
            if (String.IsNullOrEmpty(platformCultureString))
                throw new ArgumentException("Expected culture identifier", "platformCultureString"); // in C# 6 use nameof(platformCultureString)

            PlatformString = platformCultureString.Replace("_", "-"); // .NET expects dash, not underscore
            var dashIndex = PlatformString.IndexOf("-", StringComparison.Ordinal);
            if (dashIndex > 0)
            {
                var parts = PlatformString.Split('-');
                LanguageCode = parts[0];
                LocaleCode = parts[1];
            }
            else
            {
                LanguageCode = PlatformString;
                LocaleCode = "";
            }
        }
        public string PlatformString { get; private set; }
        public string LanguageCode { get; private set; }
        public string LocaleCode { get; private set; }
        public override string ToString()
        {
            return PlatformString;
        }
    }
}
</code>
then in my PCL code, I am able to overwrite the culture with the code below
<code>  string name = Helpers.Settings.PreferredLanguage == "en" ? "en-US" : Helpers.Settings.PreferredLanguage + "-" + Helpers.Settings.PreferredLanguage.ToUpper();
                        currentCultureInfo = new System.Globalization.CultureInfo(name);
                        Xamarin.Forms.DependencyService.Get<Resx.ILocalize>().SetLocale(currentCultureInfo);

                Resx.AppRes.Culture = currentCultureInfo;
</code>
This Code implementation works fine when I run in Debug and Release Mode.
But It fails working in Release Mode using "Bundle Assemblies into Native Code".
If I remove the check for this option, It works fine.
What could be the possible problem? I dont know how to track this down. I tried using Android Device Monitor but it doesnt display much for it.
configuration looks like as above.
EDIT: when I enable, "Enable developer instrumentation" in Release mode, It works also.
Answer: Obviously there is already an existing bug for this issue on the link. Until bug is fixed by xamarin, workaround is as suggested on the link. add a line for each language in OnCreate function of MainActivity
<code>  System.Reflection.Assembly.LoadFile("de-DE\\AppName.resources.dll");
</code>


C++ syntax help, using templates

Question: It is probably some stupid syntax mistake, i have the following class written in h file
#include "IGenticSolverHelper.h"
template <class T>
class GenericGeneticSolver
{
public:
    GenericGeneticSolver(IGenticSolverHelper<T>& helper, int generationSize) : mSolverHelper(helper)
    {
        mSolverHelper.GenerateFirstGeneration(0, generationSize, currentGeneration);
    }
private :
    vector<T> currentGeneration;
    IGenticSolverHelper<T>& mSolverHelper;
};

And then the following code :
#include "IGenticSolverHelper.h"
#include "GenericGeneticSolver.h"

class HelperImpl : IGenticSolverHelper<int>
{
public:
    void GenerateFirstGeneration(const int seed,const int generationSize, vector<int>& firstGeneration)
    {
    }
    void Crossover(const int& father,const int& mother, int& son)
    {
    }
    void Mutate(const int& orignal, int& mutated)
    {
    }
    float Cost(int& solution)
    {
    }
};

int main()
{
    int a =5;
    GenericGeneticSolver<int> mySolver(HelperImpl,a);
}

And i get the following error when i compile :
error C2061: syntax error : identifier 'a'

if i will change the line to :
GenericGeneticSolver<int> mySolver(HelperImpl);

it will compile, though the constructor expect 2 arguments, and will get the following warning :
warning C4930: 'GenericGeneticSolver<T> mySolver(HelperImpl)': prototyped function not called (was a variable definition intended?)

And to add to the oddness, when i put a break point on this line, he won't stop there.
What am i doing wrong, i just trying to create an instance of GenericGeneticSolver
Answer: Take a look at this line:
GenericGeneticSolver<int> mySolver(HelperImpl,a);

The compiler is confused about what you're trying to do here because HelperImpl is the name of a type, while a is the name of an object. The compiler thinks what you're doing is trying to prototype a function named mySolver that takes in a parameter of type HelperImpl and a parameter of type a, but then gets stuck because it doesn't know of any types named a.
If you remove a, you get this:
GenericGeneticSolver<int> mySolver(HelperImpl);

This is a perfectly legal prototype of a function called mySolver that takes an argument of type HelperImpl and returns a GenericGeneticSolver<int>. The warning you're getting is the compiler telling you that you might not have meant to make this a prototype, since it somewhat looks like an instantiation of a variable named mySolver but isn't.
Since I assume that you're trying to instantiate an object of type GenericGeneticSolver<int> here, you probably want to instantiate a HelperImpl and then pass that object into the constructor, like this:
HelperImpl hi;
GenericGeneticSolver<int> mySolver(hi, a);

Hope this helps!
Comment: Thanks, i didn't noticed that i pass a type and not an instance !
Comment: We call them _declarations_ in C++, not "prototypes". GCC's C++ front-end is senile in this regard.

C++ syntax help, using templates


File Size Increased in Server (HDFS) when uploaded from jmeter

Question: I am trying to upload file in HDFS (server) from jmeter. As I see, file is uploaded in HDFS successfully but the file size is slightly increased. Thus, making file corrupt. And file doesn't work as expected.
The same file I uploaded using Postman and it works fine. There is no change in file size in HDFS and the file works as expected.
here is the requested body in jmeter which shows success message and file is in server
 POST http://myurl/../..

POST data:
--HTKJ_hgyyM7QVWQfJBS5X-WQX0zkMO5fqmlY
Content-Disposition: form-data; name="file1.pak"; filename="file1.pak"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary

<actual file content, not shown here>
--HTKJ_hgyyM7QVWQfJBS5X-WQX0zkMO5fqmlY--

[no cookies]

Request Headers:
Connection: close
file_name: jmeter13.pak
Content-Type: application/octet-stream
Content-Length: 11563
Host: 10.45.3.64:8080
User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_111)

Answer: In the body of your POST request, Jmeter is wrapping the following headers within the boundary to the actual file content before sending to the server.

POST data:
  --HTKJ_hgyyM7QVWQfJBS5X-WQX0zkMO5fqmlY
  Content-Disposition: form-data; name="file1.pak"; filename="file1.pak"
  Content-Type: application/octet-stream
  Content-Transfer-Encoding: binary

  --HTKJ_hgyyM7QVWQfJBS5X-WQX0zkMO5fqmlY--

In case you want to send the actual file within the body, try removing the "Parameter Name" in the "Files Upload" box of the HTTP request as stated in http://jmeter.apache.org/usermanual/component_reference.html#HTTP_Request
File Path:
Name of the file to send. If left blank, JMeter does not send a file, if filled in, JMeter automatically sends the request as a multipart form request.
If it is a POST or PUT or PATCH request and there is a single file whose 'Parameter name' attribute (below) is omitted, then the file is sent as the entire body of the request, i.e. no wrappers are added. This allows arbitrary bodies to be sent. This functionality is present for POST requests, and also for PUT requests.See below for some further information on parameter handling.
This worked for me, please try it out.
Answer: The most possible reason is Postman and JMeter being configured differently. Add View Results Tree listener and carefully inspect JMeter request paying attention to literally everything, especially to the "Request Headers"as they matter. See How to Debug your Apache JMeter Script guide for comprehensive information on JMeter tests troubleshooting.
If you won't be able to figure out the differences using View Results Tree listener you can capture requests from JMeter and Postman using a "lower level" network sniffer tool like Wireshark  which is the most advanced network traffic analyzer, you will be able to detect a single byte inconsistency with it.
If above tips won't help please update your question with Postman and JMeter configurations and maybe Wireshark .pcap trace for both the requests so I or other community members  could take a look and suggest the appropriate changes.
Comment: I added view result tree and didn't found any error in. (file uploaded successfully). I don't know how to use wireshark. The file uploaded successfully from both jmeter and postman but there is a slight different in file size when uploaded form jmeter
Comment: Hello, Dmitri T, here is the link [jmeter_uploadfile](https://www.dropbox.com/s/h85hv6lqtoho05r/jmeter_fileupload.pcap?dl=0)
 to the .pcap file. Please view it and let me know.
[jmeter_uploadfile](https://www.dropbox.com/s/h85hv6lqtoho05r/jmeter_fileupload.pcap?dl=0)
Thank you.


Could non pivot columns form the basis for the column space of a matrix?

Question: Since the pivot columns of a matrix are always linearly independent and span the columns of the matrix, they usually make up the basis of the matrix. However, this had me wondering about the non pivot columns of the matrix. According to column correspondence theory, the non pivot columns are linear combinations of the pivot columns. Does this mean that the non pivot columns could also be a generating set of the columns like how the pivot columns are a generating set of the columns? Then, if the non pivot columns were proven to be linearly independent by finding the reduced row echelon form or by some other means and the number of non pivot columns was equal to the number of pivot columns (therefore, the dimension wouldn't be a problem), could the non pivot columns make up a basis for the column space of a matrix?
Comment: @Bye_World: I suggest that you answer in the answer box and not in the comments.
Comment: @Bye_World Why did you delete your comment? I thought it was a good answer :(
Answer: Yes, it is perfectly possible. When you perform row reduction, you are set to make the first columns the pivot columns. But the column space does not depend on the order of the columns. Nothing prevents you from doing "row reduction" by working on the last column first.
Comment: So is it fair to say that we usually use the pivot columns to find a basis for the column space because we know they're linearly independent, yet non pivot columns can also be generating a set for the column space?
Comment: Yes, that's one way to see it.


Bootstrap - Two Nav bars not collapsing properly

Question: Hello Bootstrap Users
I was wondering whether you could help me. Please look at screen-shot

of my two nav bars (sample taken from Bootstrap website) unfortunately when I I add some extra items to the menu the menu will not collapse as it should (See link above) This issue affects all devices / browsers.
Does anyone know what the problem might be ??
See my code below (sorry for the formatting)

        Toggle navigation

      FRIENDLY_NAME

         Home

           General

            Group 2
             Link 1
 Link2
 Link3

            Group 2
 Link 4
 Link 5
 Link 6

             Group 3
 Link 7

           Group 4

            Link 8 42

            Link 9 220

 Link 10

 Help

     Settings

 Notification

 Members

 New User
';

     Administrator

 Profile
';

 Change Password
';

 Log Out
';

Kind Regards;
pi4r0n
Comment: You've got few PHP echoes inside of HTML. Mind if you post entire code? (you could use Pastebin, or any similar service to do that).That might be causing the issues
Comment: @Nikola sorry I forgot to remove echos ;) but this isn't a problem. I have took this example from Bootstrap website and from what I can see this issue is there as well so it might be a framework issue which i can not solve :(
Answer:

 Bootstrap 3

 General

link

link

link

link

link

 Orders

link

link

link

link

link

Time Table

Customize

 Settings

link

link

link

link

link

 Administrator

link

link

link

link

link

Twitter Bootstrap 3.0

DEMO Here
Comment: unfortunately your example got same issue as my. Look at you demo and try to resize the width of the UI slowly. See  http://s14.postimg.org/b9n6f9clt/Still_The_Same.jpg@Wilf
Comment: Oh, I get the point now. Well, try to implement something like this:
http://jsfiddle.net/ajkochanowicz/wkqQU/
Comment: @Nokola the above solution isn't really mobile / tablet friendly :(
Answer: We explicitly cover this in the navbar docs...

Overflowing content
Since Bootstrap doesn't know how much space the content in your navbar needs, you might run into issues with content wrapping into a second row. To resolve this, you can:

Reduce the amount or width of navbar items.
Hide certain navbar items at certain screen sizes using responsive utility classes.
Change the point at which your navbar switches between collapsed and horizontal mode. Customize the @grid-float-breakpoint variable or add your own media query.


how to repair garage concrete threshold

Question:
I have a really badly cracked concrete floor at the garage's threshold, looks like the previous owner just slapped concrete on threshold, and it has broken in pieces. What is the right way to fix it?
Also, most of the time I see that garage floor kind of naturally propagates beyond the threshold, up to 20cm or so, and I don't see it in my case. Does it mean the floor is not correctly poured?
Thanks.
Comment: That job looks like a wheelbarrow job , mixed in a wheelbarrow and poured it was not floated or the shading in the photo looks that way to me.  To do it right I would say it needs to be removed. It looks like there is gravel under the concrete I use welded wire in small areas like that For strength and a good mIx. If you are not putting anything heavy on this no footing is needed. A good mix with some metal should be more than enough for foot traffic.
Comment: Yes most home stores carry welded wire as a reenforcement for concrete.
Comment: naturally propogates?  sometimes the entrance area slopes down towards the door but that's just to prevent rainwater from flowing in.
Comment: @Jasen, what I meant to say is that in other places I saw a concrete slab goes all the way beyond the threshold, while in my case it stops right where the door closes. It looks like this was build wrong way?
Comment: I don't think this is a simple fix or patch job, I'd say it needs cut out and repoured.
Comment: @EdBeal, thanks for feedback. Is there a pre-welded wire that can be used, or I'll need to weld it? Generally, you're talking about some kind of wire grid that is put on the surface and concrete is poured over it?
Answer: There should be a reinforced foundation beam (footing) under the threshold and reinforcing mesh inside the floor slab, I'm guessing that you are missing both.
fix?  It looks like a do-over to me.
Comment: Footings are not needed for slabs but I would agree on a do over.

how to repair garage concrete threshold


If the only self adjoint operators from $\mathcal H$ to $\mathcal H$ are $0$, what comment we can make on $\mathcal H$?

Question: If $\mathcal H$ is a Hilbert space over $\mathbb C $ or $\mathbb R$.
The only self adjoint operators from $\mathcal H$ to $\mathcal H$ are $0$ and $I$. --------------------------------(1)

Then can we say that $\mathcal H$ is a one-dimensional space?

What other comments we can make on (1).
Comment: @Crostul: In case $\mathcal{H} = \{0\}$, you have $\lambda \, I = 0$ for all $\lambda$, so this is possible.
Comment: Is this even possible? All operators of the form $\lambda I$ (where $\lambda$ is a real number) are self adjoint.
Answer: The operator $2 \, I$ is always self-adjoint. Hence, $2 \, I = I$ or $2 \, I = 0$. This yields $I = 0$, hence, $\mathcal{H} = \{0\}$.
Edit: Since every orthogonal projection onto a subspace is self-adjoint, it is quite easy to reconstruct $\mathcal{H}$ from its self-adjoint operators.


can't resolve error \x93 when call my print function

Question: I'm reposting the question because unsolved or inefficiently answered, filled with some missing info.
After several iteration in loop of my print function without problem, I face to this error I can't figure out: UnicodeEncodeError: 'charmap' codec can't encode character '\x93' in position 0: character maps to <undefined>, but. you'll see better on traceback down below.
j is a string ( a flag I use for my ref. into the file.. You can take any..); h take value of gh when passed the function prt_tit_gen. dir_conf+ct are strings respectively a dir and a name file where to print in..
For what I can understand (because appear on spyder debuger ), the text code is utf-8.
The routine is (gh is the "exploded" format for debugging purpose) :
   gh = j+' -> '+str(' '.join(e))+"\n"
   prt_tit_gen(dir_conf+ct , gh , 'a')

where
def prt_tit_gen(d,h,m):
    file1 = open(d, m)
    file1.writelines(h)
    file1.close()

and
e = [
'zip:GY1 1WW',
'sector:Financial Services',
'longBusinessSummary:Eurocastle Investment Limited is a publicly traded closed-ended investment company that focuses on investing in performing and nonperforming loans and other real estate related assets primarily in Italy. The Company is Euro denominated and is listed on Euronext Amsterdam under the symbol "ECT". Eurocastle is managed by an affiliate of Fortress Investment Group LLC, a leading global investment manager. For more information regarding Eurocastle Investment Limited and to be added to our email distribution list, please visit www.eurocastleinv.com.',
'city:Saint Peter Port',
'country:Guernsey',
'regularMarketPrice:8.3',
'preMarketPrice:None',
'logo_url:https://logo.clearbit.com/eurocastleinv.com'
]

Traceback (most recent call last):
File "D:\Documenti\Develope\Python\AI\Previsone Titoli\getTiker Sector.py", line 89, in <module>
    prt_tit_gen(dir_conf+ct, j+' -> '+str(' '.join(e))+"\n", 'a')
  File "D:\Documenti\Develope\Python\AI\Previsone Titoli\getTiker Sector.py", line 45, in prt_tit_gen
    file1.writelines(h)
  File "C:\Program Files\Linguaggi\Python397\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x93' in position 0: character maps to <undefined>

Answer: Open the file with a specified encoding like this
file1 = open(d, m, encoding="utf-8")

Comment: refined Traceback due to lack of size post.. :
    File "D:\Documenti\Develope\Python\AI\Previsone Titoli\getTiker Sector.py", line 36, in readFileOut
    data = my_file.read()
  File "C:\Program Files\Linguaggi\Python397\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 1468: invalid start byte
Comment: Sorry raizo, I wrong the open to place your amendment.. now seams its works... need to check better. For now, thanks !!


Why is my dryer taking longer to dry clothes?

Question: I know nothing of dryers... but my dryer is taking longer and longer to dry clothes.  I've heard this is very common among dryers and I was wondering what it might mean.  Is there a specific part I should take a look at?
I've heard the lint-catcher thing might need to be washed with soap and water, so I've done that with no affect.
Answer: This usually happens because the dryer vent is getting clogged with lint (the lint-catcher isn't 100% effective, so some does escape).  You should clean it out regularly because a clogged vent can cause fires.  If the vent is short enough, you may be able to use a vacuum cleaner to clear it; otherwise use a dryer vent brush (can also be called a dryer duct brush) to reach the places the vacuum can't:
Comment: Hrmm... I thought I've checked that before... perhaps I should recheck it.
Answer: If you have a gas dryer and can see the flame that heats the dryer, then watch the flame.  When it clicks on the flame should point straight down the vent that goes up and into the drum.  This is how it should work when everything is clean.
If the flame burns like a candle, like the flame goes straight up an not follow the vent, then there is not proper air in the dryer.  This causes the dryer to heat up to quickly and cuts the heating cycle by reaching the thermostats cut-off temperature too quickly.
I'm not sure how you can tell on an electric dryer.
If you are any bit handy look up on the internet how to take the front off your dryer.  Then unplug the dryer and slide it out enough to get behind it and take the vent hose off.  Slide the dryer out and take the front off while it is unplugged and vacuum the inside out really good, paying attention to the motor and getting it clean. Get a brush like Niall C suggests and clean out the vent in the wall.  Hopefully your vent is less than the maximum length 25 ft (in the wall), taking footage off for 45's and 90's.  Too long a vent will cause your problem too.
If you have a plastic or vinyl hose that attaches between the wall and your dryer then replace it with Mylar, foil or aluminum.  When you put the dryer back make sure the hose is not crinkled or crimped anyplace.  A crimped hose will causes it to act like a dirty vent.
I was a Maytag repairman many years ago, luckily it was commercial only.
Answer:
Check the vent on the outside for bird nests.
Check for a bunch of lint caught up in the vent near the dryer.
Make sure there is not water in the vent hose. Sometimes condensation settles in the vent hose (if there's a dip in it) and cuts down on the airflow.
Answer: For my gas dryer, the solenoids seem to die most often.  The symptom is low heat and a long drying time.


SQL error:Incorrect syntax near ',' using select in insert

Question: I'm trying to execute this SQL query:
INSERT INTO ItemAssignments(EmployeeId, ItemId, ModifiedOn)
    (SELECT Id FROM Employees WHERE Acronym ='ardsd',2,'2019-07-10 09:03:55.830'),
    (SELECT Id FROM Employees WHERE Acronym ='bsadf',2,'2019-07-10 09:03:55.830'),
    (SELECT Id FROM Employees WHERE Acronym ='casde',3,'2019-07-10 09:03:55.830'),
    (SELECT Id FROM Employees WHERE Acronym ='dasas',3,'2019-07-10 09:03:55.830');

Error between SELECT expression and next parameter.
I've tried to write SELECT into brackets - but that didn't help.
Please tell me what can I do in this case?
Answer: Use one SELECT with a UNION as the source:
INSERT INTO ItemAssignments(EmployeeId,ItemId,ModifiedOn)
SELECT id, 2, '2019-07-10 09:03:55.830'
FROM Employees
WHERE Acronym in ('ardsd', 'bsadf')

UNION ALL

SELECT id, 3, '2019-07-10 09:03:55.830'
FROM Employees
WHERE Acronym in ('casde', 'dasas');

Answer: You seem to want logic like this:
INSERT INTO ItemAssignments(EmployeeId, ItemId, ModifiedOn)
    SELECT Id,
           (CASE WHEN Acronym in ('ardsd', 'bsadf') THEN 2
                 ELSE 3
            END),
           '2019-07-10 09:03:55.830'
    FROM Employees
    WHERE Acronym in ('ardsd', 'bsadf', 'casde', 'dasas')


What sort of applications are there for $(dy/dx) (dx/dy) = 1$?

Question: A calculus exercise that I just did concludes that $$\frac{dy}{dx} \frac{dx}{dy} = 1.$$  The exercise remarks that this is true in general. In what sort of situation can I use this?  Can you show an exercise where I can take advantage of a result like that?  (A typical exercise or practical application would be great.)
Comment: It is the key to the Inverse Function Theorem, which lets you find the derivative of $f^{-1}(x)$ in terms of the derivative of $f$ and the value of $f^{-1}$.
Answer: It helps find the derivatives of inverse functions.
Example: Find the derivative of $y = \arcsin(x)$ ($x \in [-1,1]$, $y \in [-\frac{\pi}{2}, \frac{\pi}{2}]$), knowing that $\frac{d}{dx} \sin(x) = \cos(x)$.
By the definition of an inverse function:
$$\sin(y) = x$$
Differentiating wrt $y$ gives:
$$\cos(y) = \frac{dx}{dy}$$
Taking the reciprocal (which your question acknowledges that you can do) gives:
$$\frac{dy}{dx} = \frac{1}{\cos y}$$
$$\frac{dy}{dx} = \frac{1}{\cos(\arcsin(x))}$$
From the Pythagorean identity $\cos^2 \theta + \sin^2 \theta = 1$, with $x = \sin \theta$, this becomes:
$$\frac{dy}{dx} = \frac{1}{\sqrt{1-x^2}}$$
Comment: Very interesting!  Thank you.
Answer: As an example of where it can be used,
suppose $y={\rm e}^{\theta}$ where $x=f(\theta)$ and
we wish to obtain the derivative of $y\,$ with respect to $x.$ We get
$$\dfrac{{\rm d}y}{{\rm d}x}={\rm e}^{\theta}\,\dfrac{{\rm d}\theta}{{\rm d}x}.$$
The derivative of $\theta=f^{-1}(x)$ with respect to $x$ may be difficult to obtain, but this can easily be avoided by noting that it can be evaluated simply as $$ \dfrac{{\rm d}\theta}{{\rm d}x}=\left(\!\dfrac{{\rm d}x}{{\rm d}\theta}\! \right)^{\!\!-1}, $$so that the derivative ${\rm d}y/{\rm d}x$ is easily obtained as
$$\dfrac{{\rm d}y}{{\rm d}x}=
{\rm e}^{\theta}
\left(\!\dfrac{{\rm d}f(\theta)}{{\rm d}\theta}\!\right)^{\!\!-1},
$$without having to obtain the inverse $\theta=f^{-1}(x).$
Comment: Your example is pretty great too.  Thank you.


Inverters : 12V vs 24V?

Question: Searching on internet i've found some articles like this :
https://earthship360.com/what-is-the-advantage-of-a-24v-system-over-a-12v-system/
that is in favor of higher voltage system.
But on other articles , i've read that is better 12V or there's no significant differencies.
So , Is there any advantage choosing one or other system ?
Thank you !
Comment: Higher voltages are used for running cable over long distances (transmission lines). But no real advantages.
Comment: That earthship360 article appears to be written by a knowledgeable industry professional. Everything in there seems to be accurate. The point about line regulation is that if you lose 1V in a 24V system, that is a small loss (on a percent basis) compared to a 1V loss in a 12V system.
Comment: @Josh Jobin According to that article ,  what about 1) Better input regulation and 2)Better inverter efficiency and regulation ?
Comment: Really depends on the inverter. Do you have inverters in mind?
Comment: ok , what do you think about this 24V inverter : http://powerwalker.com/?page=product&item=10120209⟨=en
Answer: As the inverter power level goes up, 12V inverters become totally impractical due to the required wire diameter. For example, if you have a 4kW inverter, it would be really ridiculous to design it for 12V. 4kW/12V = 433A. Even at 1kW, you are pushing limits with a 12V inverter.
There are a lot of really junky inverters out there. If you see a high power inverter that takes 12V, there is a good chance that it is a piece of junk, and that the ratings are wildly optimistic.
For off grid home use, I would recommend you work with the highest battery voltage that is practical (which is  generally 48V). This will allow you to use more reasonable wire diameters without power loss. Power loss in wire is a function of I squared, so it makes a big difference. And copper is expensive. And fat cables are difficult to work with. Etc.
If you can't or don't want to work with 48V, then 24V is the next best thing.
Comment: The wire size makes a big difference, I have only set up a few solar systems but 48v was the best option, I would use the highest voltage your array can support.+
Answer: There are two issues. A) the inverter itself and B) the cables to connect it to the batteries.
The Inverter
Other things being equal, I would expect the 24v inverter to have a slight efficiency advantage over 12v. This is due to a wider range of FETs being available that will handle the higher voltages, and lower currents in the supply wires. But the difference will be small, and could easily be exceeded by any particular differences of a particular model and manufacturer.
A 12v inverter may well have worse regulation than 124V, though need not have, it depends how much copper has been put in to carry the current. There will always be the temptation to skimp, which will do less harm on a 24v input than 12v.
The Supply
If you want to run the inverter at any distance from the batteries, the difference between (say) 70A at 24v and 140A at 12v will be quite significant. Don't forget double the current will need 4x the copper area for the same power loss in the cables, and fractional regulation at the inverter.
For a fixed system, 24v is the obvious preference over 12v, as it requires less copper to supply it. If you want to be mobile, then you may want to choose 12v for use from a single car battery. If you have the option, then it's worth looking at 48v, less supply copper again.
Comment: Actually , i want to use with pairs of car batteries , never from a car.According to article , what about 1) Better input regulation and 2)Better inverter efficiency and regulation ?
Comment: Thank you for your answer. But please can you explain to me the problems with wires ? Because the batteries are almost in the same place with inverter (20cm  distance ) , and in the output both inverters produce 220V. So for what wires are you speaking ?
Answer: The 24 volt system might be a little more efficient, but the emphasis is on the word little. It's a little bit easier to design for smaller currents, but 2x difference isn't that much after all. Real efficiency benefits would be gained from having a 400 VDC (or something around that - not really sure what the exact voltage should be) system, which would eliminate the need for a step-up stage in power inverters.
12 volts, on the other hand, has the advantage that there's a lot of equipment that can run directly from 12 volts. Stuff like cellphone car chargers, lighting equipment, car televisions etc. And 12 volt equipment such as inverters for example are generally more common and thus cheaper than their 24 volt counterparts. The boost in efficiency in using 12 volt equipment comes from not having to step up and invert the voltage from 12 volts to 110 or 230 volts before being able to use the equipment. You can run lights, watch TV, charge your cellphone and even use a laptop computer without switching on the power inverter.
Possibly dangerous hint regarding laptops here: Many laptops with 18 volt input can be run directly from 12 volts (that happens to be the voltage of their internal batteries). I'm successfully running a couple of low end laptops, for example HP 530 this way at a summer cottage PV system. The laptop constantly shows a systray battery icon, not charging and the charge level stuck at 60%. I don't recommend that you try this with a new or good laptop since I can't guarantee that it won't break up or explode, but you may want to see if you can use your old laptop this way.
Answer: One thing that should be noted, is that it depends somewhat on the grid voltage in your country. In America, where the grid voltage is around 110VAC, your conversion ration is about 1:10. In Europe and in Africa, where we use 230VAC, that ratio is a lot larger, and 24V or even 48V inverters are favoured. Efficiency is usually better for the lower ratios, but as the other answers have noted already, it is only a little better.
The main problem remains the size of your cables. 12V is simply unworkable for anything above about a kilowatt. 24V is good up to about 3 kilowatt, and for anything above that you want 48V.
Cable size isn't the only problem. Parallel battery strings also come with drawbacks, not so much on discharge, but particularly on recharge. If the strings aren't perfectly balanced, one string overcharges while the other(s) is undercharged and dies of sulfation: The worst of both worlds. With a single string, you're limited to maybe 1000Ah. At a C5 rate, that's 200 Ampere, which is around 2.5kw. In other words, high power levels on a 12V system are impossible without parallel strings.
I personally own a 24V Victron Multiplus. I picked 24V for my system as it strikes a good balance between the aforementioned cabling requirements, and the amount of equipment you have to buy. With a 48V system, you have to buy everything in multiples of four. With a 24V system, you buy in multiples of two, which is often much easier on the pocket.
I hope that helps :-)
Comment: I think we are all talking about the required wire diameter for the DC side of the inverter. The current will be half in a 24V inverter compared to a 12V inverter. And that can make a big difference in terms of required fuse and wire diameter. For example, 600 Watts = 50A at 12V, but only 25A at 24V (at 100% efficiency). For 50A, you might need #6AWG wire, but for 25A, you might need #10AWG. The #6AWG is a lot more difficult to deal with.
Comment: Thank you for your answer. But please can you explain to me the problems with wires ? Because the batteries are almost in the same place with inverter (20cm distance ) , and in the output both inverters produce 220V. So for what wires are you speaking ?
Comment: If you are talking for the wires between batteries and inverter , these are wires less than 1 meter. We can get wires with needed diameter , and i don't think we have to spend much more money for just 0.5 meter cable.
Comment: What is the maximum sustained DC current in the wire? What wire gauge do you plan to use? You should calculate the voltage drop in the wire under sustained load conditions. If you end up using large diameter cables to avoid voltage drop, they can be more difficult to terminate or require special tools. That is the only drawback I can see. But make sure you go through the calculations. You definitely are going to need something larger than #12AWG.
Comment: I have 35mm square cables on my 24V 1.6KVA inverter. That is one size oversized, but it is good to oversize to compensate for low battery voltage conditions when current goes even higher. Largest cable you can buy at the local hardware store is around 50mm square. This is on 24V, sized for peaks of 3kw (my inverter can handle that). Now imagine having to double the size of that cable for your 12V inverter :-)
Comment: Sorry , what is the distance between your inverters and the batteries ? My inverter is almost in the same place with batteries. So i need a cable not more than 70-80cm. So the problems is just to find these wires . don't need so much cable.
Comment: Ferdi is right that length of the cable does make a difference. For very short runs, you can get away with a smaller size, but that's literally like "one size down" at best, no more. I'd still be wary though, because the lugs on the cable and the amount of cable making contact with the lug is also important. Acquaintance of mine had the experience of attempting to disconnect a malfunctioning 12V inverter at full power. The smell of burnt flesh is seared into his memory. Don't be cheap. If the run is short, use the right size.
Comment: To answer your other question: My inverter is about 1.5 meters from my batteries. This is also by design: Vented batteries spew forth Hydrogen Suplhide, which is heavier than air, and is also corrosive. You don't want your inverter too close to your batteries (unless they are sealed).
Answer: The only difference I see is reliable current flow. It is all about the wire that passes current. With 12V, the wire has high load, while with 24V, the wire has low load.
Comment: Why should a change of current affect reliability?

Inverters : 12V vs 24V?


Square of the distance in three dimension space

Question:
$|\mathbf r_2 - \mathbf r_1 |^3$ denotes square of the distance that will be the result of position of a point in three dimension space after carrying Pythagorean operation. But why it is cubed. Is it just symbolic of three dimension?
Answer: You can read it as
$$
\frac{1}{|r_2-r_1|^2}\cdot\frac{r_2-r_1}{|r_2-r_1|} = \frac{\widehat{(r_2-r_1)}}{|r_2-r_1|^2}.
$$
The first factor is the inverse square that you're used to, and the second is the normalized direction vector (meaning we divide by the length to make it have a length of 1).
See also https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation#Vector_form
Answer: It is cubed because we want a vector force :
So because the original gravitational is proportional to the inverse squared distance, putting the vector $r_2-r_1$ at the numerator allows to have vector force and compensating by the cubic norm to reach a total of homogeneous inverse squared distance.


how to pass HTTP Header to Junit test case

Question: How do i pass the HttpHeader object to the JUnit test case?
Now i'm writing the test case of my class.I want to pass the HttpHeader object parameter to my test case method to check whether the method is working or not. So any one give me the suggestion to that.
I have googled alot and wasted much time in getting the perfect way.
Thanking you in advance.
Answer: Either create a class that implements the interface, or mock it using a framework like Mockito.


adding fonts to photoshop CS6 run with wine

Question: I have photoshop CS6 installed and working on Wine1.7. It's actually surprisingly smooth. The only issue I have now is that the fonts are a bit limited, and I'm not sure if it's an issue with wine or with the photoshop installation. I tried copying some fonts to the <code>~/.wine/drive_c/windows/Fonts/</code> directory but they are not appearing in photoshop.
What should I do?
Answer: For those still searching for a solution in '17, you should install to the same wineprefix with wine or playonlinux's run exe in this virtual drive function (configure > Miscellaneous / Run a .exe ...) the program from this site:
http://www.ampsoft.net/utilities/FontViewer.php#Download
Comment: Welcome to Ask Ubuntu! I recommend to [edit] this answer to expand it with specific details about how to do this. (See also [How do I write a good answer?](/help/how-to-answer) for general advice about what sorts of answers are considered most valuable on AskUbuntu.)
Answer: you should click on the font , then click install and make restart for the program .


How can I add a panel in kubuntu?

Question: I can't right click in the desktop in kubuntu, so I can't add a panel (I remove all panels to start over the customization)
<code>$ uname -vrpmios

Linux 5.3.0-42-generic #34~18.04.1-Ubuntu SMP Fri Feb 28 13:42:26 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

$ plasmashell --version

plasmashell 5.12.9

$ kf5-config --version

Qt: 5.9.5
KDE Frameworks: 5.47.0
kf5-config: 1.0
</code>
I've created another question regarding right-click issue: Can't right click in desktop anymore
Comment: Which version of Linux have you installed  (Ubuntu server, Ubuntu desktop, Kubuntu, Lubuntu, Xubuntu, Ubuntu MATE, et al.) , and which release number? Please click [edit] and add that vital information to your question so all the facts we need are in the question. Please don't use Add Comment, since that's our channel to you. All facts about your system should go in the Question with [edit]
Answer: Right click in your desktop surface, choose add panel and appears a menu choose add default panel and that's all
Comment: That doesn't work, because I can't right click in my desktop surface, thank you

How can I add a panel in kubuntu?