Load already fetched image when offline in Glide for Android

Question: Am using Glide version 4.8.0
And for loading an image I do this
GlideApp
    .with(HomePageFragment.this)
    .load(remoteURL)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(mImageView);

When the device is connected to Internet the image loades successfully but when device goes offline, how to load the same image from cache that was already featched from the remoteURL?
My CustomAppGlideModule looks like this
@GlideModule
public class CustomAppGlideModule extends AppGlideModule {

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        builder.setMemoryCache(new LruResourceCache(20 * 1024 * 1024));
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, 100 * 1024 * 1024));
    }

}

I also tried
.onlyRetrieveFromCache(true)

But that also does not help.
Comment: can you please try it with Glide.with(mContext)
   .load(url)
   .diskCacheStrategy(DiskCacheStrategy.SOURCE)
   .into(imageView);
Comment: insted of DiskCacheStrategy.ALL use SOURCE
Answer: Option 1:
Use DiskCacheStrategy.SOURCE instead of DiskCacheStrategy.ALL it should work because of DiskCacheStrategy.SOURCE saves the original data to cache.
//Version 4.x
GlideApp
    .with(HomePageFragment.this)
    .load(remoteURL)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .into(mImageView);

//Version 3.x
Glide.with(mContext)
   .load(url)
   .diskCacheStrategy(DiskCacheStrategy.SOURCE)
   .into(imageView);

Option 2: (if above does not work)
Any specific reason for using Glide? Would you like to give a shot to Picasso, I found Picasso much better for this. You may use the following code for offline caching. It will first serve from offline if not found then search for online image.
Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {
      //..image loaded from cache
    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(posts.get(position).getImageUrl())
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {
              //... image loaded from online
            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});

Comment: Thanks for your answer, actually i found the error, it was at some other place. And yes I use glide cause it does not require to resize image for `centerCrop()` and also provide many other built in facilities. AND the most important is the caching mechanism of it.
Comment: oh thanks for sharing the knowledge. Can you please edit the answer, with the solution you found to make this question productive for others. If you found helpful please upvote.


Get Text from Clipboard with Javascript

Question: I want to paste Text into a text area on button click. But I have no idea how to get the text from Clipboard. I want to use codemirror and use the function:
function insertTextAtCursor(editor, text) {
    var doc = editor.getDoc();
    var cursor = doc.getCursor();
    doc.replaceRange(text, cursor);
}

to paste the Text on Button click. Can anybody give me a hint how to get the Text from clipboard?
Comment: Does this answer your question? [Is it possible to paste from clipboard onclick in Javascript?](https://stackoverflow.com/questions/50633601/is-it-possible-to-paste-from-clipboard-onclick-in-javascript)
Comment: check out my [codepen](https://codepen.io/Souleste/pen/ZEzWjyg), includes copying and pasting.
Answer: You can use navigator.clipboard.readText() with browsers that support it.

var editor = CodeMirror.fromTextArea(document.querySelector('textarea'), {
  lineNumbers: true
});

document.querySelector("button").addEventListener("mousedown", function(e) {
  e.preventDefault()
  if (window.navigator) {
    navigator.clipboard.readText().then(setCMText);
  }
});

function setCMText(text) {
  if (editor.getSelection().length) {
    editor.replaceSelection(text);
  } else {
    var doc = editor.getDoc();
    var cursor = doc.getCursor();
    var pos = {
      line: cursor.line,
      ch: cursor.ch
    }
    doc.replaceRange(text, pos);
  }
}
<link href="https://firstname.lastname@example.com/theme/ambiance.css" rel="stylesheet" />
<link href="https://email@example.com/lib/codemirror.css" rel="stylesheet" />

<button>Paste</button>
<textarea>
Hello World
</textarea>

Get Text from Clipboard with Javascript


pandas conditional assignment to multiple columns using .loc

Question: Using pandas version 1.0.5
I have a following dataframe:
test = {'Price': ['Free','free', '-16.66', 'Name', '']}
df = pd.DataFrame(test)
df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

Here in this e.g. if value contains : then I need to split the values and need to assign two parts to two new cols col_1 and col_2 respectively.
But I get this error:
KeyError: "None of [Index(['col_1', 'col_2'], dtype='object')] are in the [columns]"

What am I missing here?
EDIT: I tried without .loc
df[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

And got this error:
TypeError: 'Series' objects are mutable, thus they cannot be hashed

Comment: What is your pandas version? For me working well
Comment: @jezrael `1.0.5`
Comment: It is old version, try upgrade.
Comment: it is version from 2020-06-17, latest is 1.3.4
Comment: Don't use loc. Try to just use df['Price'].astype(str).str.split(':',1,expand = True)
Comment: @GedasMiksenas I have updated the post regarding this.
Answer: If not possible upgrade create columns with empty values:
df = df.assign(col_1=np.nan, col_2=np.nan)

df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

Another idea, thanks @azro working for me if there is at least one value with ::
df[['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

Comment: @azro - hmm, it should working, because append DF, not sure about ol pandad version. But add to answer.
Comment: does something like `df[['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)` may work ? I don't know if there is that kind of syntax, like unpacking
Answer: Check this out :)
test = {'Price': ['Free','free', '-16.66', 'Name', '', "what:yes"]}
df = pd.DataFrame(test)
df[['one', 'two']] = df['Price'].astype(str).str.split(':',1,expand = True)
df.fillna('')

Output:
    Price       one     two
0   Free        Free
1   free        free
2   -16.66      -16.66
3   Name        Name
4
5   what:yes    what    yes


ZF2: using url helper and reuse query parameters

Question: I'm trying to reuse query params using Url helper in a view. This is my current url:
http://localhost/events/index?__orderby=name&__order=asc

I'm using this code in the view:
$this->url('events/index', array('__page' => '2'), true);

I want to obtain this url:
http://localhost/events/index?__orderby=name&__order=asc&__page=2

But instead i get this:
http://localhost/events/index?controller=Application\Controller\Events&__page=2

This is my route inside module.config.php file:
'events' => array(
    'type' => 'segment',
    'options' => array(
        'route' => '/eventos[/:action]',
        'constraints' => array(
            'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
        ),
        'defaults' => array(
            'controller' => 'Application\Controller\Events',
            'action' => 'index',
        ),
    ),
    'may_terminate' => true,
    'child_routes' => array(
        'index' => array(
            'type' => 'Query',
        ),
    ),
),

What am i doing wrong? Thanks for your help.
Comment: try `$this->url('events', array('action'=>'index', '__page' => '2'), true);`
Comment: It doesn't work. It produces the next Url: `http://localhost/events`
Comment: Ah i just noticed, it's the child route. Maybe `$this->url('events/index', array('__page' => 2))` may work - never really worked with query routes. But the child-routes name, which you want to access, is 'events/index' and not just 'events'
Comment: Nope, I'm using `$this->url('eventos/index', array('__page' => '2'))` and still doesn't not work.
Comment: It should be `'events/index'` not `'eventos/index'` you assign the route by their `NAME`. The names you assign are `events` and `events/index`. If this still doesn't work then the Query-Route simply works differently. It might then just work like `$this->url('events/index').'?__page=2` :S
Answer: I think what you are looking for is a Query route type to capture the Query string for you as a child route:
'route' => array(
    'type'    => 'literal',
    'options' => array(
        'route'    => 'page',
        'defaults' => array(
        ),
    ),
    'may_terminate' => true,
    'child_routes'  => array(
        'query' => array(
            'type' => 'Query',
            'options' => array(
                'defaults' => array(
                    'foo' => 'bar'
                )
            )
        ),
    ),

You can then use the view helper to generate and append the query string for you. If you don't use a Query child route, then the helper will just ignore your query string.
$this->url(
    'page/query',
    array(
        'name'=>'my-test-page',
        'format' => 'rss',
        'limit' => 10,
    )
);

You can then set the third parameter to TRUE and allow the helper to use the current parameters as you are trying to do in your example.
There's examples in the docs:
http://framework.zend.com/manual/2.0/en/modules/zend.mvc.routing.html
Comment: Note that the Query route type has been deprecated as of ZF 2.1
Answer: You could use something like this, but the query parameters arent reused in my case.
$this->url(
    'page/query',
    array(),
    array(
        'query' => array(
            'name'=>'my-test-page',
            'format' => 'rss',
            'limit' => 10,
        )
    ),
    true
);

So if you want to reuse query parameters you coul merge them with your new ones and then add all of them to the query array (3 parameter).


Meta-analysis: dealing with bias with a small number of studies

Question: I performed a meta-analysis with 5 RCTs measuring odds ratios of event rates in patients receiving and not receiving a treatment. P of the pooled data resulted > 0.05; this result is acceptable for me.
What is the best way to deal with publication bias? I initially used the Begg test but this method is known to be unreliable for meta-analyses based on a small number of studies. Any suggestions?
Comment: How many studies? What is the actual effect size? Have you made forrest and funnel plots?
Comment: 5 studies, all of them roughly enrolling 100 patients. Odds ratio resulted just above 1; I used fixed effects model. Yes, I made forrest and funnel plots.
Comment: In most situations, its better to use a random-effects model rather than a fixed-effect one. This section in the Cochrane Handbook summarized the empirical evidence on the topic (http://handbook.cochrane.org/chapter_9/9_4_4_3_random_effects_method.htm).
Answer: With such a small number of analyzed trials, all the methods for possible detection of publication bias are underpowered. Therefore instead of claiming that you conducted any of the analyses and did not detect evidence of publication bias, you should state that:
Methods section:
"We intended to assess publication bias using funnel plot techniques, Begg's rank test and Egger's regression test, as appropriate given the known limitations of these methods.
Results section:
"Publication bias was not assessed as there were inadequate numbers of included trials to properly assess a funnel plot or more advanced regression-based assessments."
This is a standard statement I use for Cochrane reviews and teach my students.
Hope this helps.
Ahmed
Answer: You could look here where a couple of other methods are mentioned. However, with so few studies, and all with roughly the same N, your best bet is to present the funnel plot and comment on whether you believe that there is publication bias or not.
You should also be including a description of your efforts to obtain unpublished data from published researchers and by looking up registered studies that were not published.


Continuous Lattices - Confusing passage in Dana Scott's paper

Question: In Dana Scott's paper called "Continuous Lattices" from 1971, I am lost in the following passage. This passage occurs in some exposition after his Proposition 2.4.

Before going any deeper, however, we should clear up another point about topologies. Suppose that $D$ is any $T_0$ space which becomes a complete lattice under its induced partial ordering. Then it is evident from our definitions that every set open in the given topology is also open in the topology induced from the lattice structure. Question: when do the two topologies agree? Answer: A sufficient condition is:
$$y = \bigsqcup \{ \sqcap U  | y \in U\} $$
for all $y$, where $U$ ranges across the given open sets. Because if $V$ is open in the lattice sense and $y \in V$, then $\sqcap U$ ... $V$ is a union of open sets and is thus open in the given topology.

I am completely lost with regards to this passage. Where he says "it is evident from our definitions that every set open in the given topology is also open in the induced topology", I rather have no clue why it is true, and I find it obvious that any set open in the induced topology is open in the original topology!
To explain: I interpret the "induced partial order" as the order imposed on a topology by letting $x \leq y$ iff for all open $U$, $ x\in U \implies y \in U$. He introduces this definition as the first sentence of the second section, "Continuous Lattices." The "induced topology" on a partial order is composed of the sets that are upper sets and are inaccessible from taking the joins of directed sets outside the set.
Scott points out earlier that "every limit of a directed set is a lub, but not every lub is a limit" which is the reason for the induced topology in the first place. It should be nontrivial to show that the original sets of the given topology are all Scott-open even with the assumption that the order forms a complete lattice.
What am I missing? All I want to see is a short explanation of how, if $U$ is an open set of $D$ in the original topology, then a directed set has a join in $U$ iff it eventually enters $U$.
Answer: The answer is simple: Scott made a mistake. In a correction released after the original paper (which can be found appended to the paper as it's published in Toposes, Algebraic Geometry and Logic), he points out that there are a wide variety of counterexamples to his original statement and fixes the proof.


How to draw a label with separator in Install4j Configurable From

Question: In install4j, I'd like to draw a label just like the 'Destination Directory' in the standard screen 'Installation location'
I've tried 'Installation directory chooser', but no such label displayed.
Is there any form component can do this?
Answer: Try the "Horizontal separator" form component with its "Text" property set to the title.


LINQ to Objects - Does Not Contain?

Question: I have a collection of Items that each have a collection of Relationships.  I have a list of Groups that Items can have Relationships with.
I can find all the Items that have a particular relationship but I now want to find all the Items that don't have a Relationship with any of my Groups.
I can find the Items that have a relationship with any of the Groups by doing this:
Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
                 Where item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
                 Select item).ToList

How can I find all the items that do not have a relationship with any of the groups?
Comment: Don't you just want to negate the where clause?
Answer: Have you tried negating the results of the Contains method?
Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
                 Where item.Relationships.Any(Function(r) Not groupIds.Contains(r.TargetID)) _
                 Select item).ToList

Comment: This answer is incorrect. This matches all items that have one or more Relationships that don't match, as opposed to all items that have no matching Relationships.
Comment: This was what I had originally tried, but as Thorarin correctly points out, it returned all of the items in the original group rather than excluding those with any matches.
Answer: I don't remember VB all that well, but a simple "Not" should work.
Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
             Where Not item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
             Select item).ToList

Answer: If you're generating the haveGroup collection anyway then you could just do something like this:
Dim groupIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList

Dim haveGroup = (From item In items _
    Where item.Relationships.Any(Function(r) groupIds.Contains(r.TargetID)) _
    Select item).ToList

Dim haveNotGroup = items.Except(haveGroup).ToList

Answer: Dim notHasGroup = items.Except(haveGroup)

Answer: Dim listIds as List(of Integer) = (From g In cmdbGroups Select g.ID).ToList
Dim haveGroup = (From item In items _
    Where Not listIds.Contains(item.ID)
    Select item.ID).ToList

Comment: Can you please add an explenation to your answer?

LINQ to Objects - Does Not Contain?


Anonymous javascript polling function does not trigger setTimeout ajax call immediately

Question: I have an anonymous polling function which has a setTimeout to kick off a ajax call every 30 seconds.  However, the anonymous function does kick off immediately but for some reason the ajax call does not kick off immediately, but starts only after the 30 seconds.  Am I missing something like calling it immediately to trigger right away?
(function poll() {
        console.log('polling called');
        setTimeout(function () {
            $.ajax({
                url: "/server/call",
                type: 'GET',
                dataType: "json",
                timeout: 30000,
                success: function (data) {
                    var currentdate = new Date();
                    var datetime = "Last Sync: " +                  currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getFullYear() + " @ "
                    + currentdate.getHours() + ":"
                    + currentdate.getMinutes() + ":"
                    + currentdate.getSeconds();

                    console.log(datetime);
                    console.log('call was successful at: ' + datetime);
                }
            });
        },
        30000);
    })();

The logging just starts off only after 30 seconds and not right away.
Thanks
Comment: You're immediately scheduling it for 30 seconds from now. If you want it to run immediately, don't schedule it for 30 seconds from now with `setTimeout`...? Maybe what you want to do is have `poll` immediately make the call, and then delay *future* calls to `poll` by 30 seconds?
Comment: Also, why do you want to trigger it right after your page just got refreshed? - I assume you don't trigger it by a click event...
Comment: @apsillers So instead of setTimeout to poll immediately and how about how to set up future calls?
Comment: @JeroenBellemans The page loads and I want to detect what to display control wise, meaning if buttons or divs needs to be enabled or disabled.  So on page load I want it to check and then keep checking until a status has changed based on the ajax call's response.
Comment: i mean... that's what setTimeout does. it waits.
Comment: @Kevin B As stated before, i want to kick it off immediately then start the timer to start waiting.  I guess I would need to figure to manually kick it off and then start the timer which would require more code then expected.
Comment: Right. so... do that.
Comment: @Kevin B Look I'm trying to learn here, no need to be so condescending and sarcastic about things.
Comment: @Lumpy you already have two answers that do what you ask.
Comment: @Kevin B I'm the person asking the question so if the answers did not work for me in my case, then who are you to tell me if the answer fits my needs?  I did mark Malvolio answer as the correct answer.  Get off your high horse in thinking you can dictate people's actions.  This is a community to learn from one another, not push people around.
Answer: If you are writing some polling function you must send request after previous was complete. The server have to respond to browser after several seconds. In this time server process all other requests. Here is example:

(function poll() {
            console.log('polling called');

            $.ajax({
                url: "/server/call",
                type: 'GET',
                dataType: "json",
                timeout: 30000,
                success: function (data) {
                    var currentdate = new Date();
                    var datetime = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
                        + currentdate.getFullYear() + " @ "
                        + currentdate.getHours() + ":"
                        + currentdate.getMinutes() + ":"
                        + currentdate.getSeconds();

                    console.log(datetime);
                    console.log('call was successful at: ' + datetime);
                },
                complete: function () {
                    setTimeout(function () {
                        poll()
                    }, 200) //do nothing 200ms
                }
            });
        })();

Comment: Looks like running your code snippet, the actual ajax call does not get executed since it does not log out the statements within the success.  It only logs the "polling called" statement.
Comment: Of course it's not :) Because server does not exists :) It's just an example to show how to implement long-polling
Comment: What I meant was it did not work when I implemented it in my environment either.  Sorry for the confusion.  Thanks
Comment: Ah, ok, so what exactly doesn't work? Any error? If request was not successful you can add method to detect what kind of error happened
Comment: I apologize, it was a mistake on my end.  The server request had an error and never returned.  Your solution is a very valid one and should work in all browsers.
Answer: That is not remotely what setTimeout() does.  setTimeout() calls its function, once, and only after the given time has expired.
setInterval() is close to what you want, but even that only calls the function the first time after the interval has expired once.
What you need is to do this:
const everyThree = () =>
            $.ajax({
                url: "/server/call",
                type: 'GET',
...
everyThree();
setInterval(everyThree, 3000);

If you don't like using setInterval(), you can do the same thing manually:
const everyThree = () => {
            setTimeout(everyThree, 3000);
            $.ajax({
                url: "/server/call",
                type: 'GET',
...
everyThree();

If you suspect the AJAX call might run long, you could do the following:
const everyThree = () =>
            $.ajax({
                url: "/server/call",
                type: 'GET',
           ...
           })
           .always(() => setTimeout(everyThree, 3000));

everyThree();

This will make the next AJAX call 3 seconds after the previous one has succeeded, failed, or timed-out.
Edit:
If you don't have const or => ("fat-arrow") in your environment, your choices are

Make do with var and function.  They are inferior in many ways, but universally available.
Use a transpiler like Babel and get all the advantages of a modern language (constants, easy anonymous functions, deconstruction, array-spreading), at the cost of a slight increase in complexity in your operational environment.
Comment: But from what I have been reading, it was not recommended to use setInterval since it can queue up lots of request, and the recommended way was to use anonymous setTimeout instead.
Comment: @Lumpy -- see edit.
Comment: Thanks, looks like it does the job, I'm just unfamiliar with the keyword const in javascript, but doing some reading on immutable variables (http://stackoverflow.com/questions/33040703/proper-use-of-const-for-defining-functions-in-javascript) it would be just to do with scoping.
Comment: Also a note that const is not supported in all browsers unfortunately.
Comment: @Lumpy doesn't make the answer any less valid or useful.
Comment: @Lumpy -- see edit
Comment: @Malvolio Thanks!I've learned some good things here.


Adicionar um item em um array que está dentro de outro array?

Question: Minha dúvida é extremamente simples, adicionar um valor a um array que está dentro de outro.
var logDebug = ["value", [Adicionar itens aqui]]

Answer: Tente este código:

var logDebug = ["value", []];
logDebug[1].push("novo valor 1");
logDebug[1].push("novo valor 2");
console.log(logDebug);
Answer: Só para complementar a resposta do Taffarel, se o array secundário não possuir posição fixa no array principal você pode fazer como no exemplo abaixo para não ter que fazer por exemplo logDebug[1], fazendo um for para percorrer o array principal e comparando para ver se encontra um array com o método Array.isArray()

let logDebug= [1, 2, 3, 4, [], 5];

for(let i=0; i<logDebug.length; i++) {
  let array = Array.isArray(logDebug[i])

  if(array) logDebug[i].push('Qualquer coisa aqui!')
}

console.log(logDebug)
Answer: Ou pode tentar tambem:

let object = [1, 2, 3];
console.log('antes: ' + object);
item = 10;
object.push(item);
console.log('depois: ' + object);

update

let logDebug = [];
logDebug.push({
    value : []
});

let item = 'item';
logDebug[0].value.push(item);
console.log(logDebug);


Enabling SSL in asp.net 4.0 and IIS 7.5

Question: I have created an asp.net 4.0 project. I want to enable SSL for it. Do I need to map this web project to new website in IIS. When I try to create a new website, I get:
The binding '*:80:' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?
I am trying to follow the following posts:
<code>http://weblogs.asp.net/scottgu/archive/2007/04/06/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates.aspx

http://mscrm4humans.wordpress.com/2010/06/24/enabling-ssl-on-iis-7-0-using-self-signed-certificates/
</code>
my IIS is 7.5.7600....
I am totally new to SSL in asp.net. Please suggest solution to this issue.
Answer: It sounds like you created a new site in IIS and are trying to set it to use port 80, which will already be in use by the Default Web Site. If you have nothing in the default site, simply stop it, and you will be able to assign 80 to your project. After that, you can obtain your cert, and apply it to that site.

Enabling SSL in asp.net 4.0 and IIS 7.5


Making responsive navigation for mobile devices

Question: I have this menu. I want to make it optimized for mobile devices like when clicked on toggle button with three bar lines a menu slides in. Can anyone help  me with the simplest way of doing it?
My Menu Code

Home

About Us

Our Gallery

Membership Plans

Register

Contacts

This is working well in desktop and laptop browsers but when I get to mobile responsive mode the menu disappears. Please help me as how can I make a mobile optimized menu with css here.
Comment: What does your css look like for stuck_container wrap?
Comment: do you have access to the css if so please post it so we can help solve the solution.
Comment: Welcome to Stack Overflow, your question should contain [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
Answer: This is a responsive design example you will have to apply this to your code.
I basically set max width of 100%, and a mid width of 180px for small devices on the container holding the list, then i added an exact width and a min width on each list item so when the screen decreases the buttons center for a responsive mobile design.
.linkContainer{
width:100%;
height:2em;
min-width:180px;
margin-left:auto;
margin-right:auto;
}
.navContainer{
width:100%;
min-width:180px;
float:left;
}
li{
width:160px;
min-width:100px;
float:left;
text-align:center;
list-style:none;
}
</style>

Home

About Us

Our Gallery

Membership Plans

Register

Contacts

Answer:

/* Add a black background color to the top navigation */
.topnav {
    background-color: #333;
    overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

/* Change the color of links on hover */
.topnav a:hover {
    background-color: #ddd;
    color: black;
}

/* Add an active class to highlight the current page */
.active {
    background-color: #4CAF50;
    color: white;
}

/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
    display: none;
}

 Home
 About Us
 Our Gallery
 Membership Plans
 Register
 Contacts
  ☰

This one is also responsive . The link with class="icon" is used to open and close the topnav on small screens.
or you could do it like this also : Using MediaQueries

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}
body {margin:0;}

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.active {
  background-color: #4CAF50;
  color: white;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }

}

  Home
  News
  Contact
  About
  ☰

Responsive Topnav Example

Resize the browser window to see how it works.

EDIT
To add a drop down you can apply this code to yours

.message {
background:#181818;
color:#FFF;
position: absolute;
top: -250px;
left: 0;
width: 100%;
height: 250px;
padding: 20px;
transition: top 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
overflow: hidden;
box-sizing: border-box;

}

#toggle {
  position:absolute;
  appearance:none;
  cursor:pointer;
  left:-100%;
  top:-100%;
}

#toggle + label {
  position:absolute;
  cursor:pointer;
  padding:10px;
  background: #26ae90;
width: 100px;
border-radius: 3px;
padding: 8px 10px;
color: #FFF;
line-height:20px;
font-size:12px;
text-align:center;
-webkit-font-smoothing: antialiased;
cursor: pointer;
  margin:20px 50px;
  transition:all 500ms ease;
}
#toggle + label:after {
  content:"Open"
}

.container {
transition: margin 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  padding:5em 3em;
}

#toggle:checked ~ .message {
  top: 0;
}

#toggle:checked ~ .container {
  margin-top: 250px;
}

#toggle:checked + label {
  background:#dd6149;
}

#toggle:checked + label:after {
  content:"Close"
}
<input type="checkbox" name="toggle" id="toggle" />

Comment: In second example where I toggle with a button I want to add a Slide Down effect. How can I?


Does there exist a smooth vector field which is locally the gradient of a function but not globally.

Question: Let $v:\mathbb{R}^n\rightarrow\mathbb{R}^n$ be a smooth vector field such that for any $p\in\mathbb{R}^n$ there exists open set $U_p\ni p$ and $f_p:U\rightarrow \mathbb{R}^n$ such that $\nabla f_p = v|_U$. That is to say, locally the vector field can be expressed as the gradient of a function. Does this imply the existence of a global function $f:\mathbb{R}^n\rightarrow\mathbb{R}^n$ st. $\nabla f = v$? If so I'd like a proof, if not, a counter example, and in either case a pointer to a proof/counter example would suffice. Thanks for the help.
Comment: Since $\mathbb{R}^n$ is simply connected if $v$ is defined on *all* of it then yes, every [irrotational vector field is a gradient](https://en.wikipedia.org/wiki/Conservative_vector_field#Irrotational_vector_fields) (any local gradient is trivially irrotational). But if $v$ is undefined even at one point this is false.
Answer: Yes.  Thinking of $v$ as a $1$-form rather than a vector field, the condition that $v$ is locally a gradient implies that the exterior derivative $dv$ is $0$.  The Poincaré lemma then says there is a smooth function $f$ such that $v=df$; going back to thinking of $v$ as a vector field, this says that $v$ is the gradient of $f$.
Note that for more general domains, this is false.  For instance, identify $\mathbb{R}^2\setminus\{(0,0)\}$ with $\mathbb{C}\setminus\{0\}$ and let $v$ be the vector field that is locally the gradient of the argument function (which is only defined mod $2\pi$, but if you pick a branch then it is locally a smooth function).  Then $v$ is locally a gradient, but not globally, since there is no global argument function (of course it takes some work to make this rigorous).  More generally, if $U\subseteq\mathbb{R}^n$ is open, the space of vector fields that are locally a gradient modulo the space of vector fields that are globally a vector field is naturally isomorphic to the first cohomology group $H^1(U,\mathbb{R})$ (by the de Rham theorem).


Im getting an error in the shell whenever enter is pressed when I'm changing the board size

Question: Have a look at ChangeBoardSize()
It'll be part of the while loop that I have to change but I'm not sure what to change or what to change it to.
I would appreciate any help for this to be done in anyway.
Ignore this but now because I am just trying to get the character count up so that I can post this.
import random

def SetUpGameBoard(Board, Boardsize, PlayerInitials, ComputerInitials):
    for Row in range(1, BoardSize + 1):
      for Column in range(1, BoardSize + 1):
        if (Row == (BoardSize + 1) // 2 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2 + 1):
          Board[Row][Column] = ComputerInitials
        elif (Row == (BoardSize + 1) // 2 + 1 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2):
          Board[Row][Column] = PlayerInitials
        else:
          Board[Row][Column] = " "

def ChangeInitials(PlayerName):
    print("Enter the initials for", PlayerName, "'s piece")
    PlayerInitials = input()
    PlayerInitials = PlayerInitials.upper()
    print("Enter the initials for the computer's piece")
    ComputerInitials = input()
    ComputerInitials = ComputerInitials.upper()
    return ComputerInitials, PlayerInitials

def ChangeBoardSize():
    BoardSize = int(input("Enter a board size (between 4 and 9): "))
    while not(BoardSize >= 4 and BoardSize <= 9):
        BoardSize = int(input("Enter a board size (between 4 and 9): "))
        if BoardSize != [4, 5, 6, 7, 8, 9]:
            ChangeBoardSize()
        elif BoardSize == " ":
            ChangeBoardSize()
    return BoardSize

def GetHumanPlayerMove(PlayerName):
    print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
    Coordinates = input()
    if Coordinates.isdigit():
        MoveValid = True

    return int(Coordinates)

def GetComputerPlayerMove(BoardSize):
    return random.randint(1, BoardSize) * 10 + random.randint(1, BoardSize)

def GameOver(Board, BoardSize):
    for Row in range(1 , BoardSize + 1):
      for Column in range(1, BoardSize + 1):
        if Board[Row][Column] == " ":
          return False
    return True

def GetPlayersName():
    PlayerName = input("What is your name? ")
    return PlayerName

def CheckIfMoveIsValid(Board, Move):
    Row = Move % 10
    Column = Move // 10
    MoveIsValid = False
    if Board[Row][Column] == " ":
      MoveIsValid = True
    return MoveIsValid

def GetPlayerScore(Board, BoardSize, Piece):
    Score = 0
    for Row in range(1, BoardSize + 1):
      for Column in range(1, BoardSize + 1):
        if Board[Row][Column] == Piece:
          Score = Score + 1
    return Score

def CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
    RowCount = StartRow + RowDirection
    ColumnCount = StartColumn + ColumnDirection
    FlipStillPossible = True
    FlipFound = False
    OpponentPieceFound = False
    while RowCount <= BoardSize and RowCount >= 1 and ColumnCount >= 1 and ColumnCount <= BoardSize and FlipStillPossible and not FlipFound:
      if Board[RowCount][ColumnCount] == " ":
        FlipStillPossible = False
      elif Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
        OpponentPieceFound = True
      elif Board[RowCount][ColumnCount] == Board[StartRow][StartColumn] and not OpponentPieceFound:
        FlipStillPossible = False
      else:
        FlipFound = True
      RowCount = RowCount + RowDirection
      ColumnCount = ColumnCount + ColumnDirection
    return FlipFound

def FlipOpponentPiecesInOneDirection(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
    FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
    if FlipFound:
      RowCount = StartRow + RowDirection
      ColumnCount = StartColumn + ColumnDirection
      while Board[RowCount][ColumnCount] != " " and Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
        if Board[RowCount][ColumnCount] == "H":
          Board[RowCount][ColumnCount] = "C"
        else:
          Board[RowCount][ColumnCount] = "H"
        RowCount = RowCount + RowDirection
        ColumnCount = ColumnCount + ColumnDirection

def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
    Row = Move % 10
    Column = Move // 10
    if HumanPlayersTurn:
      Board[Row][Column] = "H"
    else:
      Board[Row][Column] = "C"
    FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0)
    FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0)
    FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1)
    FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1)

def PrintLine(BoardSize):
    print("   ", end="")
    for Count in range(1, BoardSize * 2):
      print("_", end="")
    print()

def DisplayGameBoard(Board, BoardSize):
    print()
    print("  ", end="")
    for Column in range(1, BoardSize + 1):
      print(" ", end="")
      print(Column, end="")
    print()
    PrintLine(BoardSize)
    for Row in range(1, BoardSize + 1):
      print(Row, end="")
      print(" ", end="")
      for Column in range(1, BoardSize + 1):
        print("|", end="")
        print(Board[Row][Column], end="")
      print("|")
      PrintLine(BoardSize)
      print()

def DisplayMenu():
    print("(p)lay game")
    print("(e)nter name")
    print("(c)hange board size")
    print("(i)initials change")
    print("(a)lter piece name")
    print("(q)uit")
    print()

def GetMenuChoice(PlayerName):
    print(PlayerName, "enter the letter of your chosen option: ", end="")
    Choice = input()
    return Choice

def CreateBoard():
    Board = []
    for Count in range(BoardSize + 1):
      Board.append([])
      for Count2 in range(BoardSize + 1):
        Board[Count].append("")
    return Board

def PlayGame(PlayerName, BoardSize, PlayerInitials, ComputerInitials):
    Board = CreateBoard()
    SetUpGameBoard(Board, BoardSize, PlayerInitials, ComputerInitials)
    HumanPlayersTurn = False
    while not GameOver(Board, BoardSize):
      HumanPlayersTurn = not HumanPlayersTurn
      DisplayGameBoard(Board, BoardSize)
      MoveIsValid = False
      while not MoveIsValid:
        if HumanPlayersTurn:
          Move = GetHumanPlayerMove(PlayerName)
        else:
          Move = GetComputerPlayerMove(BoardSize)
        MoveIsValid = CheckIfMoveIsValid(Board, Move)
      if not HumanPlayersTurn:
        print("Press the Enter key and the computer will make its move")
        input()
      MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
    DisplayGameBoard(Board, BoardSize)
    HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
    ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
    if HumanPlayerScore > ComputerPlayerScore:
      print("Well done", PlayerName, ", you have won the game!")
    elif HumanPlayerScore == ComputerPlayerScore:
      print("That was a draw!")
    else:
      print("The computer has won the game!")
    print()

random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
PlayerInitials = 'H'
ComputerInitials = 'C'

while Choice.lower() != "q":    #.lower() makes any allows uppercase input
    DisplayMenu()
    Choice = GetMenuChoice(PlayerName)
    if Choice.lower() == "p":
        PlayGame(PlayerName, BoardSize, ComputerInitials, PlayerInitials)
    elif Choice.lower() == "e":
        PlayerName = GetPlayersName()
    elif Choice.lower() == 'a':
        ChangePieceName()
    elif Choice.lower() == 'i':
        ChangeInitials(PlayerName)
    elif Choice.lower() == "c":
        BoardSize = ChangeBoardSize()

Answer: There is a problem because you don't handle entering characters other than numbers so it fails on line 39
return int(Coordinates) # if Coordinates is not str convertable to int it fails

So you need to do something like
def GetHumanPlayerMove(PlayerName):
    print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
    Coordinates = input()
    if Coordinates.isdigit():
        MoveValid = True
    try:
        return int(Coordinates)
    except ValueError:
        print("Please enter number")
        print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
        return GetHumanPlayerMove(PlayerName)

Or create a while loop like you did below. So
while not isinstance(Coordinates, int): ...

The function will look like this
def GetHumanPlayerMove(PlayerName):
    MoveValid = False
    while not MoveValid:
        print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
        Coordinates = input()
        if Coordinates.isdigit():
            MoveValid = True
    return int(Coordinates)


Construct a Taylor Polynomial of a function containing an integral

Question: I am trying to create a taylor polynomial (degree 5)
of
$(1/x)\int_{0}^{x}e^{-v^{2}} dv$
Now I've created taylor polynomials before, but I've never seen a problem involving two variables.
Comment: To respond to your edit: **yes**, your idea works. The only way it could plausibly fail is if your function $g(x) = \int_{0}^{x} e^{-t^{2}} dt$ had a constant term, which it does not, because it is $0$ when $x=0$.
Answer: Let
$$f(x) = \frac{1}{x}\int_{0}^{x}e^{-t^2}dt$$
then
$$f'(x) = \frac{-1}{x^2}\int_{0}^{x}e^{-t^2}dt+\frac{e^{-x^2}}{x} = \frac{-f(x)}{x}+\frac{e^{-x^2}}{x}.$$
This will give you a recurrence relation to generate successive derivatives with which you could construct your polynomial.
Or something even better, you could change variables and write
$$f(x) = \frac{1}{x}\int_{0}^{x}e^{-t^2}dt$$
as $(t= xu)$
$$f(x)= \int_{0}^{1}e^{-x^2u^2}du = \int_{0}^{1}\sum_{k=0}^{\infty} (-1)^{k}\frac{(xu)^{2k}}{k!}du\\
= \sum_{k=0}^{\infty} \frac{(-1)^{k}x^{2k}}{(2k+1)k!}.$$
Comment: how did you get f'(x)? im  having trouble seeing how the derivative works out
Comment: You apply the product rule with functions $1/x$ and $\int_{0}^{x}e^{-t^2}dt$ which is also a function of $x.$
Comment: You could use the second trick, if you are not comfortable with the Fundamental Theorem of Caclulus (used to differentiate the integral).
Answer: $$e^t=\sum_{n=0}^{\infty}\frac{t^n}{n!}$$
$$e^{-t^2}=\sum_{n=0}^{\infty}\frac{(-1)^{n}(t)^{2n}}{n!}$$
$$\int_{0}^{x}e^{-t^2}dt=\sum_{n=0}^{\infty}\frac{(-1)^{n}(x)^{2n+1}}{(2n+1)n!}$$
so
$$\frac{1}{x}\int_{0}^{x}e^{-t^2}dt=\sum_{n=0}^{\infty}\frac{(-1)^{n}(x)^{2n}}{(2n+1)n!}$$
Comment: @e-h-e where does the 2n+1 come from?
Comment: $\int x^{2n}dx=\frac{x^{2n+1}}{2n+1}$


How do we get this approximation

Question: Show the following relationship:
$\int_{-\infty}^{\infty} \Phi(\lambda x) N(x | \mu, \sigma^2) \, dx = \Phi\left(\frac{\mu}{\sqrt{\lambda^{-2} + \sigma^2}}\right)$
Hint: One way to solve this is to use the definition of $Phi(x) = P[Z \leq x]$.
I have gotten to the point in the Bayesian logistic regression where the integral of the probability distribution is only solvable as this inverse probit. I started off by writing the LHS in full $\int_{-\infty}^{\infty} \left( \int_{-\infty}^{\lambda x} \frac{1}{\sqrt{2\pi}} \exp\left(-\frac{u^2}{2}\right) du \right) \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right) \, dx$
I expect to do some change of variable to convolute the exponentials but can't quite see what to do next.
Comment: Follow this [hint](https://math.stackexchange.com/questions/4859626/integral-involving-the-cdf-of-normal-distribution-from-a-to-b#comment10359239_4859626).
Answer: Let $Y \sim \mathcal{N}(0,1)$ independent of $X \sim \mathcal{N}(\mu, \sigma^2)$. Then
$$\Pr(Y \leqslant \lambda X) = \int_{-\infty}^{\infty} \Pr(Y \leqslant \lambda x) N(x | \mu, \sigma^2) \, dx = \int_{-\infty}^{\infty} \Phi(\lambda x) N(x | \mu, \sigma^2) \, dx.$$
Now, $Y - \lambda X \sim \mathcal{N}(-\lambda\mu, 1 + \lambda^2\sigma^2)$ has cdf $\Phi\left(\frac{\cdot \, + \lambda\mu}{\sqrt{1 + \lambda^2\sigma^2}}\right)$, hence
$$\Pr(Y \leqslant \lambda X) = \Pr(Y - \lambda X \leqslant 0) = \Phi\left(\frac{\lambda\mu}{\sqrt{1+\lambda^2\sigma^2}}\right),$$
and this is equal to the annouced result.

How do we get this approximation


proof with prime numbers that is reflexive, symmetric and transitive

Question: I have found the following problem and try to solve it by myself, but I have some doubts about it. The problem is the following:
A binary relation P is defined on Z as follows: For all $m,n\in \mathbb{Z},mPn\Leftrightarrow \exists$ a prime number p such that p|m and p|n.
Reflexive:
$mPm\Longleftrightarrow \exists p$ such that p|m and p|m, so clearly it holds the reflexive property.
(However, in the solution book it states that this property does not hold, because the author considers m=1, but 1 is not a prime number).
Symmetric:
$mPn\Longleftrightarrow \exists p$ such that $p|m\wedge p|n$
$nPm\Longleftrightarrow \exists p$ such that $p|n\wedge p|m$
Because of the commutative law this symmetric property also holds.
For the transitive property I have seen that it could be fairly straightforward also:
If I have $mPn,nPq$, then I would like to prove that $mPq$
so I take a prime p and I make that $p|m$ and $p|n$ because mPn. Also, I have that $p|n$ and $p|q$ because $nPq$ and I can say that $p|m$ and $p|q$ proving that is transitive.
However, the solution book states that the transitive property does not hold, because considering a counterexample with the following values: m=2,n=6 and p=9. We have that $mPn$ because the prime number 2 divides 2 and 6, then $nPq$ it  holds when I choose 3 as a prime number that divides 6 and 9. However, the transitivity does not hold because 2 cannot divide 9.
The proof by counterexample seems right, but I would like to know if there is some way to prove this transitivity property without using the counterexample. The proof that I found and stated before seemed right, but the counterexample prove it wrong.
Thanks for your help.
Comment: You want to prove something is right, when you already have a proof that it is wrong. If you could do that, you would single-handedly destroy all of mathematics. A better use of your time would be to understand why your argument for transitivity is a fallacious argument. Also, the book is right about reflexivity, and you should try to understand why, again, your reasoning is fallacious.
Comment: Since a lot of people learning discrete math find disproofs by counterexample unsatisfying, I think it's worth emphasizing:  if you want to prove the negation of a universally quantified statement (something like $\neg \forall x P(x)$), producing a counterexample is not informal or nonrigorous at all---it's **exactly what you need to do**.  Reason:  by De Morgan's laws, $\neg \forall x P(x)$ is equivalent to $\exists x (\neg P(x))$.  How does one prove an existential statement?  By constructing an example--in this case, a value of $c$ such that $\neg P(c)$.
Comment: thank you for your comment @Gerry Myerson, I was just curious if it was possible to disprove it in some formal way and not using counterexample. I will review it.
Comment: @Lila I think the main reason everyone(including me) was getting confused  was your repeated use of "proof" when you clearly meant "disproof". I hope my answer helped. Thanks!
Comment: thank you @insipidintegrator it served a lot, now I know that I should use the correct terminology.
Answer: It is NOT transitive. If mPn, it means that $\exists$ a prime p such that p|m and p|n. Also if nPq, it means that $\exists$ a prime b such that b|n and b|q. This need not imply that p=b, the fallacy in your argument.
Also note that the symmetric argument should prove "if mPn, then nPm" and not "mPn and nPm".
 It satisfies the reflexive property for all elements of $\mathbb Z$ EXCEPT 1. So overall not reflexive.
Comment: So you want a more rigorous _dis_proof? Well, a single counter example (as you mention that the author talks about 2, 6 and 9) is enough to completely disprove the statement. I believe that you are in pursuit of a rigorous, well-written set of statements arguing that the transitivity property is false when applied to the given relation, and are not content with the counter example. We prove a statement because we want to show that the statement holds for all possible elements of a specified set. But here we say that it does not hold for all, which is evident from the counter example.
Comment: @GerryMyerson
Comment: thank you for your answer, it was really helpful, but could you expand a little bit the proof of the transitive part, is there any formal way to express it?
Comment: YOU CANNOT PROVE IT. IT IS FALSE. YOU COULD PROVE IT ONLY IF IT WERE TRUE. Do you want me to elaborate on the disproof?
Comment: Please do not write in uppercase because it is somewhat rude in online postings. The issue is that I saw that the author proof it (that it was false), but I was wondering if there was another way to prove it more formally (just for the sake of curiosity).
Comment: thanks for your comment and your time, yes you are right. with the counter example it might seem enough.
Comment: After you were told, several times, Lila, that you can't prove something that has already been proved to be false, you still insisted on asking for a proof of the false statement. In view of that, insipid was more than justified in shouting at you, since mere repetition didn't seem to be getting through. But, insipid, the last word in your answer should be "reflexive", rather than "symmetric".
Comment: @GerryMyerson I think the OP just used instead of disproof. Nothing malicious.
Comment: I'm sure no malice was intended. I'm saying that after being told, repeatedly, that you couldn't prove something you had already disproved, Lila might have taken a moment to wonder why users kept telling her that, and might have figured out why we were doing that, or might have asked us why we were doing that, instead of just continuing as if nothing had happened. Hey, you were the one who shouted at Lila, not me!


Is it correct to refer to a third/fifth/etc even if they're on black keys?

Question: As I understand it, the terms "third", "fifth", "seventh", etc. all refer to the n-th white key relative to the root note.
To demonstrate this, let's observe a C major chord (interval 0-4-7):
Root:  C
third: E (this is the THIRD white key relative to the root)
fifth: G (this is the FIFTH white key relative to the root)

Now let's take a C# major (interval 0-4-7):
Root:  C#
third: F
fifth: G# (This is not a white key)

Because a major chord always has the interval 0-4-7, the 'fifth' (note with interval 7 relative to root) is on a black key.

Is G# still called the 'fifth'?
Does a 'third' always refer to interval 4 and a 'fifth' always refer to interval 7? Even in other scales/keys/modes?
Comment: C#-F-G# would not be C# major, although it would sound exactly the same as if it was.  C#-E#-G# would be C# major.
Comment: Broadly speaking, what distinguishes (say) a major third from a diminished fourth is spelling, not pitch; see @AndrewChin's comment for an example.  Any interval going from any C (Cb, C, C#) up to any G (Gb, G, G#) is a fifth, whether it sounds the same as a perfect fourth or a major sixth.
Answer:
As I understand it, the terms "third", "fifth", "seventh", etc. all
refer to the n-th white key relative to the root note.

This is not correct. The interval distance is determined by the letter name distance which is the number of letters you encounter between the two notes which is very easy to see on a staff. This loops if you go to an octave or above. An example on C would be:

C to C (same octave) 1st (unison or prime)
C to D 2nd
C to E 3rd
C to F 4th
C to G 5th
C to A 6th
C to B 7th
C to C (next octave) 8th (octave)

On the staff it looks like this for C:
X: 1
K: C
L: 1/4
%%score (T1 T2)
V:T1 clef=treble
V:T2 clef=treble
[V:T1] C D E F | G A B c
[V:T2] "1st"C "2nd"C "3rd"C "4th"C | "5th"C "6th"C "7th"C "8th"C

So any C to any D has to be some kind of 2nd. C to F can't be a 3rd because it's a letter distance of a 4th (C to F). To make it a 3rd, you have to convert it to its enharmonic equivalent of E♯ which is a 3rd (a major 3rd to be specific).
Comment: @seamurmurs - for every major and minor scale, there needs to be one of each letter name. With your G minor, there won't be A and A#. That A# is called Bb. Trying to have two same letters will inevitably mess up any interval calculations. In any case, believe it or not, G>A# is a differently named interval from G>Bb.
Comment: @seamurmurs You have a correct idea there: your s, t, u, v, w, x, y are do, re, mi, fa, so, la, te.
Comment: Would it be correct to say: For a given key signature and scale----for convenience, let's call the scale "s, t, u, v, w, x, y" (where, for example, in the case of C major, s=C, t=D, u=E, v=F, w=G, x=A, y=B; in the case of G minor, s=G, t=A, u=A#, v=C, w=D, x=D#, y=F)----s to t is 2nd, s to u is 3rd, .... s to y is 7th?  (e.g. In G minor, G to D# is sixth)?    Do we only speak of 2nd, 3rd, etc. relative to the very first note in the scale, or can we also say A# to D# is fourth in G minor?
Comment: While that's the basic idea @seamurmurs, you seem to be making it more complicated than it needs to be and attaching extra concepts like scales and keys that don't need to be included. A# to D# is a 4th in _any_ key (you would not see either in G minor anyway, but that's a different story). Just count up from any letter name to the one you want to go to. It's so much easier to see on the staff as you can visually see the difference between any interval. In fact recognizing intervals is a big part of sight  reading.
Comment: Tim Thanks, got it (except for the last sentence). Rosie Thanks. In the case of G minor (or any other minor), I pronounce it as la ti do re mi fa so--not sure if that's how others pronounce it (maybe I'm using fixed do by doing so?).
Comment: But what about "suspended" n-ths? I hear terms like "suspended _n-th_" all the time. Does that mean a certain note in a chord is moved up/down a semitone and may end up on black keys?
Comment: @Xunie if you have a new question please ask it so it does not get lost in the comments.
Answer: Don't let the keyboard layout fool you into false premises!
Use the guitar and it should become clear that what you start from in your question is dubious. On guitar there are no 'black' or 'white' notes (keys on piano). And you are probably aware that when you play , say, C E G somewhere, by moving everything up one fret, you get C♯ E♯ G♯. Up to wherever, use the same shape, and you always have a major triad - on whichever strings you choose. And - that F isn't in the triad - it gets called E♯. Honest!
To simplify even more - take your 0-4-7 formula, and use only one string. Let's say open G. 0=G, 4=B, 7=D. now add whatever number you wish to those start numbers, and play. You make that triad again every time, so whatever the note names, 0=root, 4=third (M3) and 7= fifth (P5).
Using the white keys on piano to ascertain intervals isn't always the best approach, as you may now be aware! However, if you insist, then simply count the number of smallest steps (semitones, or each guitar fret) for half the answer. The other half will be revealed once you've established what the lower and upper notes are called. And simply playing them cold, and listening to them aint gonna work! They need to be written down, in a specific key, on a stave. Otherwise they could have  any of two or more different names, depending on situation and their own names.
Just realised I haven't answered the question!
Yes, the black keys work in their own right, just as the white keys do, although they usually have ♯ or ♭ in their names. And when you consider that F is enhamonic with E♯, why shouldn't they? Any black key can be part of any interval, including 3rds and 5ths (and everything else) Yes!
Answer: Yes. The intervals are always relative to the root. There are some interesting cases where there are two possible names for the same interval depending on how the note is named (even though it's the same note). So, for example, with the root C you would call Gb the diminished fifth. The same note spelled F# would be an augmented fourth. Changing the root to C# you get a diminished fifth is G but the augmented fourth will be called F## (and now you know why there are double-sharp and double-flat spellings for notes).
Comment: But is it still correct to use "third", "fifth" or "seventh" when referring to *black keys*? (this is my question, by the way. Sorry to be pedantic.)
Comment: @No'amNewman you cannot just think in terms of semitones for interval. C to D# and C to Eb are both 3 semitones away, but they are two different intervals.
Comment: The question could be seen as 'piano-centric'. I doubt that the question would be asked if the OP were a guitarist as there are no white or black keys on  a guitar! Or on a flute, for that matter.
Comment: @No'amNewman I am a guitarist, though? I'm getting into music theory and I find the terminology to be insultingly circular in non-explanation. Hence, this weird question. -- An important realization here seems to be that most of music theory is based on the chromatic scale and piano keyboard itself. Just look at standard notation! It seems every music theory system is geared towards this and seems horribly broken outside of anything else.
Comment: @Xunie: Think in terms of semitones or frets. A minor third is three frets, a major third is four frets, a fourth is five frets (yes, a guitar is mostly tuned in fourths), an augumented fourth/dimished fifth is six frets, a perfect fifth is seven frets, etc. The actual starting note is irrelevant; what is important is the 'distance', the number of semitones between notes.
Answer: "As I understand it, the terms "third", "fifth", "seventh", etc. all refer to the n-th white key relative to the root note."
Not quite  They refer to the n-th LETTER NAME relative to the lower note.
C - G is a 5th.   So is C♯ to G♯, C♯ to G♭, C double-sharp to G double-flat and any other combination of C and G notes you like to pick (though that last example, C double-sharp to G double-flat, might be difficult to name as what SORT of 5th!)
it's all about spelling.  And spelling is all about what the interval DOES.  In isolation, is the interval from that white note near the piano keyhole to the next-but-two black one C to F♯ or C to G♭?  Or even B♯ to   E double-sharp (OK, unlikely, that one!)    Until the interval has context, until it DOES something, we have no way of knowing.
Comment: The dreaded quadruple-diminished fifth!
Answer:
As I understand it, the terms "third", "fifth", "seventh", etc. all refer to the n-th white key relative to the root note.

Interval naming and sizes aren't specific to an instrument. "...white key relative..." how would that work for non-keyboard instruments? Basically, the intervals are named by the letters and the specific quality comes from the number of half steps between the tones.
You're on the right track with 0-4-7. Those are the interval sizes in half-steps. But that isn't enough to get the interval names. You need to spell it with letters. That part - the spelling with letters - is important and it leads to a mistake in your example.
C# F G# is sized in half steps as 0-4-7, but the intervals are not a third and a fifth, not with the spelling you give. C to F is a fourth of some quality. A perfect fourth would be 5 half steps, but in this case the sharp on C makes the interval one half step smaller, it becomes diminished, so it's a diminished fourth.
If you want to take C E G - interval above root of major third and perfect fifth - and raise it a half step and keep the same interval naming, you spell it C# E# G#. Starting with root C# any third above it must be letter E, accidentals are next applied to size it to the specific kind of third: E# for a major third, E for a minor third, Eb for a diminished third, etc.
Your use of the white key on keyboard effectively serves the purpose of providing letters, but I think it leads to confusion with enharmonic spellings like E# versus F natural...

...that image in truth is wrong. The key labeled F can be F or E# or Gbb, etc. etc. Drop the method of keyboard reference and get comfortable with just reciting the gamut of letters. For practical purposes you want to be able to recite by thirds and fifths in ascending and descending order.
Starting with gamut A B C D E F G...

all fifths are perfect except B,F which is a diminished fifth
all fourths are perfect except F,B which is an augmented fourth
all thirds are major except those encompassing either half-step B,C or E,F
all sixth are major except those encompassing both half-steps B,C and E,F

...then just keep track of any accidentals applied and the corresponding changes in interval quality.


Unable to remove users in Workgroup Manager, they just keep coming back!

Question: When I try to remove a user in the Workgroup Manager on OS X Server 10.6.2, it looks as though the user is removed correctly at first. But when refreshing, the user pops right back into view without any error messages. I can change any attributes of the user, and my current workaround has simply been to disable the accounts that really should be removed.
The only log that seems to report anything at all when I do this is the LDAP Log, which makes sense, unfortunately it's a rather unhelpful message:

slapd[4937]: SASL [conn=22] Failure:
  GSSAPI Error: Unspecified GSS failure.
  Minor code may provide more
  information (Key table entry not
  found)

I googled the error but couldn't really find a solution. Has anyone else seen this before and if so, how did you solve it?
Comment: More info required:
 - In WGM, who are you connecting to your OD server as?  yourself? diradmin?
 - Are you running WGM on the primary OD server, a secondary, or on a client?
 - If on the server, who are you logged in as? admin? yourself? root? diradmin?
 - If on a client, are you connecting to your primary OD server? or are you connecting to a client (ie: localhost) and then changing the directory node?
Comment: In WGM, I'm connecting to the OD server as diradmin. WGM is indeed running on the primary OD server and I'm logged in with administrator priviliges (not diradmin nor root, but a local administrator account). Hope this helps!
Comment: I had a password failure using WGM : didn't recognize the password. A search in the logs : >*GSSAPI Error: Unspecified GSS failure. Minor code may provide more information (Key table entry not found)* and then in google leads me here. I tried John's solution => it worked perfectly ! So thanks for that, John !
Answer: Macke, I had a similar situation in MacOS X Server 10.5.x.

Use a tool like Carbon Copy Cloner and make a good backup of your server.
From the Terminal, run: sudo changeip -checkhostname . If that comes back without issue then try Step 2. If not, repair the underlying issues with the servername/DNS issues.
In ServerAdmin, in OpenDirectory, run a backup (Archive) of the OpenDirectory data. Save it somewhere safe. In fact make 2 copies. Then demote your OpenDirectory Master to a Standalone server. And then reboot. Now, promote it to an OpenDirectory Master. And reboot. And then Restore your OpenDirectory backup. And finally reboot once more.

That should do the trick hopefully
Comment: I accept that sometimes server management is a bit of black magic due to the fact that a lot of different components have to work together and sometimes they simply don't, Workgroup Manager seems to be one of those. However, I'm a bit reluctant to try this out considering the implications it could have. Is there something (safe) I could do to verify that this is indeed the preferred solution for my problem?
Comment: You could use Carbon Copy Cloner to clone your server's HD to an external HD and then use that drive as your boot/server drive and try the change on that copy first.
Comment: I'm gonna do that and see if anything clears up, thanks!
Comment: Sorry for the late reply, but I wasn't able to try until now. Your suggestion worked perfectly, thank you very much!
Comment: Glad to help. BTW, since then I have found a few other ways to fix this, but none of them are pretty as they require editing the data in LDAP...
Comment: Well, this worked out perfectly and was easy and painless to go through. Now that's a solution if I ever saw one =)
Answer: Your error log reminds me of something I encountered recently. Check your DNS settings; make sure forward and reverse lookups are correct. Next, disable SSL for LDAP. Logout of WGM, then back in. If the SASL error goes away, and you can use WGM as intended, then try adding back an SSL cert and see what happens.


HP Smart Array P400 Write Cache not Enabling on VMware ESXi 5.5 Running on ProLiant DL380 G6

Question: I am trying to get write caching enabled on a Smart Array P400 even though there is no battery backup.  We have a large building wide UPS backed up by a generator so the likelihood of loosing power is minimal and the write performance on this VM host server is terrible.  I have installed the HP VMware  drivers and software and I have used hpssacli to turn on write caching and no-battery write cache:
<code>/opt/hp/hpssacli/bin # ./hpssacli controller slot=1 show config detail

Smart Array P400 in Slot 1
   Bus Interface: PCI
   Slot: 1
   Serial Number: PAFGK0P9VX029O
   Cache Serial Number: PA82C0J9VX12T7
   RAID 6 (ADG) Status: Disabled
   Controller Status: OK
   Hardware Revision: E
   Firmware Version: 7.22
   Rebuild Priority: Medium
   Expand Priority: Medium
   Surface Scan Delay: 15 secs
   Surface Scan Mode: Idle
   Wait for Cache Room: Disabled
   Surface Analysis Inconsistency Notification: Disabled
   Post Prompt Timeout: 0 secs
   Cache Board Present: True
   Cache Status: OK
   Cache Ratio: 100% Read / 0% Write
   Drive Write Cache: Enabled
   Total Cache Size: 256 MB
   Total Cache Memory Available: 208 MB
   No-Battery Write Cache: Enabled
   Battery/Capacitor Count: 0
   SATA NCQ Supported: True
   Number of Ports: 2 Internal only
   Encryption Supported: False
   Driver Version: 3.6.14
   Driver Supports HP SSD Smart Path: False

   Internal Drive Cage at Port 1I, Box 1, OK
      Power Supply Status: Not Redundant
      Serial Number:
      Drive Bays: 4
      Port: 1I
      Box: 1
      Location: Internal

   Physical Drives
      physicaldrive 1I:1:7 (port 1I:box 1:bay 7, SATA, 250 GB, OK, spare)
      physicaldrive 1I:1:6 (port 1I:box 1:bay 6, SATA, 250 GB, OK)
      physicaldrive 1I:1:5 (port 1I:box 1:bay 5, SATA, 250 GB, OK)

   Internal Drive Cage at Port 2I, Box 1, OK
      Power Supply Status: Not Redundant
      Serial Number:
      Drive Bays: 4
      Port: 2I
      Box: 1
      Location: Internal

   Physical Drives
      physicaldrive 2I:1:4 (port 2I:box 1:bay 4, SATA, 250 GB, OK)
      physicaldrive 2I:1:3 (port 2I:box 1:bay 3, SATA, 250 GB, OK)
      physicaldrive 2I:1:2 (port 2I:box 1:bay 2, SATA, 250 GB, OK)
      physicaldrive 2I:1:1 (port 2I:box 1:bay 1, SATA, 120 GB, OK)

   Array: A
      Interface Type: SATA
      Unused Space: 0  MB
      Status: OK
      Array Type: Data

      Logical Drive: 1
         Size: 111.8 GB
         Fault Tolerance: 0
         Heads: 255
         Sectors Per Track: 32
         Cylinders: 28722
         Strip Size: 128 KB
         Full Stripe Size: 128 KB
         Status: OK
         Caching:  Enabled
         Unique Identifier: 600508B10010503956583032394F0009
         Logical Drive Label: A0199599PAFGK0P9VX029O81A9
         Drive Type: Data
         LD Acceleration Method: Controller Cache

      physicaldrive 2I:1:1
         Port: 2I
         Box: 1
         Bay: 1
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 120 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K647T8B25P5U
         Model: ATA     GJ0120CAGSP
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 33
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

   Array: B
      Interface Type: SATA
      Unused Space: 0  MB
      Status: OK
      Array Type: Data
      Spare Type: dedicated

      Logical Drive: 2
         Size: 931.4 GB
         Fault Tolerance: 5
         Heads: 255
         Sectors Per Track: 32
         Cylinders: 65535
         Strip Size: 64 KB
         Full Stripe Size: 256 KB
         Status: OK
         Caching:  Enabled
         Parity Initialization Status: Initialization Completed
         Unique Identifier: 600508B10010503956583032394F000A
         Logical Drive Label: A01986FDPAFGK0P9VX029O8FA7
         Drive Type: Data
         LD Acceleration Method: Controller Cache

      physicaldrive 1I:1:5
         Port: 1I
         Box: 1
         Bay: 5
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648TAC28P4N
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 35
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

      physicaldrive 1I:1:6
         Port: 1I
         Box: 1
         Bay: 6
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648T8C25MF2
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 34
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

      physicaldrive 2I:1:2
         Port: 2I
         Box: 1
         Bay: 2
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648T8C25MFW
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 35
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

      physicaldrive 2I:1:3
         Port: 2I
         Box: 1
         Bay: 3
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648T8B25M9W
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 35
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

      physicaldrive 2I:1:4
         Port: 2I
         Box: 1
         Bay: 4
         Status: OK
         Drive Type: Data Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648T8C25ML9
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 35
         Maximum Temperature (C): 58
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps

      physicaldrive 1I:1:7
         Port: 1I
         Box: 1
         Bay: 7
         Status: OK
         Drive Type: Spare Drive
         Interface Type: SATA
         Size: 250 GB
         Native Block Size: 512
         Firmware Revision: HPG2
         Serial Number: K648T8C25MK0
         Model: ATA     GJ0250EAGSQ
         SATA NCQ Capable: True
         SATA NCQ Enabled: True
         Current Temperature (C): 31
         Maximum Temperature (C): 57
         PHY Count: 1
         PHY Transfer Rate: 1.5Gbps
</code>
But as you can see, the cache ratio is 0% for writes.  What am I missing?
Answer: It looks like this looks like what you are looking for:
<code>ctrl slot=0 cacheratio=50/50
</code>
source: https://community.hpe.com/t5/ProLiant-Servers-ML-DL-SL/Smart-Array-Controller-P400-cache-ratio/td-p/4018686
Comment: That was it, thanks!  For clarity, the actual command is /opt/hp/hpssacli/bin/hpssacli controller slot=1 modify cacheratio=50/50.
Answer: This is a tacky solution.
The HP Smart Array P400 doesn't really honor the no-battery cache override setting.

But the use of a Smart Array P400 means you're using an HP ProLiant G5 server...
Which means you're using something from the 2005-2008 era... 10 years old.
Which indicates that you're running something that VMware doesn't support anymore...
And SATA drives downshift their speed to 1.5Gbps (instead of 3Gbps or 6Gbps) on that controller; half the speed of a SAS drive...
Which means your performance is going to be really, really poor... even WITH write cache.

You could try to find a battery, but the server is so old that nobody had a stock of new healthy batteries.
And since the street value of a server of that generation is about $100, it's a tough use case.
Are you sure you want to run this particular server?
Comment: It is an old server that runs some non-essential VMs.  Mostly testing and monitoring stuff.  I am going to replace it next budget cycle but I'm just trying to get a little better performance out of it until then.
Comment: I understood that this hardware was old, maybe not as specifically as you. I am just starting out on this site, so I am trying to understand the best way to handle things. Should I not help a user if it is "not worth working on"? He seems to understand the risks of no battery cache, and just wanted help with the ratio issue.


Como decidir o tipo de uma função?

Question: Em muitos códigos escritos C em que eu vejo na internet eu só vejo funções do tipo void e int e possível declarar funções de outros tipos? Por exemplo struct e float.
Eu fiz um teste simples com os tipos char e float e funcionou, mas eu ainda não entende a verdadeira importância do tipo da função quando eu devo usar qual?
#include <stdio.h>
#include <stdlib.h>

float rf(){

    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);

}

char rc(){

    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);

}

int main(){

 rf();
 rc();
 return 0;

}

Comment: Você pode declarar funções que retornam qualquer tipo de dados. Só que acho que você não entendeu muito bem o que é retorno na função, já que suas função não retornam nada.
Comment: @Assanges a unica função do seu exemplo que retorna algo (no caso `0`) é o main. O resto não tá retornando nada.
Comment: as funcoes retornan o que esta contido nelas @JoãoSobral
Answer: Na verdade a função não tem tipo, quem tem tipo é o valor que ela retorna. Isso sim é importante.
O retorno, assim como os parâmetros, variáveis, constantes, etc. podem e devem ter qualquer tipo disponível no código, pode ser um já definido na linguagem, na bibliotecas padrão, em outras bibliotecas que esteja usando, ou tipos definidos pelo seu código (com typedef e provavelmente struct).
Obviamente que a função deve retornar algo com o comando return e o valor retornado deve ser compatível com o tipo de retorno declarado nela.
Se for pra retornar nada, então o tipo de retorno deve ser void. Assim a função não poderá ser usada em expressões que sempre esperam algum valor. void é nenhum valor, é "menos" do que nulo.
Você deve usar o que seja mais adequado para resolver o problema. Nenhuma resposta genérica poderá determinar qual é o mais adequado para a situação específica.
É claro que algumas coisas a gente sabe. Um tipo deve comportar todos os valores válidos que sabe que aquele elemento do código pode ter. Por exemplo, se declarar um int, provavelmente (depende de arquitetura), o maior valor possível é 2.147.483.647.
Em alguns raros casos pode precisar de um tipo não sinalizado (que só aceita positivos), é raro e não vem ao caso aqui porque não deve optar por eles como padrão.
Se precisa de um valor monetário o programador novato vai quente no float ou double (que permitem valores com parte decimal), mas não pode usá-los para isso.
Enfim, são só exemplos, não dá para colocar todas regras básicas sob pena da pergunta ficar muito ampla.
O exemplo ligeiramente melhorado de acordo com minha especulação:
#include <stdio.h>

float rf() {
    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);
    return testfloat;
}

char rc() {
    float testfloat = 1.3;
    char string[]; //havia um erro aqui e isso ainda não vai dar certo
    printf("'%f' '%s'", testfloat, string);
    return 'a';
}

void rv() {
    printf("faz algo aqui");
    return;
}
int main() {
    float x = rf();
    char c = rc();
    rv();
}

Coloquei no GitHub para referência futura.
Comment: no caso se eu implimentar uma funcao que retorne uma struct eu poderia criar uma especie de classe bacana gostei +1  pela resposta

Como decidir o tipo de uma função?


Construction of irrational numbers

Question: Can an irrational number be constructed which is a) not any known transcendental number b) not a surd?
If yes, then how can I construct one?
A detailed answer regarding the theory behind this and some references will be appreciated.
 I modified the a) part to what it is now, because I am guessing numbers are either algebraic or not algebraic(I.e. transcendental). Is this correct?
I am thinking along the lines of constructing a sequence which converges to the desired number, but then  how to construct a sequence to a desired limit?
Comment: What is a known transcendental number BTW?
Comment: What do you mean by a surd? If you mean something you can write down in terms of $n^{th}$ roots then the answer is yes. Some quintic polynomial should work.
Comment: Err, e or pi or golden ratio?
Comment: @user286490 e and pi are transcendental and the golden ratio is a surd
Comment: Oh okay, and yes, by surd I mean what you.
Comment: Okay, I think the question can be reduced to "construction of transcendental numbers"
Comment: You are correct that numbers are either algebraic or transcendental (i.e. not algebraic)
Answer: The answer is yes. If you know about Galois theory, you need an extension of $\mathbb{Q}$ that has a non-solvable Galois group (like $S_5$). If you don't know about Galois theory, then the roots of the polynomial $x^5-80x+5$ are irrational numbers but they are not surds and not transcendental.
Comment: Okay, but can I know what the number looks like?
Comment: Is it possible to prove that the roots are not surds without knowledge of Galois theory?
Comment: @cr001 I don't know of any way to show that the roots are not surds without using Galois theory. I think it would be quite difficult.
Comment: @user286490 what do you mean by what the number looks like? You could use a CAS or wolfram to get approximate complex roots of the equation. Another polynomial that will work is in [this link](https://en.wikipedia.org/wiki/Galois_theory#A_non-solvable_quintic_example)
Comment: @Sam Weatherhog Thanks. But using Galois theory there is a way of proving numbers are not surds?
Comment: The problem with it not being a surd is that it is difficult to write the numbers precisely any other way. The best you can really do is to say they are roots of some polynomial.
Comment: @cr001 yes one of the major driving factors for the development of Galois theory was to answer this question. The Galois theory answer to it is that if the Galois group of the extension is solvable then the polynomial can be solved in terms of radicals (surds). See [this link re solvability](https://en.wikipedia.org/wiki/Galois_theory#A_non-solvable_quintic_example)
Comment: Thank you very much for answering my comments.

Construction of irrational numbers


How to change input type of sap.ui.input control. I have done as per documentation but it is not reflecting in view

Question: I want to change input type from password to text.
What i have done:
1) In xml view:
<input type="Password" id="idPassword" showValueHelp="true" /> // enabling showValueHelp a button right corner in input text

2) In controller :
var oInput = this.getView().byId("idPassword");
oInput.attachValueHelpRequest(function(){
oInput.type = "Text"; //change input type as per documentation.
console.log(oInput); // I can see type="Text" in console
});

Actually It is not reflecting in browser.
Answer: There is not method called type.You should use
oInput.setType("Text");

or
oInput.setType(sap.m.InputType.Text);

Note:default type is Text.So you dont have to set it at all
Comment: "type" is property of sap.m.input control. Yes, default is "Text". I am trying to change it from "Password" to "Text" when user click on help indicator.


Use old raid drive as boot device without data loss

Question: There were two disks in sw-raid. There were /dev/md1 as swap, /dev/md2 as boot and a /dev/md3 with ext4.
The sw-raid was disabled by stopping and removing mdadm and then zeroing the superblock on each /dev/mdX partition with:
sudo mdadm --zero-superblock /dev/sda1
sudo mdadm --zero-superblock /dev/sda2
sudo mdadm --zero-superblock /dev/sda3

In the disk that is the first boot device, I don't know if it's relevant, the system type of each partition was set back from fd to 82 or 83 with fdisk, /etc/fstab was updated, changing /dev/mdX to /dev/sdaX, and grub was reinstalled on the boot partition (/dev/sda2) with grub-instal. But the system wont boot.
What else should I do to use this disk as the boot device without reinstall or data loss?
Current output of fdisk
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048    33556480    16777216+  82  Linux swap / Solaris
/dev/sda2   *    33558528    34607104      524288+  83  Linux
/dev/sda3        34609152  3907027120  1936208984+  83  Linux

With it doesn't boot I mean that it stops in the grub console (with the grub> symbol). A ls command says:
(hd0) (hd0,msdos3) (hd0,msdos2) (hd0,msdos1) (hd1) (hd1,msdos1)

It's weird because hd1 was formatted with ext4...
Comment: That would normally be enough, in my experience (thought I'm not sure about the zeroing-the-superblock bit - how did you do that?).  Could you be more precise about what the system does when "*the system won't boot*"?
Comment: OK on the superblock-zeroing.  Is `/dev/sda2` tagged as bootable in the partition table?  And I repeat my question about *how* it fails to boot.
Comment: Added the command used. I can't really see what happens on boot, I only have access via ssh. All I know is that I can't connect after reboot (it was working perfectly before). Now I'm using a rescue system.
Comment: Yes, it is. Added the output of fdisk.
Comment: Without console access, or at least a pair of eyes on it, this will be very, very hard to diagnose.  Should I take your comment about a "rescue system" to mean that this is a virtualised system?
Comment: It's a physical system, a dedicated server. Added what happens after boot.
Answer: At the end, it was a problem of the grub installation. I ran grub from the mounted fs (the rescue system didn't have the grub command) and the did:
grub> root (hd0,1)
grub> setup (hd0)


Dúvida na implementação da função ode45 do Matlab

Question: Nunca utilizei a função ode45 do Matlab. Abaixo a função e o programa que desenvolvi, alguém, por gentileza, pode me ajudar a encontrar os erros?
-Função
function di=didt(t,i,flag,R,L,v,f,Rsec)
i1=i(1);
i2=i(2);
A=L;
D=L*R;
w=2*pi*f;
di(1)=A(1,1)(vcos(w*t))+A(1,2)Rseci2+A(1,3)*((D(3,1)*i1+D(3,2)i2...
    -A(3,1)(vcos(wt))-A(3,2)Rseci2)/A(3,3))-D(1,1)*i1-D(1,2)i2;
di(2)=A(2,1)(vcos(wt))+A(2,2)Rseci2+A(2,3)*((D(3,1)*i1+D(3,2)i2...
    -A(3,1)(vcos(wt))-A(3,2)Rseci2)/A(3,3))-D(2,1)*i1-D(2,2)*i2;
di=[di(1) di(2)]';
end
-Programa
% Definição dos parâmetros
R=[2.1581 0 0; 0 0.0114 0; 0 0 0.0556];
L=[8.7492 -8.7828 0.0336; -8.7828 12.3082 -3.5254; 0.0336 -3.5254 3.4918];
f=1e3;
v=10e3;
Rsec=100;
i10=0;
i20=0;
% Tempo de simulação
t=[0 10e-3];
[t,i]=ode45('didt',t,[i10 i20],[],R,L,v,f,Rsec)
figure(1)
plot(t,i(:,1), t,i(:,2))
Comment: Por favor especifique o que você quer fazer com seu programa.
Comment: @FábioPerez preciso encontrar as correntes i1 e i2 usando a função ode45 do Matlab.
Answer: Há diversos problemas de digitação da sua definição da função e para ter certeza da resposta seria necessário que mostrasse o modelo original que está tentando simular. Tentando fazer uma correção prévia sem essa informação, um programa que funciona é o seguinte:
Definição do sistema:
function di=didt(t,i,R,L,v,f,Rsec)

i1=i(1); i2=i(2); A=L; D=L*R; w=2*pi*f;

di(1,1)=A(1,1)*(v*cos(w*t))+A(1,2)*Rsec*i2+A(1,3)*((D(3,1)*i1+D(3,2)*i2...
    -A(3,1)*(v*cos(w*t))-A(3,2)*Rsec*i2)/A(3,3))-D(1,1)*i1-D(1,2)*i2;
di(2,1)=A(2,1)*(v*cos(w*t))+A(2,2)*Rsec*i2+A(2,3)*((D(3,1)*i1+D(3,2)*i2...
    -A(3,1)*(v*cos(w*t))-A(3,2)*Rsec*i2)/A(3,3))-D(2,1)*i1-D(2,2)*i2;

end

Programa para a simulação:
% Definição dos parâmetros
R=[2.1581 0 0; 0 0.0114 0; 0 0 0.0556];
L=[8.7492 -8.7828 0.0336; -8.7828 12.3082 -3.5254; 0.0336 -3.5254 3.4918];
f=1e3; v=10e3; Rsec=100; i10=0; i20=0;

% Tempo de simulação
ts=[0 10e-3];

[t,i]=ode45(@(t,y) didt(t,y,R,L,v,f,Rsec),ts ,[i10 i20])
figure(1)
plot(t,i(:,1), t,i(:,2))

Note que havia o parâmetro flag não utilizado e que para chamar a função ode45 com parâmetros auxiliares para a função é necessário definir uma função anônima como foi feito ali @(t,y) didt(t,y,R,L,v,f,Rsec).


metatag_display_extender plugin does not exist

Question: I am migrating a Drupal site over, the following error is being received... I have clear cache, did a rebuild and no luck. Any suggestions

The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The
"metatag_display_extender" plugin does not exist. Valid plugin IDs for
Drupal\views\Plugin\ViewsPluginManager are: default in
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 53 of
core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('metatag_display_extender')
(Line: 16)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('metatag_display_extender',
Array) (Line: 83)
Drupal\Component\Plugin\PluginManagerBase->createInstance('metatag_display_extender')
(Line: 161)
Drupal\views\Plugin\views\display\DisplayPluginBase->initDisplay(Object,
Array) (Line: 91)
Drupal\views\DisplayPluginCollection->initializePlugin('default')
(Line: 38) Drupal\views\DisplayPluginCollection->__construct(Object,
Object) (Line: 728) Drupal\views\ViewExecutable->initDisplay() (Line:
1754) Drupal\views\ViewExecutable->access('page_1') (Line: 60)
Drupal\views\Element\View::preRenderViewElement(Array)
call_user_func_array(Array, Array) (Line: 100)
Comment: Hey acctman, please always try to include the steps that need to be performed to reproduce this issue. What exactly have you done before you ran into the error? How did you migrate? What did you migrate? `Any suggestions` is a too broad question and the only answer to it is: Debug! And then edit your question and add debugging info as well. Many thanks
Answer: I had this issue when trying to add metatag_views to an install profile.
I fixed this issue by adding a config dependency on metatag_views to the top of views.settings.yml:
dependencies:
  module:
    - metatag_views

There's more information on this Drupal.org issue.


Value from ajaxified form field not passed to ajax callback

Question: This is a continuation of this issue, where I couldn't get the ajax to fire on an entity reference field in a node edit form. With the following code, I'm able to get the ajax to fire.
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function mymodule_form_blog_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_video_reference']['#ajax'] = array(
    'callback' => 'mymodule_video_ajax_callback',
    'wrapper' => 'my-path-div',
  );

  $form['my_path'] = array(
    '#markup' => t('My path'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#weight' => 6,
  );

  if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = 'Token path: http://www.mysite.org/node/' . $form_state['node']->field_video_reference['und'][0]['target_id'];
  }
}

function mymodule_video_ajax_callback($form, $form_state) {
  return $form['my_path'];
}

The problem is that the value from field_video_reference isn't being passed to the if statement in the form builder or my callback, so the value from that field isn't displayed in the my_path field when the value is first selected on the node create form (it works fine if the node has already been saved and there is a value in field_video_reference when I edit the node). I'm following examples from the "Drupal 7 Module Development" book as well as from the Examples module, so I can't see what I'm missing.
Thanks.
Answer: $form_state['values']['field_video_reference']['und'][0]['target_id'] looks wrong to me.
I would expect the value to be in $form_state['values']['field_video_reference'].
If you haven't already then install the Devel module and then use can use dpm($form_state); to output the array to the message area and inspect it to find the correct path.
Sometimes for ajax requests Devel Debug Log is also useful as it allows you to send a dump of a variable to a log so you can inspect it even if it is not possible to send content to the message area.
Comment: With Xebug and PHPStorm, I've used my debugger to inspect every available variable in just about every place possible.
Answer: Try to replace with the code
if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = t('Token path: http://www.example.com/node/' . $form_state['node']->field_video_reference['und'][0]['target_id']);
  }

The issue was that you need to put every content of #markup into the t('text') function.


Ajax to Webservice Asmx file returns Xml value but need json value

Question: Simple HTML button in asp.net page when clicks the button the Ajax code pass the call to service page method and return the value but in XML format need it in json
Ajax Code
$(document).ready(function(){
    $("#btnSubmit").click(function(){
        txtNameValue = $("#txtName").val();
       alert("button clicked");

        $.ajax({
        type: "POST",
        url: serviceURL+"/HelloWorld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success:function(response) {

            console.log(response);
        }
        });

    });
});

Service Page code
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

///
/// Summary description for FirstPageWebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[ScriptService]
public class FirstPageWebService : System.Web.Services.WebService {

    public FirstPageWebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld() {

        return "Hello World";
    }

}

In HTML page when tracks through networks Got this response in XML

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

Comment: `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]` un comment this line
Comment: no response page with some errors
Comment: What are the errors ?
Comment: need to return json value
Comment: ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the [ASMX Forum](http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/threads) on MSDN.
Answer: You can use JavaScriptSerializer in your service method :
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize("Hello World");


DateTimeFormatter throwing exception "could not be parsed at index 0"

Question: I keep on getting an error from running this code.
java.time.format.DateTimeParseException: Text 'Jan 03, 2020' could not be parsed at index 0
final String myFormat = "LLL dd, yyyy"; //sets format in which to show date (same as how its saved in database) ex. Jan 29, 2020
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(myFormat);

String startingBiWeeklyCheck = sharedPreferences.getString("biweekly start", "Jan 03, 2020");
            LocalDate startingDate = LocalDate.parse(startingBiWeeklyCheck, dateFormatter);

Ive played around with the format but I'm not seeing why the pattern "LLL dd, yyyy" doesn't parse Jan 03, 2020
Answer: You should use MMM instead of LLL for month parsing.
Updated:
I was wrong about my answer above. It's the half of answer.
The deal is DateTimeFormatter.ofPattern(myFormat) uses default Locale.
For non-US locales, it doesn't work.
So you need to specify the locale according to your pattern.
DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)

Comment: changing the format to "MMM dd, yyyy" is throwing the same exception.
Comment: Check your `startingBiWeeklyCheck` variable output. It should always return a string with the same pattern as you specified in `myFormat`
Comment: By the way, what's your locale? Try also set `DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)`
Comment: @Ole V.V. It's actually interesting because take look the [doc](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)
`M/L     month-of-year               number/text       7; 07; Jul; July; J`. So the L represents number and M represents text value. On my `AdoptOpenJDK 1.8.0_262-b10` it's vise versa!
Comment: Here is my output https://pastebin.com/MnrFwJrb
Comment: I've just mentioned that's the question marked as duplicated and https://stackoverflow.com/questions/30518954/datetimeformatter-month-pattern-letter-l-fails has an explanation about this behavior.
Comment: I admit that the documentation that you quote is easy to misunderstand. `MM` and `LL` are both month number. `MMM` and `LLL` are both month abbreviations, only in a few languages they are different forms. The documentation also says: "**Number/Text:** If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above."


Series with elements from an uncountable set

Question: Let $S$ be a given uncountable set in which all elements are positive real numbers.
Is it necessary that the set: { $\sum a_n |a_n\in S, a_i\neq a_j$ if $i\neq j$ } be unbounded? I mean can we find an uncountable set with positive elements such that the set of all series with distinct elements have an upper bound?
Comment: An uncountable subset of $\mathbb R$ has uncountably many accumulation points. So there is a positive sequence of real numbers converging to some $x>0$. Sum of these numbers must be infinite.
Answer: As $S$ is uncountable and $\mathbb{R}$ has a countable base, $S$ has uncountably many limit points in $S$. If $p \in S$ is one of them, take $p_n \in S$ all distinct such that $p_n \to p$, in particular we can find infinitely many close to $p$ such that the $\sum_n (p_n -p)$ absolutely converges in the reals, which implies that $\sum_n p_n$ diverges to $+\infty$.